function _mergeNamespaces(n, m2) {
  for (var i2 = 0; i2 < m2.length; i2++) {
    const e2 = m2[i2];
    if (typeof e2 !== "string" && !Array.isArray(e2)) {
      for (const k2 in e2) {
        if (k2 !== "default" && !(k2 in n)) {
          const d = Object.getOwnPropertyDescriptor(e2, k2);
          if (d) {
            Object.defineProperty(n, k2, d.get ? d : {
              enumerable: true,
              get: () => e2[k2]
            });
          }
        }
      }
    }
  }
  return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { value: "Module" }));
}
(function polyfill() {
  const relList = document.createElement("link").relList;
  if (relList && relList.supports && relList.supports("modulepreload")) return;
  for (const link of document.querySelectorAll('link[rel="modulepreload"]')) processPreload(link);
  new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type !== "childList") continue;
      for (const node of mutation.addedNodes) if (node.tagName === "LINK" && node.rel === "modulepreload") processPreload(node);
    }
  }).observe(document, {
    childList: true,
    subtree: true
  });
  function getFetchOpts(link) {
    const fetchOpts = {};
    if (link.integrity) fetchOpts.integrity = link.integrity;
    if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy;
    if (link.crossOrigin === "use-credentials") fetchOpts.credentials = "include";
    else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
    else fetchOpts.credentials = "same-origin";
    return fetchOpts;
  }
  function processPreload(link) {
    if (link.ep) return;
    link.ep = true;
    const fetchOpts = getFetchOpts(link);
    fetch(link.href, fetchOpts);
  }
})();
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function getDefaultExportFromCjs(x2) {
  return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
}
var jsxRuntime = { exports: {} };
var reactJsxRuntime_production_min = {};
var react = { exports: {} };
var react_production_min = {};
var hasRequiredReact_production_min;
function requireReact_production_min() {
  if (hasRequiredReact_production_min) return react_production_min;
  hasRequiredReact_production_min = 1;
  var l2 = /* @__PURE__ */ Symbol.for("react.element"), n = /* @__PURE__ */ Symbol.for("react.portal"), p2 = /* @__PURE__ */ Symbol.for("react.fragment"), q2 = /* @__PURE__ */ Symbol.for("react.strict_mode"), r2 = /* @__PURE__ */ Symbol.for("react.profiler"), t2 = /* @__PURE__ */ Symbol.for("react.provider"), u2 = /* @__PURE__ */ Symbol.for("react.context"), v2 = /* @__PURE__ */ Symbol.for("react.forward_ref"), w2 = /* @__PURE__ */ Symbol.for("react.suspense"), x2 = /* @__PURE__ */ Symbol.for("react.memo"), y = /* @__PURE__ */ Symbol.for("react.lazy"), z2 = Symbol.iterator;
  function A(a2) {
    if (null === a2 || "object" !== typeof a2) return null;
    a2 = z2 && a2[z2] || a2["@@iterator"];
    return "function" === typeof a2 ? a2 : null;
  }
  var B2 = { isMounted: function() {
    return false;
  }, enqueueForceUpdate: function() {
  }, enqueueReplaceState: function() {
  }, enqueueSetState: function() {
  } }, C = Object.assign, D2 = {};
  function E2(a2, b2, e2) {
    this.props = a2;
    this.context = b2;
    this.refs = D2;
    this.updater = e2 || B2;
  }
  E2.prototype.isReactComponent = {};
  E2.prototype.setState = function(a2, b2) {
    if ("object" !== typeof a2 && "function" !== typeof a2 && null != a2) throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");
    this.updater.enqueueSetState(this, a2, b2, "setState");
  };
  E2.prototype.forceUpdate = function(a2) {
    this.updater.enqueueForceUpdate(this, a2, "forceUpdate");
  };
  function F2() {
  }
  F2.prototype = E2.prototype;
  function G2(a2, b2, e2) {
    this.props = a2;
    this.context = b2;
    this.refs = D2;
    this.updater = e2 || B2;
  }
  var H2 = G2.prototype = new F2();
  H2.constructor = G2;
  C(H2, E2.prototype);
  H2.isPureReactComponent = true;
  var I2 = Array.isArray, J2 = Object.prototype.hasOwnProperty, K2 = { current: null }, L2 = { key: true, ref: true, __self: true, __source: true };
  function M2(a2, b2, e2) {
    var d, c = {}, k2 = null, h2 = null;
    if (null != b2) for (d in void 0 !== b2.ref && (h2 = b2.ref), void 0 !== b2.key && (k2 = "" + b2.key), b2) J2.call(b2, d) && !L2.hasOwnProperty(d) && (c[d] = b2[d]);
    var g2 = arguments.length - 2;
    if (1 === g2) c.children = e2;
    else if (1 < g2) {
      for (var f2 = Array(g2), m2 = 0; m2 < g2; m2++) f2[m2] = arguments[m2 + 2];
      c.children = f2;
    }
    if (a2 && a2.defaultProps) for (d in g2 = a2.defaultProps, g2) void 0 === c[d] && (c[d] = g2[d]);
    return { $$typeof: l2, type: a2, key: k2, ref: h2, props: c, _owner: K2.current };
  }
  function N2(a2, b2) {
    return { $$typeof: l2, type: a2.type, key: b2, ref: a2.ref, props: a2.props, _owner: a2._owner };
  }
  function O2(a2) {
    return "object" === typeof a2 && null !== a2 && a2.$$typeof === l2;
  }
  function escape2(a2) {
    var b2 = { "=": "=0", ":": "=2" };
    return "$" + a2.replace(/[=:]/g, function(a3) {
      return b2[a3];
    });
  }
  var P2 = /\/+/g;
  function Q2(a2, b2) {
    return "object" === typeof a2 && null !== a2 && null != a2.key ? escape2("" + a2.key) : b2.toString(36);
  }
  function R(a2, b2, e2, d, c) {
    var k2 = typeof a2;
    if ("undefined" === k2 || "boolean" === k2) a2 = null;
    var h2 = false;
    if (null === a2) h2 = true;
    else switch (k2) {
      case "string":
      case "number":
        h2 = true;
        break;
      case "object":
        switch (a2.$$typeof) {
          case l2:
          case n:
            h2 = true;
        }
    }
    if (h2) return h2 = a2, c = c(h2), a2 = "" === d ? "." + Q2(h2, 0) : d, I2(c) ? (e2 = "", null != a2 && (e2 = a2.replace(P2, "$&/") + "/"), R(c, b2, e2, "", function(a3) {
      return a3;
    })) : null != c && (O2(c) && (c = N2(c, e2 + (!c.key || h2 && h2.key === c.key ? "" : ("" + c.key).replace(P2, "$&/") + "/") + a2)), b2.push(c)), 1;
    h2 = 0;
    d = "" === d ? "." : d + ":";
    if (I2(a2)) for (var g2 = 0; g2 < a2.length; g2++) {
      k2 = a2[g2];
      var f2 = d + Q2(k2, g2);
      h2 += R(k2, b2, e2, f2, c);
    }
    else if (f2 = A(a2), "function" === typeof f2) for (a2 = f2.call(a2), g2 = 0; !(k2 = a2.next()).done; ) k2 = k2.value, f2 = d + Q2(k2, g2++), h2 += R(k2, b2, e2, f2, c);
    else if ("object" === k2) throw b2 = String(a2), Error("Objects are not valid as a React child (found: " + ("[object Object]" === b2 ? "object with keys {" + Object.keys(a2).join(", ") + "}" : b2) + "). If you meant to render a collection of children, use an array instead.");
    return h2;
  }
  function S2(a2, b2, e2) {
    if (null == a2) return a2;
    var d = [], c = 0;
    R(a2, d, "", "", function(a3) {
      return b2.call(e2, a3, c++);
    });
    return d;
  }
  function T2(a2) {
    if (-1 === a2._status) {
      var b2 = a2._result;
      b2 = b2();
      b2.then(function(b3) {
        if (0 === a2._status || -1 === a2._status) a2._status = 1, a2._result = b3;
      }, function(b3) {
        if (0 === a2._status || -1 === a2._status) a2._status = 2, a2._result = b3;
      });
      -1 === a2._status && (a2._status = 0, a2._result = b2);
    }
    if (1 === a2._status) return a2._result.default;
    throw a2._result;
  }
  var U2 = { current: null }, V2 = { transition: null }, W2 = { ReactCurrentDispatcher: U2, ReactCurrentBatchConfig: V2, ReactCurrentOwner: K2 };
  function X2() {
    throw Error("act(...) is not supported in production builds of React.");
  }
  react_production_min.Children = { map: S2, forEach: function(a2, b2, e2) {
    S2(a2, function() {
      b2.apply(this, arguments);
    }, e2);
  }, count: function(a2) {
    var b2 = 0;
    S2(a2, function() {
      b2++;
    });
    return b2;
  }, toArray: function(a2) {
    return S2(a2, function(a3) {
      return a3;
    }) || [];
  }, only: function(a2) {
    if (!O2(a2)) throw Error("React.Children.only expected to receive a single React element child.");
    return a2;
  } };
  react_production_min.Component = E2;
  react_production_min.Fragment = p2;
  react_production_min.Profiler = r2;
  react_production_min.PureComponent = G2;
  react_production_min.StrictMode = q2;
  react_production_min.Suspense = w2;
  react_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = W2;
  react_production_min.act = X2;
  react_production_min.cloneElement = function(a2, b2, e2) {
    if (null === a2 || void 0 === a2) throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + a2 + ".");
    var d = C({}, a2.props), c = a2.key, k2 = a2.ref, h2 = a2._owner;
    if (null != b2) {
      void 0 !== b2.ref && (k2 = b2.ref, h2 = K2.current);
      void 0 !== b2.key && (c = "" + b2.key);
      if (a2.type && a2.type.defaultProps) var g2 = a2.type.defaultProps;
      for (f2 in b2) J2.call(b2, f2) && !L2.hasOwnProperty(f2) && (d[f2] = void 0 === b2[f2] && void 0 !== g2 ? g2[f2] : b2[f2]);
    }
    var f2 = arguments.length - 2;
    if (1 === f2) d.children = e2;
    else if (1 < f2) {
      g2 = Array(f2);
      for (var m2 = 0; m2 < f2; m2++) g2[m2] = arguments[m2 + 2];
      d.children = g2;
    }
    return { $$typeof: l2, type: a2.type, key: c, ref: k2, props: d, _owner: h2 };
  };
  react_production_min.createContext = function(a2) {
    a2 = { $$typeof: u2, _currentValue: a2, _currentValue2: a2, _threadCount: 0, Provider: null, Consumer: null, _defaultValue: null, _globalName: null };
    a2.Provider = { $$typeof: t2, _context: a2 };
    return a2.Consumer = a2;
  };
  react_production_min.createElement = M2;
  react_production_min.createFactory = function(a2) {
    var b2 = M2.bind(null, a2);
    b2.type = a2;
    return b2;
  };
  react_production_min.createRef = function() {
    return { current: null };
  };
  react_production_min.forwardRef = function(a2) {
    return { $$typeof: v2, render: a2 };
  };
  react_production_min.isValidElement = O2;
  react_production_min.lazy = function(a2) {
    return { $$typeof: y, _payload: { _status: -1, _result: a2 }, _init: T2 };
  };
  react_production_min.memo = function(a2, b2) {
    return { $$typeof: x2, type: a2, compare: void 0 === b2 ? null : b2 };
  };
  react_production_min.startTransition = function(a2) {
    var b2 = V2.transition;
    V2.transition = {};
    try {
      a2();
    } finally {
      V2.transition = b2;
    }
  };
  react_production_min.unstable_act = X2;
  react_production_min.useCallback = function(a2, b2) {
    return U2.current.useCallback(a2, b2);
  };
  react_production_min.useContext = function(a2) {
    return U2.current.useContext(a2);
  };
  react_production_min.useDebugValue = function() {
  };
  react_production_min.useDeferredValue = function(a2) {
    return U2.current.useDeferredValue(a2);
  };
  react_production_min.useEffect = function(a2, b2) {
    return U2.current.useEffect(a2, b2);
  };
  react_production_min.useId = function() {
    return U2.current.useId();
  };
  react_production_min.useImperativeHandle = function(a2, b2, e2) {
    return U2.current.useImperativeHandle(a2, b2, e2);
  };
  react_production_min.useInsertionEffect = function(a2, b2) {
    return U2.current.useInsertionEffect(a2, b2);
  };
  react_production_min.useLayoutEffect = function(a2, b2) {
    return U2.current.useLayoutEffect(a2, b2);
  };
  react_production_min.useMemo = function(a2, b2) {
    return U2.current.useMemo(a2, b2);
  };
  react_production_min.useReducer = function(a2, b2, e2) {
    return U2.current.useReducer(a2, b2, e2);
  };
  react_production_min.useRef = function(a2) {
    return U2.current.useRef(a2);
  };
  react_production_min.useState = function(a2) {
    return U2.current.useState(a2);
  };
  react_production_min.useSyncExternalStore = function(a2, b2, e2) {
    return U2.current.useSyncExternalStore(a2, b2, e2);
  };
  react_production_min.useTransition = function() {
    return U2.current.useTransition();
  };
  react_production_min.version = "18.3.1";
  return react_production_min;
}
var hasRequiredReact;
function requireReact() {
  if (hasRequiredReact) return react.exports;
  hasRequiredReact = 1;
  {
    react.exports = requireReact_production_min();
  }
  return react.exports;
}
var hasRequiredReactJsxRuntime_production_min;
function requireReactJsxRuntime_production_min() {
  if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
  hasRequiredReactJsxRuntime_production_min = 1;
  var f2 = requireReact(), k2 = /* @__PURE__ */ Symbol.for("react.element"), l2 = /* @__PURE__ */ Symbol.for("react.fragment"), m2 = Object.prototype.hasOwnProperty, n = f2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, p2 = { key: true, ref: true, __self: true, __source: true };
  function q2(c, a2, g2) {
    var b2, d = {}, e2 = null, h2 = null;
    void 0 !== g2 && (e2 = "" + g2);
    void 0 !== a2.key && (e2 = "" + a2.key);
    void 0 !== a2.ref && (h2 = a2.ref);
    for (b2 in a2) m2.call(a2, b2) && !p2.hasOwnProperty(b2) && (d[b2] = a2[b2]);
    if (c && c.defaultProps) for (b2 in a2 = c.defaultProps, a2) void 0 === d[b2] && (d[b2] = a2[b2]);
    return { $$typeof: k2, type: c, key: e2, ref: h2, props: d, _owner: n.current };
  }
  reactJsxRuntime_production_min.Fragment = l2;
  reactJsxRuntime_production_min.jsx = q2;
  reactJsxRuntime_production_min.jsxs = q2;
  return reactJsxRuntime_production_min;
}
var hasRequiredJsxRuntime;
function requireJsxRuntime() {
  if (hasRequiredJsxRuntime) return jsxRuntime.exports;
  hasRequiredJsxRuntime = 1;
  {
    jsxRuntime.exports = requireReactJsxRuntime_production_min();
  }
  return jsxRuntime.exports;
}
var jsxRuntimeExports = requireJsxRuntime();
var reactExports = requireReact();
const React = /* @__PURE__ */ getDefaultExportFromCjs(reactExports);
const React$1 = /* @__PURE__ */ _mergeNamespaces({
  __proto__: null,
  default: React
}, [reactExports]);
var client = {};
var reactDom = { exports: {} };
var reactDom_production_min = {};
var scheduler = { exports: {} };
var scheduler_production_min = {};
var hasRequiredScheduler_production_min;
function requireScheduler_production_min() {
  if (hasRequiredScheduler_production_min) return scheduler_production_min;
  hasRequiredScheduler_production_min = 1;
  (function(exports) {
    function f2(a2, b2) {
      var c = a2.length;
      a2.push(b2);
      a: for (; 0 < c; ) {
        var d = c - 1 >>> 1, e2 = a2[d];
        if (0 < g2(e2, b2)) a2[d] = b2, a2[c] = e2, c = d;
        else break a;
      }
    }
    function h2(a2) {
      return 0 === a2.length ? null : a2[0];
    }
    function k2(a2) {
      if (0 === a2.length) return null;
      var b2 = a2[0], c = a2.pop();
      if (c !== b2) {
        a2[0] = c;
        a: for (var d = 0, e2 = a2.length, w2 = e2 >>> 1; d < w2; ) {
          var m2 = 2 * (d + 1) - 1, C = a2[m2], n = m2 + 1, x2 = a2[n];
          if (0 > g2(C, c)) n < e2 && 0 > g2(x2, C) ? (a2[d] = x2, a2[n] = c, d = n) : (a2[d] = C, a2[m2] = c, d = m2);
          else if (n < e2 && 0 > g2(x2, c)) a2[d] = x2, a2[n] = c, d = n;
          else break a;
        }
      }
      return b2;
    }
    function g2(a2, b2) {
      var c = a2.sortIndex - b2.sortIndex;
      return 0 !== c ? c : a2.id - b2.id;
    }
    if ("object" === typeof performance && "function" === typeof performance.now) {
      var l2 = performance;
      exports.unstable_now = function() {
        return l2.now();
      };
    } else {
      var p2 = Date, q2 = p2.now();
      exports.unstable_now = function() {
        return p2.now() - q2;
      };
    }
    var r2 = [], t2 = [], u2 = 1, v2 = null, y = 3, z2 = false, A = false, B2 = false, D2 = "function" === typeof setTimeout ? setTimeout : null, E2 = "function" === typeof clearTimeout ? clearTimeout : null, F2 = "undefined" !== typeof setImmediate ? setImmediate : null;
    "undefined" !== typeof navigator && void 0 !== navigator.scheduling && void 0 !== navigator.scheduling.isInputPending && navigator.scheduling.isInputPending.bind(navigator.scheduling);
    function G2(a2) {
      for (var b2 = h2(t2); null !== b2; ) {
        if (null === b2.callback) k2(t2);
        else if (b2.startTime <= a2) k2(t2), b2.sortIndex = b2.expirationTime, f2(r2, b2);
        else break;
        b2 = h2(t2);
      }
    }
    function H2(a2) {
      B2 = false;
      G2(a2);
      if (!A) if (null !== h2(r2)) A = true, I2(J2);
      else {
        var b2 = h2(t2);
        null !== b2 && K2(H2, b2.startTime - a2);
      }
    }
    function J2(a2, b2) {
      A = false;
      B2 && (B2 = false, E2(L2), L2 = -1);
      z2 = true;
      var c = y;
      try {
        G2(b2);
        for (v2 = h2(r2); null !== v2 && (!(v2.expirationTime > b2) || a2 && !M2()); ) {
          var d = v2.callback;
          if ("function" === typeof d) {
            v2.callback = null;
            y = v2.priorityLevel;
            var e2 = d(v2.expirationTime <= b2);
            b2 = exports.unstable_now();
            "function" === typeof e2 ? v2.callback = e2 : v2 === h2(r2) && k2(r2);
            G2(b2);
          } else k2(r2);
          v2 = h2(r2);
        }
        if (null !== v2) var w2 = true;
        else {
          var m2 = h2(t2);
          null !== m2 && K2(H2, m2.startTime - b2);
          w2 = false;
        }
        return w2;
      } finally {
        v2 = null, y = c, z2 = false;
      }
    }
    var N2 = false, O2 = null, L2 = -1, P2 = 5, Q2 = -1;
    function M2() {
      return exports.unstable_now() - Q2 < P2 ? false : true;
    }
    function R() {
      if (null !== O2) {
        var a2 = exports.unstable_now();
        Q2 = a2;
        var b2 = true;
        try {
          b2 = O2(true, a2);
        } finally {
          b2 ? S2() : (N2 = false, O2 = null);
        }
      } else N2 = false;
    }
    var S2;
    if ("function" === typeof F2) S2 = function() {
      F2(R);
    };
    else if ("undefined" !== typeof MessageChannel) {
      var T2 = new MessageChannel(), U2 = T2.port2;
      T2.port1.onmessage = R;
      S2 = function() {
        U2.postMessage(null);
      };
    } else S2 = function() {
      D2(R, 0);
    };
    function I2(a2) {
      O2 = a2;
      N2 || (N2 = true, S2());
    }
    function K2(a2, b2) {
      L2 = D2(function() {
        a2(exports.unstable_now());
      }, b2);
    }
    exports.unstable_IdlePriority = 5;
    exports.unstable_ImmediatePriority = 1;
    exports.unstable_LowPriority = 4;
    exports.unstable_NormalPriority = 3;
    exports.unstable_Profiling = null;
    exports.unstable_UserBlockingPriority = 2;
    exports.unstable_cancelCallback = function(a2) {
      a2.callback = null;
    };
    exports.unstable_continueExecution = function() {
      A || z2 || (A = true, I2(J2));
    };
    exports.unstable_forceFrameRate = function(a2) {
      0 > a2 || 125 < a2 ? console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported") : P2 = 0 < a2 ? Math.floor(1e3 / a2) : 5;
    };
    exports.unstable_getCurrentPriorityLevel = function() {
      return y;
    };
    exports.unstable_getFirstCallbackNode = function() {
      return h2(r2);
    };
    exports.unstable_next = function(a2) {
      switch (y) {
        case 1:
        case 2:
        case 3:
          var b2 = 3;
          break;
        default:
          b2 = y;
      }
      var c = y;
      y = b2;
      try {
        return a2();
      } finally {
        y = c;
      }
    };
    exports.unstable_pauseExecution = function() {
    };
    exports.unstable_requestPaint = function() {
    };
    exports.unstable_runWithPriority = function(a2, b2) {
      switch (a2) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
          break;
        default:
          a2 = 3;
      }
      var c = y;
      y = a2;
      try {
        return b2();
      } finally {
        y = c;
      }
    };
    exports.unstable_scheduleCallback = function(a2, b2, c) {
      var d = exports.unstable_now();
      "object" === typeof c && null !== c ? (c = c.delay, c = "number" === typeof c && 0 < c ? d + c : d) : c = d;
      switch (a2) {
        case 1:
          var e2 = -1;
          break;
        case 2:
          e2 = 250;
          break;
        case 5:
          e2 = 1073741823;
          break;
        case 4:
          e2 = 1e4;
          break;
        default:
          e2 = 5e3;
      }
      e2 = c + e2;
      a2 = { id: u2++, callback: b2, priorityLevel: a2, startTime: c, expirationTime: e2, sortIndex: -1 };
      c > d ? (a2.sortIndex = c, f2(t2, a2), null === h2(r2) && a2 === h2(t2) && (B2 ? (E2(L2), L2 = -1) : B2 = true, K2(H2, c - d))) : (a2.sortIndex = e2, f2(r2, a2), A || z2 || (A = true, I2(J2)));
      return a2;
    };
    exports.unstable_shouldYield = M2;
    exports.unstable_wrapCallback = function(a2) {
      var b2 = y;
      return function() {
        var c = y;
        y = b2;
        try {
          return a2.apply(this, arguments);
        } finally {
          y = c;
        }
      };
    };
  })(scheduler_production_min);
  return scheduler_production_min;
}
var hasRequiredScheduler;
function requireScheduler() {
  if (hasRequiredScheduler) return scheduler.exports;
  hasRequiredScheduler = 1;
  {
    scheduler.exports = requireScheduler_production_min();
  }
  return scheduler.exports;
}
var hasRequiredReactDom_production_min;
function requireReactDom_production_min() {
  if (hasRequiredReactDom_production_min) return reactDom_production_min;
  hasRequiredReactDom_production_min = 1;
  var aa2 = requireReact(), ca = requireScheduler();
  function p2(a2) {
    for (var b2 = "https://reactjs.org/docs/error-decoder.html?invariant=" + a2, c = 1; c < arguments.length; c++) b2 += "&args[]=" + encodeURIComponent(arguments[c]);
    return "Minified React error #" + a2 + "; visit " + b2 + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
  }
  var da = /* @__PURE__ */ new Set(), ea2 = {};
  function fa(a2, b2) {
    ha2(a2, b2);
    ha2(a2 + "Capture", b2);
  }
  function ha2(a2, b2) {
    ea2[a2] = b2;
    for (a2 = 0; a2 < b2.length; a2++) da.add(b2[a2]);
  }
  var ia2 = !("undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement), ja2 = Object.prototype.hasOwnProperty, ka2 = /^[: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][: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\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/, la = {}, ma = {};
  function oa2(a2) {
    if (ja2.call(ma, a2)) return true;
    if (ja2.call(la, a2)) return false;
    if (ka2.test(a2)) return ma[a2] = true;
    la[a2] = true;
    return false;
  }
  function pa2(a2, b2, c, d) {
    if (null !== c && 0 === c.type) return false;
    switch (typeof b2) {
      case "function":
      case "symbol":
        return true;
      case "boolean":
        if (d) return false;
        if (null !== c) return !c.acceptsBooleans;
        a2 = a2.toLowerCase().slice(0, 5);
        return "data-" !== a2 && "aria-" !== a2;
      default:
        return false;
    }
  }
  function qa2(a2, b2, c, d) {
    if (null === b2 || "undefined" === typeof b2 || pa2(a2, b2, c, d)) return true;
    if (d) return false;
    if (null !== c) switch (c.type) {
      case 3:
        return !b2;
      case 4:
        return false === b2;
      case 5:
        return isNaN(b2);
      case 6:
        return isNaN(b2) || 1 > b2;
    }
    return false;
  }
  function v2(a2, b2, c, d, e2, f2, g2) {
    this.acceptsBooleans = 2 === b2 || 3 === b2 || 4 === b2;
    this.attributeName = d;
    this.attributeNamespace = e2;
    this.mustUseProperty = c;
    this.propertyName = a2;
    this.type = b2;
    this.sanitizeURL = f2;
    this.removeEmptyString = g2;
  }
  var z2 = {};
  "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a2) {
    z2[a2] = new v2(a2, 0, false, a2, null, false, false);
  });
  [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(a2) {
    var b2 = a2[0];
    z2[b2] = new v2(b2, 1, false, a2[1], null, false, false);
  });
  ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(a2) {
    z2[a2] = new v2(a2, 2, false, a2.toLowerCase(), null, false, false);
  });
  ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(a2) {
    z2[a2] = new v2(a2, 2, false, a2, null, false, false);
  });
  "allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a2) {
    z2[a2] = new v2(a2, 3, false, a2.toLowerCase(), null, false, false);
  });
  ["checked", "multiple", "muted", "selected"].forEach(function(a2) {
    z2[a2] = new v2(a2, 3, true, a2, null, false, false);
  });
  ["capture", "download"].forEach(function(a2) {
    z2[a2] = new v2(a2, 4, false, a2, null, false, false);
  });
  ["cols", "rows", "size", "span"].forEach(function(a2) {
    z2[a2] = new v2(a2, 6, false, a2, null, false, false);
  });
  ["rowSpan", "start"].forEach(function(a2) {
    z2[a2] = new v2(a2, 5, false, a2.toLowerCase(), null, false, false);
  });
  var ra2 = /[\-:]([a-z])/g;
  function sa2(a2) {
    return a2[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".split(" ").forEach(function(a2) {
    var b2 = a2.replace(
      ra2,
      sa2
    );
    z2[b2] = new v2(b2, 1, false, a2, null, false, false);
  });
  "xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a2) {
    var b2 = a2.replace(ra2, sa2);
    z2[b2] = new v2(b2, 1, false, a2, "http://www.w3.org/1999/xlink", false, false);
  });
  ["xml:base", "xml:lang", "xml:space"].forEach(function(a2) {
    var b2 = a2.replace(ra2, sa2);
    z2[b2] = new v2(b2, 1, false, a2, "http://www.w3.org/XML/1998/namespace", false, false);
  });
  ["tabIndex", "crossOrigin"].forEach(function(a2) {
    z2[a2] = new v2(a2, 1, false, a2.toLowerCase(), null, false, false);
  });
  z2.xlinkHref = new v2("xlinkHref", 1, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false);
  ["src", "href", "action", "formAction"].forEach(function(a2) {
    z2[a2] = new v2(a2, 1, false, a2.toLowerCase(), null, true, true);
  });
  function ta2(a2, b2, c, d) {
    var e2 = z2.hasOwnProperty(b2) ? z2[b2] : null;
    if (null !== e2 ? 0 !== e2.type : d || !(2 < b2.length) || "o" !== b2[0] && "O" !== b2[0] || "n" !== b2[1] && "N" !== b2[1]) qa2(b2, c, e2, d) && (c = null), d || null === e2 ? oa2(b2) && (null === c ? a2.removeAttribute(b2) : a2.setAttribute(b2, "" + c)) : e2.mustUseProperty ? a2[e2.propertyName] = null === c ? 3 === e2.type ? false : "" : c : (b2 = e2.attributeName, d = e2.attributeNamespace, null === c ? a2.removeAttribute(b2) : (e2 = e2.type, c = 3 === e2 || 4 === e2 && true === c ? "" : "" + c, d ? a2.setAttributeNS(d, b2, c) : a2.setAttribute(b2, c)));
  }
  var ua2 = aa2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, va2 = /* @__PURE__ */ Symbol.for("react.element"), wa2 = /* @__PURE__ */ Symbol.for("react.portal"), ya2 = /* @__PURE__ */ Symbol.for("react.fragment"), za2 = /* @__PURE__ */ Symbol.for("react.strict_mode"), Aa2 = /* @__PURE__ */ Symbol.for("react.profiler"), Ba2 = /* @__PURE__ */ Symbol.for("react.provider"), Ca2 = /* @__PURE__ */ Symbol.for("react.context"), Da2 = /* @__PURE__ */ Symbol.for("react.forward_ref"), Ea2 = /* @__PURE__ */ Symbol.for("react.suspense"), Fa2 = /* @__PURE__ */ Symbol.for("react.suspense_list"), Ga2 = /* @__PURE__ */ Symbol.for("react.memo"), Ha2 = /* @__PURE__ */ Symbol.for("react.lazy");
  var Ia2 = /* @__PURE__ */ Symbol.for("react.offscreen");
  var Ja2 = Symbol.iterator;
  function Ka2(a2) {
    if (null === a2 || "object" !== typeof a2) return null;
    a2 = Ja2 && a2[Ja2] || a2["@@iterator"];
    return "function" === typeof a2 ? a2 : null;
  }
  var A = Object.assign, La2;
  function Ma2(a2) {
    if (void 0 === La2) try {
      throw Error();
    } catch (c) {
      var b2 = c.stack.trim().match(/\n( *(at )?)/);
      La2 = b2 && b2[1] || "";
    }
    return "\n" + La2 + a2;
  }
  var Na2 = false;
  function Oa2(a2, b2) {
    if (!a2 || Na2) return "";
    Na2 = true;
    var c = Error.prepareStackTrace;
    Error.prepareStackTrace = void 0;
    try {
      if (b2) if (b2 = function() {
        throw Error();
      }, Object.defineProperty(b2.prototype, "props", { set: function() {
        throw Error();
      } }), "object" === typeof Reflect && Reflect.construct) {
        try {
          Reflect.construct(b2, []);
        } catch (l2) {
          var d = l2;
        }
        Reflect.construct(a2, [], b2);
      } else {
        try {
          b2.call();
        } catch (l2) {
          d = l2;
        }
        a2.call(b2.prototype);
      }
      else {
        try {
          throw Error();
        } catch (l2) {
          d = l2;
        }
        a2();
      }
    } catch (l2) {
      if (l2 && d && "string" === typeof l2.stack) {
        for (var e2 = l2.stack.split("\n"), f2 = d.stack.split("\n"), g2 = e2.length - 1, h2 = f2.length - 1; 1 <= g2 && 0 <= h2 && e2[g2] !== f2[h2]; ) h2--;
        for (; 1 <= g2 && 0 <= h2; g2--, h2--) if (e2[g2] !== f2[h2]) {
          if (1 !== g2 || 1 !== h2) {
            do
              if (g2--, h2--, 0 > h2 || e2[g2] !== f2[h2]) {
                var k2 = "\n" + e2[g2].replace(" at new ", " at ");
                a2.displayName && k2.includes("<anonymous>") && (k2 = k2.replace("<anonymous>", a2.displayName));
                return k2;
              }
            while (1 <= g2 && 0 <= h2);
          }
          break;
        }
      }
    } finally {
      Na2 = false, Error.prepareStackTrace = c;
    }
    return (a2 = a2 ? a2.displayName || a2.name : "") ? Ma2(a2) : "";
  }
  function Pa2(a2) {
    switch (a2.tag) {
      case 5:
        return Ma2(a2.type);
      case 16:
        return Ma2("Lazy");
      case 13:
        return Ma2("Suspense");
      case 19:
        return Ma2("SuspenseList");
      case 0:
      case 2:
      case 15:
        return a2 = Oa2(a2.type, false), a2;
      case 11:
        return a2 = Oa2(a2.type.render, false), a2;
      case 1:
        return a2 = Oa2(a2.type, true), a2;
      default:
        return "";
    }
  }
  function Qa2(a2) {
    if (null == a2) return null;
    if ("function" === typeof a2) return a2.displayName || a2.name || null;
    if ("string" === typeof a2) return a2;
    switch (a2) {
      case ya2:
        return "Fragment";
      case wa2:
        return "Portal";
      case Aa2:
        return "Profiler";
      case za2:
        return "StrictMode";
      case Ea2:
        return "Suspense";
      case Fa2:
        return "SuspenseList";
    }
    if ("object" === typeof a2) switch (a2.$$typeof) {
      case Ca2:
        return (a2.displayName || "Context") + ".Consumer";
      case Ba2:
        return (a2._context.displayName || "Context") + ".Provider";
      case Da2:
        var b2 = a2.render;
        a2 = a2.displayName;
        a2 || (a2 = b2.displayName || b2.name || "", a2 = "" !== a2 ? "ForwardRef(" + a2 + ")" : "ForwardRef");
        return a2;
      case Ga2:
        return b2 = a2.displayName || null, null !== b2 ? b2 : Qa2(a2.type) || "Memo";
      case Ha2:
        b2 = a2._payload;
        a2 = a2._init;
        try {
          return Qa2(a2(b2));
        } catch (c) {
        }
    }
    return null;
  }
  function Ra2(a2) {
    var b2 = a2.type;
    switch (a2.tag) {
      case 24:
        return "Cache";
      case 9:
        return (b2.displayName || "Context") + ".Consumer";
      case 10:
        return (b2._context.displayName || "Context") + ".Provider";
      case 18:
        return "DehydratedFragment";
      case 11:
        return a2 = b2.render, a2 = a2.displayName || a2.name || "", b2.displayName || ("" !== a2 ? "ForwardRef(" + a2 + ")" : "ForwardRef");
      case 7:
        return "Fragment";
      case 5:
        return b2;
      case 4:
        return "Portal";
      case 3:
        return "Root";
      case 6:
        return "Text";
      case 16:
        return Qa2(b2);
      case 8:
        return b2 === za2 ? "StrictMode" : "Mode";
      case 22:
        return "Offscreen";
      case 12:
        return "Profiler";
      case 21:
        return "Scope";
      case 13:
        return "Suspense";
      case 19:
        return "SuspenseList";
      case 25:
        return "TracingMarker";
      case 1:
      case 0:
      case 17:
      case 2:
      case 14:
      case 15:
        if ("function" === typeof b2) return b2.displayName || b2.name || null;
        if ("string" === typeof b2) return b2;
    }
    return null;
  }
  function Sa2(a2) {
    switch (typeof a2) {
      case "boolean":
      case "number":
      case "string":
      case "undefined":
        return a2;
      case "object":
        return a2;
      default:
        return "";
    }
  }
  function Ta2(a2) {
    var b2 = a2.type;
    return (a2 = a2.nodeName) && "input" === a2.toLowerCase() && ("checkbox" === b2 || "radio" === b2);
  }
  function Ua2(a2) {
    var b2 = Ta2(a2) ? "checked" : "value", c = Object.getOwnPropertyDescriptor(a2.constructor.prototype, b2), d = "" + a2[b2];
    if (!a2.hasOwnProperty(b2) && "undefined" !== typeof c && "function" === typeof c.get && "function" === typeof c.set) {
      var e2 = c.get, f2 = c.set;
      Object.defineProperty(a2, b2, { configurable: true, get: function() {
        return e2.call(this);
      }, set: function(a3) {
        d = "" + a3;
        f2.call(this, a3);
      } });
      Object.defineProperty(a2, b2, { enumerable: c.enumerable });
      return { getValue: function() {
        return d;
      }, setValue: function(a3) {
        d = "" + a3;
      }, stopTracking: function() {
        a2._valueTracker = null;
        delete a2[b2];
      } };
    }
  }
  function Va2(a2) {
    a2._valueTracker || (a2._valueTracker = Ua2(a2));
  }
  function Wa2(a2) {
    if (!a2) return false;
    var b2 = a2._valueTracker;
    if (!b2) return true;
    var c = b2.getValue();
    var d = "";
    a2 && (d = Ta2(a2) ? a2.checked ? "true" : "false" : a2.value);
    a2 = d;
    return a2 !== c ? (b2.setValue(a2), true) : false;
  }
  function Xa2(a2) {
    a2 = a2 || ("undefined" !== typeof document ? document : void 0);
    if ("undefined" === typeof a2) return null;
    try {
      return a2.activeElement || a2.body;
    } catch (b2) {
      return a2.body;
    }
  }
  function Ya2(a2, b2) {
    var c = b2.checked;
    return A({}, b2, { defaultChecked: void 0, defaultValue: void 0, value: void 0, checked: null != c ? c : a2._wrapperState.initialChecked });
  }
  function Za2(a2, b2) {
    var c = null == b2.defaultValue ? "" : b2.defaultValue, d = null != b2.checked ? b2.checked : b2.defaultChecked;
    c = Sa2(null != b2.value ? b2.value : c);
    a2._wrapperState = { initialChecked: d, initialValue: c, controlled: "checkbox" === b2.type || "radio" === b2.type ? null != b2.checked : null != b2.value };
  }
  function ab(a2, b2) {
    b2 = b2.checked;
    null != b2 && ta2(a2, "checked", b2, false);
  }
  function bb(a2, b2) {
    ab(a2, b2);
    var c = Sa2(b2.value), d = b2.type;
    if (null != c) if ("number" === d) {
      if (0 === c && "" === a2.value || a2.value != c) a2.value = "" + c;
    } else a2.value !== "" + c && (a2.value = "" + c);
    else if ("submit" === d || "reset" === d) {
      a2.removeAttribute("value");
      return;
    }
    b2.hasOwnProperty("value") ? cb(a2, b2.type, c) : b2.hasOwnProperty("defaultValue") && cb(a2, b2.type, Sa2(b2.defaultValue));
    null == b2.checked && null != b2.defaultChecked && (a2.defaultChecked = !!b2.defaultChecked);
  }
  function db(a2, b2, c) {
    if (b2.hasOwnProperty("value") || b2.hasOwnProperty("defaultValue")) {
      var d = b2.type;
      if (!("submit" !== d && "reset" !== d || void 0 !== b2.value && null !== b2.value)) return;
      b2 = "" + a2._wrapperState.initialValue;
      c || b2 === a2.value || (a2.value = b2);
      a2.defaultValue = b2;
    }
    c = a2.name;
    "" !== c && (a2.name = "");
    a2.defaultChecked = !!a2._wrapperState.initialChecked;
    "" !== c && (a2.name = c);
  }
  function cb(a2, b2, c) {
    if ("number" !== b2 || Xa2(a2.ownerDocument) !== a2) null == c ? a2.defaultValue = "" + a2._wrapperState.initialValue : a2.defaultValue !== "" + c && (a2.defaultValue = "" + c);
  }
  var eb = Array.isArray;
  function fb(a2, b2, c, d) {
    a2 = a2.options;
    if (b2) {
      b2 = {};
      for (var e2 = 0; e2 < c.length; e2++) b2["$" + c[e2]] = true;
      for (c = 0; c < a2.length; c++) e2 = b2.hasOwnProperty("$" + a2[c].value), a2[c].selected !== e2 && (a2[c].selected = e2), e2 && d && (a2[c].defaultSelected = true);
    } else {
      c = "" + Sa2(c);
      b2 = null;
      for (e2 = 0; e2 < a2.length; e2++) {
        if (a2[e2].value === c) {
          a2[e2].selected = true;
          d && (a2[e2].defaultSelected = true);
          return;
        }
        null !== b2 || a2[e2].disabled || (b2 = a2[e2]);
      }
      null !== b2 && (b2.selected = true);
    }
  }
  function gb(a2, b2) {
    if (null != b2.dangerouslySetInnerHTML) throw Error(p2(91));
    return A({}, b2, { value: void 0, defaultValue: void 0, children: "" + a2._wrapperState.initialValue });
  }
  function hb(a2, b2) {
    var c = b2.value;
    if (null == c) {
      c = b2.children;
      b2 = b2.defaultValue;
      if (null != c) {
        if (null != b2) throw Error(p2(92));
        if (eb(c)) {
          if (1 < c.length) throw Error(p2(93));
          c = c[0];
        }
        b2 = c;
      }
      null == b2 && (b2 = "");
      c = b2;
    }
    a2._wrapperState = { initialValue: Sa2(c) };
  }
  function ib(a2, b2) {
    var c = Sa2(b2.value), d = Sa2(b2.defaultValue);
    null != c && (c = "" + c, c !== a2.value && (a2.value = c), null == b2.defaultValue && a2.defaultValue !== c && (a2.defaultValue = c));
    null != d && (a2.defaultValue = "" + d);
  }
  function jb(a2) {
    var b2 = a2.textContent;
    b2 === a2._wrapperState.initialValue && "" !== b2 && null !== b2 && (a2.value = b2);
  }
  function kb(a2) {
    switch (a2) {
      case "svg":
        return "http://www.w3.org/2000/svg";
      case "math":
        return "http://www.w3.org/1998/Math/MathML";
      default:
        return "http://www.w3.org/1999/xhtml";
    }
  }
  function lb(a2, b2) {
    return null == a2 || "http://www.w3.org/1999/xhtml" === a2 ? kb(b2) : "http://www.w3.org/2000/svg" === a2 && "foreignObject" === b2 ? "http://www.w3.org/1999/xhtml" : a2;
  }
  var mb, nb = (function(a2) {
    return "undefined" !== typeof MSApp && MSApp.execUnsafeLocalFunction ? function(b2, c, d, e2) {
      MSApp.execUnsafeLocalFunction(function() {
        return a2(b2, c, d, e2);
      });
    } : a2;
  })(function(a2, b2) {
    if ("http://www.w3.org/2000/svg" !== a2.namespaceURI || "innerHTML" in a2) a2.innerHTML = b2;
    else {
      mb = mb || document.createElement("div");
      mb.innerHTML = "<svg>" + b2.valueOf().toString() + "</svg>";
      for (b2 = mb.firstChild; a2.firstChild; ) a2.removeChild(a2.firstChild);
      for (; b2.firstChild; ) a2.appendChild(b2.firstChild);
    }
  });
  function ob(a2, b2) {
    if (b2) {
      var c = a2.firstChild;
      if (c && c === a2.lastChild && 3 === c.nodeType) {
        c.nodeValue = b2;
        return;
      }
    }
    a2.textContent = b2;
  }
  var pb = {
    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,
    fillOpacity: true,
    floodOpacity: true,
    stopOpacity: true,
    strokeDasharray: true,
    strokeDashoffset: true,
    strokeMiterlimit: true,
    strokeOpacity: true,
    strokeWidth: true
  }, qb = ["Webkit", "ms", "Moz", "O"];
  Object.keys(pb).forEach(function(a2) {
    qb.forEach(function(b2) {
      b2 = b2 + a2.charAt(0).toUpperCase() + a2.substring(1);
      pb[b2] = pb[a2];
    });
  });
  function rb(a2, b2, c) {
    return null == b2 || "boolean" === typeof b2 || "" === b2 ? "" : c || "number" !== typeof b2 || 0 === b2 || pb.hasOwnProperty(a2) && pb[a2] ? ("" + b2).trim() : b2 + "px";
  }
  function sb(a2, b2) {
    a2 = a2.style;
    for (var c in b2) if (b2.hasOwnProperty(c)) {
      var d = 0 === c.indexOf("--"), e2 = rb(c, b2[c], d);
      "float" === c && (c = "cssFloat");
      d ? a2.setProperty(c, e2) : a2[c] = e2;
    }
  }
  var tb = A({ menuitem: true }, { 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 });
  function ub(a2, b2) {
    if (b2) {
      if (tb[a2] && (null != b2.children || null != b2.dangerouslySetInnerHTML)) throw Error(p2(137, a2));
      if (null != b2.dangerouslySetInnerHTML) {
        if (null != b2.children) throw Error(p2(60));
        if ("object" !== typeof b2.dangerouslySetInnerHTML || !("__html" in b2.dangerouslySetInnerHTML)) throw Error(p2(61));
      }
      if (null != b2.style && "object" !== typeof b2.style) throw Error(p2(62));
    }
  }
  function vb(a2, b2) {
    if (-1 === a2.indexOf("-")) return "string" === typeof b2.is;
    switch (a2) {
      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 wb = null;
  function xb(a2) {
    a2 = a2.target || a2.srcElement || window;
    a2.correspondingUseElement && (a2 = a2.correspondingUseElement);
    return 3 === a2.nodeType ? a2.parentNode : a2;
  }
  var yb = null, zb = null, Ab = null;
  function Bb(a2) {
    if (a2 = Cb(a2)) {
      if ("function" !== typeof yb) throw Error(p2(280));
      var b2 = a2.stateNode;
      b2 && (b2 = Db(b2), yb(a2.stateNode, a2.type, b2));
    }
  }
  function Eb(a2) {
    zb ? Ab ? Ab.push(a2) : Ab = [a2] : zb = a2;
  }
  function Fb() {
    if (zb) {
      var a2 = zb, b2 = Ab;
      Ab = zb = null;
      Bb(a2);
      if (b2) for (a2 = 0; a2 < b2.length; a2++) Bb(b2[a2]);
    }
  }
  function Gb(a2, b2) {
    return a2(b2);
  }
  function Hb() {
  }
  var Ib = false;
  function Jb(a2, b2, c) {
    if (Ib) return a2(b2, c);
    Ib = true;
    try {
      return Gb(a2, b2, c);
    } finally {
      if (Ib = false, null !== zb || null !== Ab) Hb(), Fb();
    }
  }
  function Kb(a2, b2) {
    var c = a2.stateNode;
    if (null === c) return null;
    var d = Db(c);
    if (null === d) return null;
    c = d[b2];
    a: switch (b2) {
      case "onClick":
      case "onClickCapture":
      case "onDoubleClick":
      case "onDoubleClickCapture":
      case "onMouseDown":
      case "onMouseDownCapture":
      case "onMouseMove":
      case "onMouseMoveCapture":
      case "onMouseUp":
      case "onMouseUpCapture":
      case "onMouseEnter":
        (d = !d.disabled) || (a2 = a2.type, d = !("button" === a2 || "input" === a2 || "select" === a2 || "textarea" === a2));
        a2 = !d;
        break a;
      default:
        a2 = false;
    }
    if (a2) return null;
    if (c && "function" !== typeof c) throw Error(p2(231, b2, typeof c));
    return c;
  }
  var Lb = false;
  if (ia2) try {
    var Mb = {};
    Object.defineProperty(Mb, "passive", { get: function() {
      Lb = true;
    } });
    window.addEventListener("test", Mb, Mb);
    window.removeEventListener("test", Mb, Mb);
  } catch (a2) {
    Lb = false;
  }
  function Nb(a2, b2, c, d, e2, f2, g2, h2, k2) {
    var l2 = Array.prototype.slice.call(arguments, 3);
    try {
      b2.apply(c, l2);
    } catch (m2) {
      this.onError(m2);
    }
  }
  var Ob = false, Pb = null, Qb = false, Rb = null, Sb = { onError: function(a2) {
    Ob = true;
    Pb = a2;
  } };
  function Tb(a2, b2, c, d, e2, f2, g2, h2, k2) {
    Ob = false;
    Pb = null;
    Nb.apply(Sb, arguments);
  }
  function Ub(a2, b2, c, d, e2, f2, g2, h2, k2) {
    Tb.apply(this, arguments);
    if (Ob) {
      if (Ob) {
        var l2 = Pb;
        Ob = false;
        Pb = null;
      } else throw Error(p2(198));
      Qb || (Qb = true, Rb = l2);
    }
  }
  function Vb(a2) {
    var b2 = a2, c = a2;
    if (a2.alternate) for (; b2.return; ) b2 = b2.return;
    else {
      a2 = b2;
      do
        b2 = a2, 0 !== (b2.flags & 4098) && (c = b2.return), a2 = b2.return;
      while (a2);
    }
    return 3 === b2.tag ? c : null;
  }
  function Wb(a2) {
    if (13 === a2.tag) {
      var b2 = a2.memoizedState;
      null === b2 && (a2 = a2.alternate, null !== a2 && (b2 = a2.memoizedState));
      if (null !== b2) return b2.dehydrated;
    }
    return null;
  }
  function Xb(a2) {
    if (Vb(a2) !== a2) throw Error(p2(188));
  }
  function Yb(a2) {
    var b2 = a2.alternate;
    if (!b2) {
      b2 = Vb(a2);
      if (null === b2) throw Error(p2(188));
      return b2 !== a2 ? null : a2;
    }
    for (var c = a2, d = b2; ; ) {
      var e2 = c.return;
      if (null === e2) break;
      var f2 = e2.alternate;
      if (null === f2) {
        d = e2.return;
        if (null !== d) {
          c = d;
          continue;
        }
        break;
      }
      if (e2.child === f2.child) {
        for (f2 = e2.child; f2; ) {
          if (f2 === c) return Xb(e2), a2;
          if (f2 === d) return Xb(e2), b2;
          f2 = f2.sibling;
        }
        throw Error(p2(188));
      }
      if (c.return !== d.return) c = e2, d = f2;
      else {
        for (var g2 = false, h2 = e2.child; h2; ) {
          if (h2 === c) {
            g2 = true;
            c = e2;
            d = f2;
            break;
          }
          if (h2 === d) {
            g2 = true;
            d = e2;
            c = f2;
            break;
          }
          h2 = h2.sibling;
        }
        if (!g2) {
          for (h2 = f2.child; h2; ) {
            if (h2 === c) {
              g2 = true;
              c = f2;
              d = e2;
              break;
            }
            if (h2 === d) {
              g2 = true;
              d = f2;
              c = e2;
              break;
            }
            h2 = h2.sibling;
          }
          if (!g2) throw Error(p2(189));
        }
      }
      if (c.alternate !== d) throw Error(p2(190));
    }
    if (3 !== c.tag) throw Error(p2(188));
    return c.stateNode.current === c ? a2 : b2;
  }
  function Zb(a2) {
    a2 = Yb(a2);
    return null !== a2 ? $b(a2) : null;
  }
  function $b(a2) {
    if (5 === a2.tag || 6 === a2.tag) return a2;
    for (a2 = a2.child; null !== a2; ) {
      var b2 = $b(a2);
      if (null !== b2) return b2;
      a2 = a2.sibling;
    }
    return null;
  }
  var ac = ca.unstable_scheduleCallback, bc = ca.unstable_cancelCallback, cc = ca.unstable_shouldYield, dc = ca.unstable_requestPaint, B2 = ca.unstable_now, ec2 = ca.unstable_getCurrentPriorityLevel, fc = ca.unstable_ImmediatePriority, gc = ca.unstable_UserBlockingPriority, hc = ca.unstable_NormalPriority, ic2 = ca.unstable_LowPriority, jc = ca.unstable_IdlePriority, kc = null, lc = null;
  function mc(a2) {
    if (lc && "function" === typeof lc.onCommitFiberRoot) try {
      lc.onCommitFiberRoot(kc, a2, void 0, 128 === (a2.current.flags & 128));
    } catch (b2) {
    }
  }
  var oc2 = Math.clz32 ? Math.clz32 : nc2, pc = Math.log, qc2 = Math.LN2;
  function nc2(a2) {
    a2 >>>= 0;
    return 0 === a2 ? 32 : 31 - (pc(a2) / qc2 | 0) | 0;
  }
  var rc = 64, sc = 4194304;
  function tc2(a2) {
    switch (a2 & -a2) {
      case 1:
        return 1;
      case 2:
        return 2;
      case 4:
        return 4;
      case 8:
        return 8;
      case 16:
        return 16;
      case 32:
        return 32;
      case 64:
      case 128:
      case 256:
      case 512:
      case 1024:
      case 2048:
      case 4096:
      case 8192:
      case 16384:
      case 32768:
      case 65536:
      case 131072:
      case 262144:
      case 524288:
      case 1048576:
      case 2097152:
        return a2 & 4194240;
      case 4194304:
      case 8388608:
      case 16777216:
      case 33554432:
      case 67108864:
        return a2 & 130023424;
      case 134217728:
        return 134217728;
      case 268435456:
        return 268435456;
      case 536870912:
        return 536870912;
      case 1073741824:
        return 1073741824;
      default:
        return a2;
    }
  }
  function uc2(a2, b2) {
    var c = a2.pendingLanes;
    if (0 === c) return 0;
    var d = 0, e2 = a2.suspendedLanes, f2 = a2.pingedLanes, g2 = c & 268435455;
    if (0 !== g2) {
      var h2 = g2 & ~e2;
      0 !== h2 ? d = tc2(h2) : (f2 &= g2, 0 !== f2 && (d = tc2(f2)));
    } else g2 = c & ~e2, 0 !== g2 ? d = tc2(g2) : 0 !== f2 && (d = tc2(f2));
    if (0 === d) return 0;
    if (0 !== b2 && b2 !== d && 0 === (b2 & e2) && (e2 = d & -d, f2 = b2 & -b2, e2 >= f2 || 16 === e2 && 0 !== (f2 & 4194240))) return b2;
    0 !== (d & 4) && (d |= c & 16);
    b2 = a2.entangledLanes;
    if (0 !== b2) for (a2 = a2.entanglements, b2 &= d; 0 < b2; ) c = 31 - oc2(b2), e2 = 1 << c, d |= a2[c], b2 &= ~e2;
    return d;
  }
  function vc(a2, b2) {
    switch (a2) {
      case 1:
      case 2:
      case 4:
        return b2 + 250;
      case 8:
      case 16:
      case 32:
      case 64:
      case 128:
      case 256:
      case 512:
      case 1024:
      case 2048:
      case 4096:
      case 8192:
      case 16384:
      case 32768:
      case 65536:
      case 131072:
      case 262144:
      case 524288:
      case 1048576:
      case 2097152:
        return b2 + 5e3;
      case 4194304:
      case 8388608:
      case 16777216:
      case 33554432:
      case 67108864:
        return -1;
      case 134217728:
      case 268435456:
      case 536870912:
      case 1073741824:
        return -1;
      default:
        return -1;
    }
  }
  function wc(a2, b2) {
    for (var c = a2.suspendedLanes, d = a2.pingedLanes, e2 = a2.expirationTimes, f2 = a2.pendingLanes; 0 < f2; ) {
      var g2 = 31 - oc2(f2), h2 = 1 << g2, k2 = e2[g2];
      if (-1 === k2) {
        if (0 === (h2 & c) || 0 !== (h2 & d)) e2[g2] = vc(h2, b2);
      } else k2 <= b2 && (a2.expiredLanes |= h2);
      f2 &= ~h2;
    }
  }
  function xc(a2) {
    a2 = a2.pendingLanes & -1073741825;
    return 0 !== a2 ? a2 : a2 & 1073741824 ? 1073741824 : 0;
  }
  function yc() {
    var a2 = rc;
    rc <<= 1;
    0 === (rc & 4194240) && (rc = 64);
    return a2;
  }
  function zc(a2) {
    for (var b2 = [], c = 0; 31 > c; c++) b2.push(a2);
    return b2;
  }
  function Ac2(a2, b2, c) {
    a2.pendingLanes |= b2;
    536870912 !== b2 && (a2.suspendedLanes = 0, a2.pingedLanes = 0);
    a2 = a2.eventTimes;
    b2 = 31 - oc2(b2);
    a2[b2] = c;
  }
  function Bc2(a2, b2) {
    var c = a2.pendingLanes & ~b2;
    a2.pendingLanes = b2;
    a2.suspendedLanes = 0;
    a2.pingedLanes = 0;
    a2.expiredLanes &= b2;
    a2.mutableReadLanes &= b2;
    a2.entangledLanes &= b2;
    b2 = a2.entanglements;
    var d = a2.eventTimes;
    for (a2 = a2.expirationTimes; 0 < c; ) {
      var e2 = 31 - oc2(c), f2 = 1 << e2;
      b2[e2] = 0;
      d[e2] = -1;
      a2[e2] = -1;
      c &= ~f2;
    }
  }
  function Cc2(a2, b2) {
    var c = a2.entangledLanes |= b2;
    for (a2 = a2.entanglements; c; ) {
      var d = 31 - oc2(c), e2 = 1 << d;
      e2 & b2 | a2[d] & b2 && (a2[d] |= b2);
      c &= ~e2;
    }
  }
  var C = 0;
  function Dc2(a2) {
    a2 &= -a2;
    return 1 < a2 ? 4 < a2 ? 0 !== (a2 & 268435455) ? 16 : 536870912 : 4 : 1;
  }
  var Ec2, Fc2, Gc2, Hc2, Ic, Jc2 = false, Kc2 = [], Lc2 = null, Mc2 = null, Nc2 = null, Oc = /* @__PURE__ */ new Map(), Pc2 = /* @__PURE__ */ new Map(), Qc2 = [], Rc2 = "mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");
  function Sc(a2, b2) {
    switch (a2) {
      case "focusin":
      case "focusout":
        Lc2 = null;
        break;
      case "dragenter":
      case "dragleave":
        Mc2 = null;
        break;
      case "mouseover":
      case "mouseout":
        Nc2 = null;
        break;
      case "pointerover":
      case "pointerout":
        Oc.delete(b2.pointerId);
        break;
      case "gotpointercapture":
      case "lostpointercapture":
        Pc2.delete(b2.pointerId);
    }
  }
  function Tc2(a2, b2, c, d, e2, f2) {
    if (null === a2 || a2.nativeEvent !== f2) return a2 = { blockedOn: b2, domEventName: c, eventSystemFlags: d, nativeEvent: f2, targetContainers: [e2] }, null !== b2 && (b2 = Cb(b2), null !== b2 && Fc2(b2)), a2;
    a2.eventSystemFlags |= d;
    b2 = a2.targetContainers;
    null !== e2 && -1 === b2.indexOf(e2) && b2.push(e2);
    return a2;
  }
  function Uc(a2, b2, c, d, e2) {
    switch (b2) {
      case "focusin":
        return Lc2 = Tc2(Lc2, a2, b2, c, d, e2), true;
      case "dragenter":
        return Mc2 = Tc2(Mc2, a2, b2, c, d, e2), true;
      case "mouseover":
        return Nc2 = Tc2(Nc2, a2, b2, c, d, e2), true;
      case "pointerover":
        var f2 = e2.pointerId;
        Oc.set(f2, Tc2(Oc.get(f2) || null, a2, b2, c, d, e2));
        return true;
      case "gotpointercapture":
        return f2 = e2.pointerId, Pc2.set(f2, Tc2(Pc2.get(f2) || null, a2, b2, c, d, e2)), true;
    }
    return false;
  }
  function Vc2(a2) {
    var b2 = Wc2(a2.target);
    if (null !== b2) {
      var c = Vb(b2);
      if (null !== c) {
        if (b2 = c.tag, 13 === b2) {
          if (b2 = Wb(c), null !== b2) {
            a2.blockedOn = b2;
            Ic(a2.priority, function() {
              Gc2(c);
            });
            return;
          }
        } else if (3 === b2 && c.stateNode.current.memoizedState.isDehydrated) {
          a2.blockedOn = 3 === c.tag ? c.stateNode.containerInfo : null;
          return;
        }
      }
    }
    a2.blockedOn = null;
  }
  function Xc2(a2) {
    if (null !== a2.blockedOn) return false;
    for (var b2 = a2.targetContainers; 0 < b2.length; ) {
      var c = Yc2(a2.domEventName, a2.eventSystemFlags, b2[0], a2.nativeEvent);
      if (null === c) {
        c = a2.nativeEvent;
        var d = new c.constructor(c.type, c);
        wb = d;
        c.target.dispatchEvent(d);
        wb = null;
      } else return b2 = Cb(c), null !== b2 && Fc2(b2), a2.blockedOn = c, false;
      b2.shift();
    }
    return true;
  }
  function Zc2(a2, b2, c) {
    Xc2(a2) && c.delete(b2);
  }
  function $c() {
    Jc2 = false;
    null !== Lc2 && Xc2(Lc2) && (Lc2 = null);
    null !== Mc2 && Xc2(Mc2) && (Mc2 = null);
    null !== Nc2 && Xc2(Nc2) && (Nc2 = null);
    Oc.forEach(Zc2);
    Pc2.forEach(Zc2);
  }
  function ad2(a2, b2) {
    a2.blockedOn === b2 && (a2.blockedOn = null, Jc2 || (Jc2 = true, ca.unstable_scheduleCallback(ca.unstable_NormalPriority, $c)));
  }
  function bd2(a2) {
    function b2(b3) {
      return ad2(b3, a2);
    }
    if (0 < Kc2.length) {
      ad2(Kc2[0], a2);
      for (var c = 1; c < Kc2.length; c++) {
        var d = Kc2[c];
        d.blockedOn === a2 && (d.blockedOn = null);
      }
    }
    null !== Lc2 && ad2(Lc2, a2);
    null !== Mc2 && ad2(Mc2, a2);
    null !== Nc2 && ad2(Nc2, a2);
    Oc.forEach(b2);
    Pc2.forEach(b2);
    for (c = 0; c < Qc2.length; c++) d = Qc2[c], d.blockedOn === a2 && (d.blockedOn = null);
    for (; 0 < Qc2.length && (c = Qc2[0], null === c.blockedOn); ) Vc2(c), null === c.blockedOn && Qc2.shift();
  }
  var cd2 = ua2.ReactCurrentBatchConfig, dd2 = true;
  function ed2(a2, b2, c, d) {
    var e2 = C, f2 = cd2.transition;
    cd2.transition = null;
    try {
      C = 1, fd2(a2, b2, c, d);
    } finally {
      C = e2, cd2.transition = f2;
    }
  }
  function gd2(a2, b2, c, d) {
    var e2 = C, f2 = cd2.transition;
    cd2.transition = null;
    try {
      C = 4, fd2(a2, b2, c, d);
    } finally {
      C = e2, cd2.transition = f2;
    }
  }
  function fd2(a2, b2, c, d) {
    if (dd2) {
      var e2 = Yc2(a2, b2, c, d);
      if (null === e2) hd2(a2, b2, d, id2, c), Sc(a2, d);
      else if (Uc(e2, a2, b2, c, d)) d.stopPropagation();
      else if (Sc(a2, d), b2 & 4 && -1 < Rc2.indexOf(a2)) {
        for (; null !== e2; ) {
          var f2 = Cb(e2);
          null !== f2 && Ec2(f2);
          f2 = Yc2(a2, b2, c, d);
          null === f2 && hd2(a2, b2, d, id2, c);
          if (f2 === e2) break;
          e2 = f2;
        }
        null !== e2 && d.stopPropagation();
      } else hd2(a2, b2, d, null, c);
    }
  }
  var id2 = null;
  function Yc2(a2, b2, c, d) {
    id2 = null;
    a2 = xb(d);
    a2 = Wc2(a2);
    if (null !== a2) if (b2 = Vb(a2), null === b2) a2 = null;
    else if (c = b2.tag, 13 === c) {
      a2 = Wb(b2);
      if (null !== a2) return a2;
      a2 = null;
    } else if (3 === c) {
      if (b2.stateNode.current.memoizedState.isDehydrated) return 3 === b2.tag ? b2.stateNode.containerInfo : null;
      a2 = null;
    } else b2 !== a2 && (a2 = null);
    id2 = a2;
    return null;
  }
  function jd2(a2) {
    switch (a2) {
      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":
      case "change":
      case "selectionchange":
      case "textInput":
      case "compositionstart":
      case "compositionend":
      case "compositionupdate":
      case "beforeblur":
      case "afterblur":
      case "beforeinput":
      case "blur":
      case "fullscreenchange":
      case "focus":
      case "hashchange":
      case "popstate":
      case "select":
      case "selectstart":
        return 1;
      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":
      case "mouseenter":
      case "mouseleave":
      case "pointerenter":
      case "pointerleave":
        return 4;
      case "message":
        switch (ec2()) {
          case fc:
            return 1;
          case gc:
            return 4;
          case hc:
          case ic2:
            return 16;
          case jc:
            return 536870912;
          default:
            return 16;
        }
      default:
        return 16;
    }
  }
  var kd2 = null, ld2 = null, md2 = null;
  function nd2() {
    if (md2) return md2;
    var a2, b2 = ld2, c = b2.length, d, e2 = "value" in kd2 ? kd2.value : kd2.textContent, f2 = e2.length;
    for (a2 = 0; a2 < c && b2[a2] === e2[a2]; a2++) ;
    var g2 = c - a2;
    for (d = 1; d <= g2 && b2[c - d] === e2[f2 - d]; d++) ;
    return md2 = e2.slice(a2, 1 < d ? 1 - d : void 0);
  }
  function od2(a2) {
    var b2 = a2.keyCode;
    "charCode" in a2 ? (a2 = a2.charCode, 0 === a2 && 13 === b2 && (a2 = 13)) : a2 = b2;
    10 === a2 && (a2 = 13);
    return 32 <= a2 || 13 === a2 ? a2 : 0;
  }
  function pd2() {
    return true;
  }
  function qd2() {
    return false;
  }
  function rd2(a2) {
    function b2(b3, d, e2, f2, g2) {
      this._reactName = b3;
      this._targetInst = e2;
      this.type = d;
      this.nativeEvent = f2;
      this.target = g2;
      this.currentTarget = null;
      for (var c in a2) a2.hasOwnProperty(c) && (b3 = a2[c], this[c] = b3 ? b3(f2) : f2[c]);
      this.isDefaultPrevented = (null != f2.defaultPrevented ? f2.defaultPrevented : false === f2.returnValue) ? pd2 : qd2;
      this.isPropagationStopped = qd2;
      return this;
    }
    A(b2.prototype, { preventDefault: function() {
      this.defaultPrevented = true;
      var a3 = this.nativeEvent;
      a3 && (a3.preventDefault ? a3.preventDefault() : "unknown" !== typeof a3.returnValue && (a3.returnValue = false), this.isDefaultPrevented = pd2);
    }, stopPropagation: function() {
      var a3 = this.nativeEvent;
      a3 && (a3.stopPropagation ? a3.stopPropagation() : "unknown" !== typeof a3.cancelBubble && (a3.cancelBubble = true), this.isPropagationStopped = pd2);
    }, persist: function() {
    }, isPersistent: pd2 });
    return b2;
  }
  var sd2 = { eventPhase: 0, bubbles: 0, cancelable: 0, timeStamp: function(a2) {
    return a2.timeStamp || Date.now();
  }, defaultPrevented: 0, isTrusted: 0 }, td2 = rd2(sd2), ud2 = A({}, sd2, { view: 0, detail: 0 }), vd2 = rd2(ud2), wd2, xd2, yd2, Ad2 = A({}, ud2, { screenX: 0, screenY: 0, clientX: 0, clientY: 0, pageX: 0, pageY: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, getModifierState: zd2, button: 0, buttons: 0, relatedTarget: function(a2) {
    return void 0 === a2.relatedTarget ? a2.fromElement === a2.srcElement ? a2.toElement : a2.fromElement : a2.relatedTarget;
  }, movementX: function(a2) {
    if ("movementX" in a2) return a2.movementX;
    a2 !== yd2 && (yd2 && "mousemove" === a2.type ? (wd2 = a2.screenX - yd2.screenX, xd2 = a2.screenY - yd2.screenY) : xd2 = wd2 = 0, yd2 = a2);
    return wd2;
  }, movementY: function(a2) {
    return "movementY" in a2 ? a2.movementY : xd2;
  } }), Bd2 = rd2(Ad2), Cd2 = A({}, Ad2, { dataTransfer: 0 }), Dd2 = rd2(Cd2), Ed2 = A({}, ud2, { relatedTarget: 0 }), Fd2 = rd2(Ed2), Gd2 = A({}, sd2, { animationName: 0, elapsedTime: 0, pseudoElement: 0 }), Hd2 = rd2(Gd2), Id2 = A({}, sd2, { clipboardData: function(a2) {
    return "clipboardData" in a2 ? a2.clipboardData : window.clipboardData;
  } }), Jd2 = rd2(Id2), Kd2 = A({}, sd2, { data: 0 }), Ld2 = rd2(Kd2), Md2 = {
    Esc: "Escape",
    Spacebar: " ",
    Left: "ArrowLeft",
    Up: "ArrowUp",
    Right: "ArrowRight",
    Down: "ArrowDown",
    Del: "Delete",
    Win: "OS",
    Menu: "ContextMenu",
    Apps: "ContextMenu",
    Scroll: "ScrollLock",
    MozPrintableKey: "Unidentified"
  }, Nd2 = {
    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"
  }, Od2 = { Alt: "altKey", Control: "ctrlKey", Meta: "metaKey", Shift: "shiftKey" };
  function Pd2(a2) {
    var b2 = this.nativeEvent;
    return b2.getModifierState ? b2.getModifierState(a2) : (a2 = Od2[a2]) ? !!b2[a2] : false;
  }
  function zd2() {
    return Pd2;
  }
  var Qd2 = A({}, ud2, { key: function(a2) {
    if (a2.key) {
      var b2 = Md2[a2.key] || a2.key;
      if ("Unidentified" !== b2) return b2;
    }
    return "keypress" === a2.type ? (a2 = od2(a2), 13 === a2 ? "Enter" : String.fromCharCode(a2)) : "keydown" === a2.type || "keyup" === a2.type ? Nd2[a2.keyCode] || "Unidentified" : "";
  }, code: 0, location: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, repeat: 0, locale: 0, getModifierState: zd2, charCode: function(a2) {
    return "keypress" === a2.type ? od2(a2) : 0;
  }, keyCode: function(a2) {
    return "keydown" === a2.type || "keyup" === a2.type ? a2.keyCode : 0;
  }, which: function(a2) {
    return "keypress" === a2.type ? od2(a2) : "keydown" === a2.type || "keyup" === a2.type ? a2.keyCode : 0;
  } }), Rd2 = rd2(Qd2), Sd2 = A({}, Ad2, { pointerId: 0, width: 0, height: 0, pressure: 0, tangentialPressure: 0, tiltX: 0, tiltY: 0, twist: 0, pointerType: 0, isPrimary: 0 }), Td2 = rd2(Sd2), Ud2 = A({}, ud2, { touches: 0, targetTouches: 0, changedTouches: 0, altKey: 0, metaKey: 0, ctrlKey: 0, shiftKey: 0, getModifierState: zd2 }), Vd2 = rd2(Ud2), Wd2 = A({}, sd2, { propertyName: 0, elapsedTime: 0, pseudoElement: 0 }), Xd2 = rd2(Wd2), Yd2 = A({}, Ad2, {
    deltaX: function(a2) {
      return "deltaX" in a2 ? a2.deltaX : "wheelDeltaX" in a2 ? -a2.wheelDeltaX : 0;
    },
    deltaY: function(a2) {
      return "deltaY" in a2 ? a2.deltaY : "wheelDeltaY" in a2 ? -a2.wheelDeltaY : "wheelDelta" in a2 ? -a2.wheelDelta : 0;
    },
    deltaZ: 0,
    deltaMode: 0
  }), Zd2 = rd2(Yd2), $d2 = [9, 13, 27, 32], ae = ia2 && "CompositionEvent" in window, be2 = null;
  ia2 && "documentMode" in document && (be2 = document.documentMode);
  var ce2 = ia2 && "TextEvent" in window && !be2, de2 = ia2 && (!ae || be2 && 8 < be2 && 11 >= be2), ee2 = String.fromCharCode(32), fe2 = false;
  function ge2(a2, b2) {
    switch (a2) {
      case "keyup":
        return -1 !== $d2.indexOf(b2.keyCode);
      case "keydown":
        return 229 !== b2.keyCode;
      case "keypress":
      case "mousedown":
      case "focusout":
        return true;
      default:
        return false;
    }
  }
  function he2(a2) {
    a2 = a2.detail;
    return "object" === typeof a2 && "data" in a2 ? a2.data : null;
  }
  var ie2 = false;
  function je(a2, b2) {
    switch (a2) {
      case "compositionend":
        return he2(b2);
      case "keypress":
        if (32 !== b2.which) return null;
        fe2 = true;
        return ee2;
      case "textInput":
        return a2 = b2.data, a2 === ee2 && fe2 ? null : a2;
      default:
        return null;
    }
  }
  function ke2(a2, b2) {
    if (ie2) return "compositionend" === a2 || !ae && ge2(a2, b2) ? (a2 = nd2(), md2 = ld2 = kd2 = null, ie2 = false, a2) : null;
    switch (a2) {
      case "paste":
        return null;
      case "keypress":
        if (!(b2.ctrlKey || b2.altKey || b2.metaKey) || b2.ctrlKey && b2.altKey) {
          if (b2.char && 1 < b2.char.length) return b2.char;
          if (b2.which) return String.fromCharCode(b2.which);
        }
        return null;
      case "compositionend":
        return de2 && "ko" !== b2.locale ? null : b2.data;
      default:
        return null;
    }
  }
  var le2 = { 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 me2(a2) {
    var b2 = a2 && a2.nodeName && a2.nodeName.toLowerCase();
    return "input" === b2 ? !!le2[a2.type] : "textarea" === b2 ? true : false;
  }
  function ne(a2, b2, c, d) {
    Eb(d);
    b2 = oe2(b2, "onChange");
    0 < b2.length && (c = new td2("onChange", "change", null, c, d), a2.push({ event: c, listeners: b2 }));
  }
  var pe2 = null, qe = null;
  function re2(a2) {
    se2(a2, 0);
  }
  function te2(a2) {
    var b2 = ue2(a2);
    if (Wa2(b2)) return a2;
  }
  function ve2(a2, b2) {
    if ("change" === a2) return b2;
  }
  var we2 = false;
  if (ia2) {
    var xe2;
    if (ia2) {
      var ye2 = "oninput" in document;
      if (!ye2) {
        var ze2 = document.createElement("div");
        ze2.setAttribute("oninput", "return;");
        ye2 = "function" === typeof ze2.oninput;
      }
      xe2 = ye2;
    } else xe2 = false;
    we2 = xe2 && (!document.documentMode || 9 < document.documentMode);
  }
  function Ae2() {
    pe2 && (pe2.detachEvent("onpropertychange", Be2), qe = pe2 = null);
  }
  function Be2(a2) {
    if ("value" === a2.propertyName && te2(qe)) {
      var b2 = [];
      ne(b2, qe, a2, xb(a2));
      Jb(re2, b2);
    }
  }
  function Ce2(a2, b2, c) {
    "focusin" === a2 ? (Ae2(), pe2 = b2, qe = c, pe2.attachEvent("onpropertychange", Be2)) : "focusout" === a2 && Ae2();
  }
  function De2(a2) {
    if ("selectionchange" === a2 || "keyup" === a2 || "keydown" === a2) return te2(qe);
  }
  function Ee2(a2, b2) {
    if ("click" === a2) return te2(b2);
  }
  function Fe(a2, b2) {
    if ("input" === a2 || "change" === a2) return te2(b2);
  }
  function Ge2(a2, b2) {
    return a2 === b2 && (0 !== a2 || 1 / a2 === 1 / b2) || a2 !== a2 && b2 !== b2;
  }
  var He2 = "function" === typeof Object.is ? Object.is : Ge2;
  function Ie2(a2, b2) {
    if (He2(a2, b2)) return true;
    if ("object" !== typeof a2 || null === a2 || "object" !== typeof b2 || null === b2) return false;
    var c = Object.keys(a2), d = Object.keys(b2);
    if (c.length !== d.length) return false;
    for (d = 0; d < c.length; d++) {
      var e2 = c[d];
      if (!ja2.call(b2, e2) || !He2(a2[e2], b2[e2])) return false;
    }
    return true;
  }
  function Je2(a2) {
    for (; a2 && a2.firstChild; ) a2 = a2.firstChild;
    return a2;
  }
  function Ke2(a2, b2) {
    var c = Je2(a2);
    a2 = 0;
    for (var d; c; ) {
      if (3 === c.nodeType) {
        d = a2 + c.textContent.length;
        if (a2 <= b2 && d >= b2) return { node: c, offset: b2 - a2 };
        a2 = d;
      }
      a: {
        for (; c; ) {
          if (c.nextSibling) {
            c = c.nextSibling;
            break a;
          }
          c = c.parentNode;
        }
        c = void 0;
      }
      c = Je2(c);
    }
  }
  function Le2(a2, b2) {
    return a2 && b2 ? a2 === b2 ? true : a2 && 3 === a2.nodeType ? false : b2 && 3 === b2.nodeType ? Le2(a2, b2.parentNode) : "contains" in a2 ? a2.contains(b2) : a2.compareDocumentPosition ? !!(a2.compareDocumentPosition(b2) & 16) : false : false;
  }
  function Me2() {
    for (var a2 = window, b2 = Xa2(); b2 instanceof a2.HTMLIFrameElement; ) {
      try {
        var c = "string" === typeof b2.contentWindow.location.href;
      } catch (d) {
        c = false;
      }
      if (c) a2 = b2.contentWindow;
      else break;
      b2 = Xa2(a2.document);
    }
    return b2;
  }
  function Ne2(a2) {
    var b2 = a2 && a2.nodeName && a2.nodeName.toLowerCase();
    return b2 && ("input" === b2 && ("text" === a2.type || "search" === a2.type || "tel" === a2.type || "url" === a2.type || "password" === a2.type) || "textarea" === b2 || "true" === a2.contentEditable);
  }
  function Oe(a2) {
    var b2 = Me2(), c = a2.focusedElem, d = a2.selectionRange;
    if (b2 !== c && c && c.ownerDocument && Le2(c.ownerDocument.documentElement, c)) {
      if (null !== d && Ne2(c)) {
        if (b2 = d.start, a2 = d.end, void 0 === a2 && (a2 = b2), "selectionStart" in c) c.selectionStart = b2, c.selectionEnd = Math.min(a2, c.value.length);
        else if (a2 = (b2 = c.ownerDocument || document) && b2.defaultView || window, a2.getSelection) {
          a2 = a2.getSelection();
          var e2 = c.textContent.length, f2 = Math.min(d.start, e2);
          d = void 0 === d.end ? f2 : Math.min(d.end, e2);
          !a2.extend && f2 > d && (e2 = d, d = f2, f2 = e2);
          e2 = Ke2(c, f2);
          var g2 = Ke2(
            c,
            d
          );
          e2 && g2 && (1 !== a2.rangeCount || a2.anchorNode !== e2.node || a2.anchorOffset !== e2.offset || a2.focusNode !== g2.node || a2.focusOffset !== g2.offset) && (b2 = b2.createRange(), b2.setStart(e2.node, e2.offset), a2.removeAllRanges(), f2 > d ? (a2.addRange(b2), a2.extend(g2.node, g2.offset)) : (b2.setEnd(g2.node, g2.offset), a2.addRange(b2)));
        }
      }
      b2 = [];
      for (a2 = c; a2 = a2.parentNode; ) 1 === a2.nodeType && b2.push({ element: a2, left: a2.scrollLeft, top: a2.scrollTop });
      "function" === typeof c.focus && c.focus();
      for (c = 0; c < b2.length; c++) a2 = b2[c], a2.element.scrollLeft = a2.left, a2.element.scrollTop = a2.top;
    }
  }
  var Pe2 = ia2 && "documentMode" in document && 11 >= document.documentMode, Qe2 = null, Re2 = null, Se2 = null, Te2 = false;
  function Ue2(a2, b2, c) {
    var d = c.window === c ? c.document : 9 === c.nodeType ? c : c.ownerDocument;
    Te2 || null == Qe2 || Qe2 !== Xa2(d) || (d = Qe2, "selectionStart" in d && Ne2(d) ? d = { start: d.selectionStart, end: d.selectionEnd } : (d = (d.ownerDocument && d.ownerDocument.defaultView || window).getSelection(), d = { anchorNode: d.anchorNode, anchorOffset: d.anchorOffset, focusNode: d.focusNode, focusOffset: d.focusOffset }), Se2 && Ie2(Se2, d) || (Se2 = d, d = oe2(Re2, "onSelect"), 0 < d.length && (b2 = new td2("onSelect", "select", null, b2, c), a2.push({ event: b2, listeners: d }), b2.target = Qe2)));
  }
  function Ve2(a2, b2) {
    var c = {};
    c[a2.toLowerCase()] = b2.toLowerCase();
    c["Webkit" + a2] = "webkit" + b2;
    c["Moz" + a2] = "moz" + b2;
    return c;
  }
  var We = { animationend: Ve2("Animation", "AnimationEnd"), animationiteration: Ve2("Animation", "AnimationIteration"), animationstart: Ve2("Animation", "AnimationStart"), transitionend: Ve2("Transition", "TransitionEnd") }, Xe2 = {}, Ye2 = {};
  ia2 && (Ye2 = document.createElement("div").style, "AnimationEvent" in window || (delete We.animationend.animation, delete We.animationiteration.animation, delete We.animationstart.animation), "TransitionEvent" in window || delete We.transitionend.transition);
  function Ze(a2) {
    if (Xe2[a2]) return Xe2[a2];
    if (!We[a2]) return a2;
    var b2 = We[a2], c;
    for (c in b2) if (b2.hasOwnProperty(c) && c in Ye2) return Xe2[a2] = b2[c];
    return a2;
  }
  var $e = Ze("animationend"), af2 = Ze("animationiteration"), bf2 = Ze("animationstart"), cf2 = Ze("transitionend"), df2 = /* @__PURE__ */ new Map(), ef2 = "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".split(" ");
  function ff2(a2, b2) {
    df2.set(a2, b2);
    fa(b2, [a2]);
  }
  for (var gf2 = 0; gf2 < ef2.length; gf2++) {
    var hf2 = ef2[gf2], jf2 = hf2.toLowerCase(), kf2 = hf2[0].toUpperCase() + hf2.slice(1);
    ff2(jf2, "on" + kf2);
  }
  ff2($e, "onAnimationEnd");
  ff2(af2, "onAnimationIteration");
  ff2(bf2, "onAnimationStart");
  ff2("dblclick", "onDoubleClick");
  ff2("focusin", "onFocus");
  ff2("focusout", "onBlur");
  ff2(cf2, "onTransitionEnd");
  ha2("onMouseEnter", ["mouseout", "mouseover"]);
  ha2("onMouseLeave", ["mouseout", "mouseover"]);
  ha2("onPointerEnter", ["pointerout", "pointerover"]);
  ha2("onPointerLeave", ["pointerout", "pointerover"]);
  fa("onChange", "change click focusin focusout input keydown keyup selectionchange".split(" "));
  fa("onSelect", "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));
  fa("onBeforeInput", ["compositionend", "keypress", "textInput", "paste"]);
  fa("onCompositionEnd", "compositionend focusout keydown keypress keyup mousedown".split(" "));
  fa("onCompositionStart", "compositionstart focusout keydown keypress keyup mousedown".split(" "));
  fa("onCompositionUpdate", "compositionupdate focusout keydown keypress keyup mousedown".split(" "));
  var lf2 = "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "), mf2 = new Set("cancel close invalid load scroll toggle".split(" ").concat(lf2));
  function nf2(a2, b2, c) {
    var d = a2.type || "unknown-event";
    a2.currentTarget = c;
    Ub(d, b2, void 0, a2);
    a2.currentTarget = null;
  }
  function se2(a2, b2) {
    b2 = 0 !== (b2 & 4);
    for (var c = 0; c < a2.length; c++) {
      var d = a2[c], e2 = d.event;
      d = d.listeners;
      a: {
        var f2 = void 0;
        if (b2) for (var g2 = d.length - 1; 0 <= g2; g2--) {
          var h2 = d[g2], k2 = h2.instance, l2 = h2.currentTarget;
          h2 = h2.listener;
          if (k2 !== f2 && e2.isPropagationStopped()) break a;
          nf2(e2, h2, l2);
          f2 = k2;
        }
        else for (g2 = 0; g2 < d.length; g2++) {
          h2 = d[g2];
          k2 = h2.instance;
          l2 = h2.currentTarget;
          h2 = h2.listener;
          if (k2 !== f2 && e2.isPropagationStopped()) break a;
          nf2(e2, h2, l2);
          f2 = k2;
        }
      }
    }
    if (Qb) throw a2 = Rb, Qb = false, Rb = null, a2;
  }
  function D2(a2, b2) {
    var c = b2[of2];
    void 0 === c && (c = b2[of2] = /* @__PURE__ */ new Set());
    var d = a2 + "__bubble";
    c.has(d) || (pf2(b2, a2, 2, false), c.add(d));
  }
  function qf2(a2, b2, c) {
    var d = 0;
    b2 && (d |= 4);
    pf2(c, a2, d, b2);
  }
  var rf2 = "_reactListening" + Math.random().toString(36).slice(2);
  function sf2(a2) {
    if (!a2[rf2]) {
      a2[rf2] = true;
      da.forEach(function(b3) {
        "selectionchange" !== b3 && (mf2.has(b3) || qf2(b3, false, a2), qf2(b3, true, a2));
      });
      var b2 = 9 === a2.nodeType ? a2 : a2.ownerDocument;
      null === b2 || b2[rf2] || (b2[rf2] = true, qf2("selectionchange", false, b2));
    }
  }
  function pf2(a2, b2, c, d) {
    switch (jd2(b2)) {
      case 1:
        var e2 = ed2;
        break;
      case 4:
        e2 = gd2;
        break;
      default:
        e2 = fd2;
    }
    c = e2.bind(null, b2, c, a2);
    e2 = void 0;
    !Lb || "touchstart" !== b2 && "touchmove" !== b2 && "wheel" !== b2 || (e2 = true);
    d ? void 0 !== e2 ? a2.addEventListener(b2, c, { capture: true, passive: e2 }) : a2.addEventListener(b2, c, true) : void 0 !== e2 ? a2.addEventListener(b2, c, { passive: e2 }) : a2.addEventListener(b2, c, false);
  }
  function hd2(a2, b2, c, d, e2) {
    var f2 = d;
    if (0 === (b2 & 1) && 0 === (b2 & 2) && null !== d) a: for (; ; ) {
      if (null === d) return;
      var g2 = d.tag;
      if (3 === g2 || 4 === g2) {
        var h2 = d.stateNode.containerInfo;
        if (h2 === e2 || 8 === h2.nodeType && h2.parentNode === e2) break;
        if (4 === g2) for (g2 = d.return; null !== g2; ) {
          var k2 = g2.tag;
          if (3 === k2 || 4 === k2) {
            if (k2 = g2.stateNode.containerInfo, k2 === e2 || 8 === k2.nodeType && k2.parentNode === e2) return;
          }
          g2 = g2.return;
        }
        for (; null !== h2; ) {
          g2 = Wc2(h2);
          if (null === g2) return;
          k2 = g2.tag;
          if (5 === k2 || 6 === k2) {
            d = f2 = g2;
            continue a;
          }
          h2 = h2.parentNode;
        }
      }
      d = d.return;
    }
    Jb(function() {
      var d2 = f2, e3 = xb(c), g3 = [];
      a: {
        var h3 = df2.get(a2);
        if (void 0 !== h3) {
          var k3 = td2, n = a2;
          switch (a2) {
            case "keypress":
              if (0 === od2(c)) break a;
            case "keydown":
            case "keyup":
              k3 = Rd2;
              break;
            case "focusin":
              n = "focus";
              k3 = Fd2;
              break;
            case "focusout":
              n = "blur";
              k3 = Fd2;
              break;
            case "beforeblur":
            case "afterblur":
              k3 = Fd2;
              break;
            case "click":
              if (2 === c.button) break a;
            case "auxclick":
            case "dblclick":
            case "mousedown":
            case "mousemove":
            case "mouseup":
            case "mouseout":
            case "mouseover":
            case "contextmenu":
              k3 = Bd2;
              break;
            case "drag":
            case "dragend":
            case "dragenter":
            case "dragexit":
            case "dragleave":
            case "dragover":
            case "dragstart":
            case "drop":
              k3 = Dd2;
              break;
            case "touchcancel":
            case "touchend":
            case "touchmove":
            case "touchstart":
              k3 = Vd2;
              break;
            case $e:
            case af2:
            case bf2:
              k3 = Hd2;
              break;
            case cf2:
              k3 = Xd2;
              break;
            case "scroll":
              k3 = vd2;
              break;
            case "wheel":
              k3 = Zd2;
              break;
            case "copy":
            case "cut":
            case "paste":
              k3 = Jd2;
              break;
            case "gotpointercapture":
            case "lostpointercapture":
            case "pointercancel":
            case "pointerdown":
            case "pointermove":
            case "pointerout":
            case "pointerover":
            case "pointerup":
              k3 = Td2;
          }
          var t2 = 0 !== (b2 & 4), J2 = !t2 && "scroll" === a2, x2 = t2 ? null !== h3 ? h3 + "Capture" : null : h3;
          t2 = [];
          for (var w2 = d2, u2; null !== w2; ) {
            u2 = w2;
            var F2 = u2.stateNode;
            5 === u2.tag && null !== F2 && (u2 = F2, null !== x2 && (F2 = Kb(w2, x2), null != F2 && t2.push(tf2(w2, F2, u2))));
            if (J2) break;
            w2 = w2.return;
          }
          0 < t2.length && (h3 = new k3(h3, n, null, c, e3), g3.push({ event: h3, listeners: t2 }));
        }
      }
      if (0 === (b2 & 7)) {
        a: {
          h3 = "mouseover" === a2 || "pointerover" === a2;
          k3 = "mouseout" === a2 || "pointerout" === a2;
          if (h3 && c !== wb && (n = c.relatedTarget || c.fromElement) && (Wc2(n) || n[uf2])) break a;
          if (k3 || h3) {
            h3 = e3.window === e3 ? e3 : (h3 = e3.ownerDocument) ? h3.defaultView || h3.parentWindow : window;
            if (k3) {
              if (n = c.relatedTarget || c.toElement, k3 = d2, n = n ? Wc2(n) : null, null !== n && (J2 = Vb(n), n !== J2 || 5 !== n.tag && 6 !== n.tag)) n = null;
            } else k3 = null, n = d2;
            if (k3 !== n) {
              t2 = Bd2;
              F2 = "onMouseLeave";
              x2 = "onMouseEnter";
              w2 = "mouse";
              if ("pointerout" === a2 || "pointerover" === a2) t2 = Td2, F2 = "onPointerLeave", x2 = "onPointerEnter", w2 = "pointer";
              J2 = null == k3 ? h3 : ue2(k3);
              u2 = null == n ? h3 : ue2(n);
              h3 = new t2(F2, w2 + "leave", k3, c, e3);
              h3.target = J2;
              h3.relatedTarget = u2;
              F2 = null;
              Wc2(e3) === d2 && (t2 = new t2(x2, w2 + "enter", n, c, e3), t2.target = u2, t2.relatedTarget = J2, F2 = t2);
              J2 = F2;
              if (k3 && n) b: {
                t2 = k3;
                x2 = n;
                w2 = 0;
                for (u2 = t2; u2; u2 = vf2(u2)) w2++;
                u2 = 0;
                for (F2 = x2; F2; F2 = vf2(F2)) u2++;
                for (; 0 < w2 - u2; ) t2 = vf2(t2), w2--;
                for (; 0 < u2 - w2; ) x2 = vf2(x2), u2--;
                for (; w2--; ) {
                  if (t2 === x2 || null !== x2 && t2 === x2.alternate) break b;
                  t2 = vf2(t2);
                  x2 = vf2(x2);
                }
                t2 = null;
              }
              else t2 = null;
              null !== k3 && wf2(g3, h3, k3, t2, false);
              null !== n && null !== J2 && wf2(g3, J2, n, t2, true);
            }
          }
        }
        a: {
          h3 = d2 ? ue2(d2) : window;
          k3 = h3.nodeName && h3.nodeName.toLowerCase();
          if ("select" === k3 || "input" === k3 && "file" === h3.type) var na2 = ve2;
          else if (me2(h3)) if (we2) na2 = Fe;
          else {
            na2 = De2;
            var xa2 = Ce2;
          }
          else (k3 = h3.nodeName) && "input" === k3.toLowerCase() && ("checkbox" === h3.type || "radio" === h3.type) && (na2 = Ee2);
          if (na2 && (na2 = na2(a2, d2))) {
            ne(g3, na2, c, e3);
            break a;
          }
          xa2 && xa2(a2, h3, d2);
          "focusout" === a2 && (xa2 = h3._wrapperState) && xa2.controlled && "number" === h3.type && cb(h3, "number", h3.value);
        }
        xa2 = d2 ? ue2(d2) : window;
        switch (a2) {
          case "focusin":
            if (me2(xa2) || "true" === xa2.contentEditable) Qe2 = xa2, Re2 = d2, Se2 = null;
            break;
          case "focusout":
            Se2 = Re2 = Qe2 = null;
            break;
          case "mousedown":
            Te2 = true;
            break;
          case "contextmenu":
          case "mouseup":
          case "dragend":
            Te2 = false;
            Ue2(g3, c, e3);
            break;
          case "selectionchange":
            if (Pe2) break;
          case "keydown":
          case "keyup":
            Ue2(g3, c, e3);
        }
        var $a2;
        if (ae) b: {
          switch (a2) {
            case "compositionstart":
              var ba2 = "onCompositionStart";
              break b;
            case "compositionend":
              ba2 = "onCompositionEnd";
              break b;
            case "compositionupdate":
              ba2 = "onCompositionUpdate";
              break b;
          }
          ba2 = void 0;
        }
        else ie2 ? ge2(a2, c) && (ba2 = "onCompositionEnd") : "keydown" === a2 && 229 === c.keyCode && (ba2 = "onCompositionStart");
        ba2 && (de2 && "ko" !== c.locale && (ie2 || "onCompositionStart" !== ba2 ? "onCompositionEnd" === ba2 && ie2 && ($a2 = nd2()) : (kd2 = e3, ld2 = "value" in kd2 ? kd2.value : kd2.textContent, ie2 = true)), xa2 = oe2(d2, ba2), 0 < xa2.length && (ba2 = new Ld2(ba2, a2, null, c, e3), g3.push({ event: ba2, listeners: xa2 }), $a2 ? ba2.data = $a2 : ($a2 = he2(c), null !== $a2 && (ba2.data = $a2))));
        if ($a2 = ce2 ? je(a2, c) : ke2(a2, c)) d2 = oe2(d2, "onBeforeInput"), 0 < d2.length && (e3 = new Ld2("onBeforeInput", "beforeinput", null, c, e3), g3.push({ event: e3, listeners: d2 }), e3.data = $a2);
      }
      se2(g3, b2);
    });
  }
  function tf2(a2, b2, c) {
    return { instance: a2, listener: b2, currentTarget: c };
  }
  function oe2(a2, b2) {
    for (var c = b2 + "Capture", d = []; null !== a2; ) {
      var e2 = a2, f2 = e2.stateNode;
      5 === e2.tag && null !== f2 && (e2 = f2, f2 = Kb(a2, c), null != f2 && d.unshift(tf2(a2, f2, e2)), f2 = Kb(a2, b2), null != f2 && d.push(tf2(a2, f2, e2)));
      a2 = a2.return;
    }
    return d;
  }
  function vf2(a2) {
    if (null === a2) return null;
    do
      a2 = a2.return;
    while (a2 && 5 !== a2.tag);
    return a2 ? a2 : null;
  }
  function wf2(a2, b2, c, d, e2) {
    for (var f2 = b2._reactName, g2 = []; null !== c && c !== d; ) {
      var h2 = c, k2 = h2.alternate, l2 = h2.stateNode;
      if (null !== k2 && k2 === d) break;
      5 === h2.tag && null !== l2 && (h2 = l2, e2 ? (k2 = Kb(c, f2), null != k2 && g2.unshift(tf2(c, k2, h2))) : e2 || (k2 = Kb(c, f2), null != k2 && g2.push(tf2(c, k2, h2))));
      c = c.return;
    }
    0 !== g2.length && a2.push({ event: b2, listeners: g2 });
  }
  var xf2 = /\r\n?/g, yf2 = /\u0000|\uFFFD/g;
  function zf2(a2) {
    return ("string" === typeof a2 ? a2 : "" + a2).replace(xf2, "\n").replace(yf2, "");
  }
  function Af2(a2, b2, c) {
    b2 = zf2(b2);
    if (zf2(a2) !== b2 && c) throw Error(p2(425));
  }
  function Bf2() {
  }
  var Cf2 = null, Df2 = null;
  function Ef2(a2, b2) {
    return "textarea" === a2 || "noscript" === a2 || "string" === typeof b2.children || "number" === typeof b2.children || "object" === typeof b2.dangerouslySetInnerHTML && null !== b2.dangerouslySetInnerHTML && null != b2.dangerouslySetInnerHTML.__html;
  }
  var Ff2 = "function" === typeof setTimeout ? setTimeout : void 0, Gf2 = "function" === typeof clearTimeout ? clearTimeout : void 0, Hf2 = "function" === typeof Promise ? Promise : void 0, Jf2 = "function" === typeof queueMicrotask ? queueMicrotask : "undefined" !== typeof Hf2 ? function(a2) {
    return Hf2.resolve(null).then(a2).catch(If2);
  } : Ff2;
  function If2(a2) {
    setTimeout(function() {
      throw a2;
    });
  }
  function Kf2(a2, b2) {
    var c = b2, d = 0;
    do {
      var e2 = c.nextSibling;
      a2.removeChild(c);
      if (e2 && 8 === e2.nodeType) if (c = e2.data, "/$" === c) {
        if (0 === d) {
          a2.removeChild(e2);
          bd2(b2);
          return;
        }
        d--;
      } else "$" !== c && "$?" !== c && "$!" !== c || d++;
      c = e2;
    } while (c);
    bd2(b2);
  }
  function Lf2(a2) {
    for (; null != a2; a2 = a2.nextSibling) {
      var b2 = a2.nodeType;
      if (1 === b2 || 3 === b2) break;
      if (8 === b2) {
        b2 = a2.data;
        if ("$" === b2 || "$!" === b2 || "$?" === b2) break;
        if ("/$" === b2) return null;
      }
    }
    return a2;
  }
  function Mf2(a2) {
    a2 = a2.previousSibling;
    for (var b2 = 0; a2; ) {
      if (8 === a2.nodeType) {
        var c = a2.data;
        if ("$" === c || "$!" === c || "$?" === c) {
          if (0 === b2) return a2;
          b2--;
        } else "/$" === c && b2++;
      }
      a2 = a2.previousSibling;
    }
    return null;
  }
  var Nf2 = Math.random().toString(36).slice(2), Of2 = "__reactFiber$" + Nf2, Pf2 = "__reactProps$" + Nf2, uf2 = "__reactContainer$" + Nf2, of2 = "__reactEvents$" + Nf2, Qf2 = "__reactListeners$" + Nf2, Rf2 = "__reactHandles$" + Nf2;
  function Wc2(a2) {
    var b2 = a2[Of2];
    if (b2) return b2;
    for (var c = a2.parentNode; c; ) {
      if (b2 = c[uf2] || c[Of2]) {
        c = b2.alternate;
        if (null !== b2.child || null !== c && null !== c.child) for (a2 = Mf2(a2); null !== a2; ) {
          if (c = a2[Of2]) return c;
          a2 = Mf2(a2);
        }
        return b2;
      }
      a2 = c;
      c = a2.parentNode;
    }
    return null;
  }
  function Cb(a2) {
    a2 = a2[Of2] || a2[uf2];
    return !a2 || 5 !== a2.tag && 6 !== a2.tag && 13 !== a2.tag && 3 !== a2.tag ? null : a2;
  }
  function ue2(a2) {
    if (5 === a2.tag || 6 === a2.tag) return a2.stateNode;
    throw Error(p2(33));
  }
  function Db(a2) {
    return a2[Pf2] || null;
  }
  var Sf2 = [], Tf2 = -1;
  function Uf2(a2) {
    return { current: a2 };
  }
  function E2(a2) {
    0 > Tf2 || (a2.current = Sf2[Tf2], Sf2[Tf2] = null, Tf2--);
  }
  function G2(a2, b2) {
    Tf2++;
    Sf2[Tf2] = a2.current;
    a2.current = b2;
  }
  var Vf2 = {}, H2 = Uf2(Vf2), Wf2 = Uf2(false), Xf2 = Vf2;
  function Yf2(a2, b2) {
    var c = a2.type.contextTypes;
    if (!c) return Vf2;
    var d = a2.stateNode;
    if (d && d.__reactInternalMemoizedUnmaskedChildContext === b2) return d.__reactInternalMemoizedMaskedChildContext;
    var e2 = {}, f2;
    for (f2 in c) e2[f2] = b2[f2];
    d && (a2 = a2.stateNode, a2.__reactInternalMemoizedUnmaskedChildContext = b2, a2.__reactInternalMemoizedMaskedChildContext = e2);
    return e2;
  }
  function Zf2(a2) {
    a2 = a2.childContextTypes;
    return null !== a2 && void 0 !== a2;
  }
  function $f2() {
    E2(Wf2);
    E2(H2);
  }
  function ag(a2, b2, c) {
    if (H2.current !== Vf2) throw Error(p2(168));
    G2(H2, b2);
    G2(Wf2, c);
  }
  function bg(a2, b2, c) {
    var d = a2.stateNode;
    b2 = b2.childContextTypes;
    if ("function" !== typeof d.getChildContext) return c;
    d = d.getChildContext();
    for (var e2 in d) if (!(e2 in b2)) throw Error(p2(108, Ra2(a2) || "Unknown", e2));
    return A({}, c, d);
  }
  function cg(a2) {
    a2 = (a2 = a2.stateNode) && a2.__reactInternalMemoizedMergedChildContext || Vf2;
    Xf2 = H2.current;
    G2(H2, a2);
    G2(Wf2, Wf2.current);
    return true;
  }
  function dg(a2, b2, c) {
    var d = a2.stateNode;
    if (!d) throw Error(p2(169));
    c ? (a2 = bg(a2, b2, Xf2), d.__reactInternalMemoizedMergedChildContext = a2, E2(Wf2), E2(H2), G2(H2, a2)) : E2(Wf2);
    G2(Wf2, c);
  }
  var eg = null, fg = false, gg = false;
  function hg(a2) {
    null === eg ? eg = [a2] : eg.push(a2);
  }
  function ig(a2) {
    fg = true;
    hg(a2);
  }
  function jg() {
    if (!gg && null !== eg) {
      gg = true;
      var a2 = 0, b2 = C;
      try {
        var c = eg;
        for (C = 1; a2 < c.length; a2++) {
          var d = c[a2];
          do
            d = d(true);
          while (null !== d);
        }
        eg = null;
        fg = false;
      } catch (e2) {
        throw null !== eg && (eg = eg.slice(a2 + 1)), ac(fc, jg), e2;
      } finally {
        C = b2, gg = false;
      }
    }
    return null;
  }
  var kg = [], lg = 0, mg = null, ng = 0, og = [], pg = 0, qg = null, rg = 1, sg = "";
  function tg(a2, b2) {
    kg[lg++] = ng;
    kg[lg++] = mg;
    mg = a2;
    ng = b2;
  }
  function ug(a2, b2, c) {
    og[pg++] = rg;
    og[pg++] = sg;
    og[pg++] = qg;
    qg = a2;
    var d = rg;
    a2 = sg;
    var e2 = 32 - oc2(d) - 1;
    d &= ~(1 << e2);
    c += 1;
    var f2 = 32 - oc2(b2) + e2;
    if (30 < f2) {
      var g2 = e2 - e2 % 5;
      f2 = (d & (1 << g2) - 1).toString(32);
      d >>= g2;
      e2 -= g2;
      rg = 1 << 32 - oc2(b2) + e2 | c << e2 | d;
      sg = f2 + a2;
    } else rg = 1 << f2 | c << e2 | d, sg = a2;
  }
  function vg(a2) {
    null !== a2.return && (tg(a2, 1), ug(a2, 1, 0));
  }
  function wg(a2) {
    for (; a2 === mg; ) mg = kg[--lg], kg[lg] = null, ng = kg[--lg], kg[lg] = null;
    for (; a2 === qg; ) qg = og[--pg], og[pg] = null, sg = og[--pg], og[pg] = null, rg = og[--pg], og[pg] = null;
  }
  var xg = null, yg = null, I2 = false, zg = null;
  function Ag(a2, b2) {
    var c = Bg(5, null, null, 0);
    c.elementType = "DELETED";
    c.stateNode = b2;
    c.return = a2;
    b2 = a2.deletions;
    null === b2 ? (a2.deletions = [c], a2.flags |= 16) : b2.push(c);
  }
  function Cg(a2, b2) {
    switch (a2.tag) {
      case 5:
        var c = a2.type;
        b2 = 1 !== b2.nodeType || c.toLowerCase() !== b2.nodeName.toLowerCase() ? null : b2;
        return null !== b2 ? (a2.stateNode = b2, xg = a2, yg = Lf2(b2.firstChild), true) : false;
      case 6:
        return b2 = "" === a2.pendingProps || 3 !== b2.nodeType ? null : b2, null !== b2 ? (a2.stateNode = b2, xg = a2, yg = null, true) : false;
      case 13:
        return b2 = 8 !== b2.nodeType ? null : b2, null !== b2 ? (c = null !== qg ? { id: rg, overflow: sg } : null, a2.memoizedState = { dehydrated: b2, treeContext: c, retryLane: 1073741824 }, c = Bg(18, null, null, 0), c.stateNode = b2, c.return = a2, a2.child = c, xg = a2, yg = null, true) : false;
      default:
        return false;
    }
  }
  function Dg(a2) {
    return 0 !== (a2.mode & 1) && 0 === (a2.flags & 128);
  }
  function Eg(a2) {
    if (I2) {
      var b2 = yg;
      if (b2) {
        var c = b2;
        if (!Cg(a2, b2)) {
          if (Dg(a2)) throw Error(p2(418));
          b2 = Lf2(c.nextSibling);
          var d = xg;
          b2 && Cg(a2, b2) ? Ag(d, c) : (a2.flags = a2.flags & -4097 | 2, I2 = false, xg = a2);
        }
      } else {
        if (Dg(a2)) throw Error(p2(418));
        a2.flags = a2.flags & -4097 | 2;
        I2 = false;
        xg = a2;
      }
    }
  }
  function Fg(a2) {
    for (a2 = a2.return; null !== a2 && 5 !== a2.tag && 3 !== a2.tag && 13 !== a2.tag; ) a2 = a2.return;
    xg = a2;
  }
  function Gg(a2) {
    if (a2 !== xg) return false;
    if (!I2) return Fg(a2), I2 = true, false;
    var b2;
    (b2 = 3 !== a2.tag) && !(b2 = 5 !== a2.tag) && (b2 = a2.type, b2 = "head" !== b2 && "body" !== b2 && !Ef2(a2.type, a2.memoizedProps));
    if (b2 && (b2 = yg)) {
      if (Dg(a2)) throw Hg(), Error(p2(418));
      for (; b2; ) Ag(a2, b2), b2 = Lf2(b2.nextSibling);
    }
    Fg(a2);
    if (13 === a2.tag) {
      a2 = a2.memoizedState;
      a2 = null !== a2 ? a2.dehydrated : null;
      if (!a2) throw Error(p2(317));
      a: {
        a2 = a2.nextSibling;
        for (b2 = 0; a2; ) {
          if (8 === a2.nodeType) {
            var c = a2.data;
            if ("/$" === c) {
              if (0 === b2) {
                yg = Lf2(a2.nextSibling);
                break a;
              }
              b2--;
            } else "$" !== c && "$!" !== c && "$?" !== c || b2++;
          }
          a2 = a2.nextSibling;
        }
        yg = null;
      }
    } else yg = xg ? Lf2(a2.stateNode.nextSibling) : null;
    return true;
  }
  function Hg() {
    for (var a2 = yg; a2; ) a2 = Lf2(a2.nextSibling);
  }
  function Ig() {
    yg = xg = null;
    I2 = false;
  }
  function Jg(a2) {
    null === zg ? zg = [a2] : zg.push(a2);
  }
  var Kg = ua2.ReactCurrentBatchConfig;
  function Lg(a2, b2, c) {
    a2 = c.ref;
    if (null !== a2 && "function" !== typeof a2 && "object" !== typeof a2) {
      if (c._owner) {
        c = c._owner;
        if (c) {
          if (1 !== c.tag) throw Error(p2(309));
          var d = c.stateNode;
        }
        if (!d) throw Error(p2(147, a2));
        var e2 = d, f2 = "" + a2;
        if (null !== b2 && null !== b2.ref && "function" === typeof b2.ref && b2.ref._stringRef === f2) return b2.ref;
        b2 = function(a3) {
          var b3 = e2.refs;
          null === a3 ? delete b3[f2] : b3[f2] = a3;
        };
        b2._stringRef = f2;
        return b2;
      }
      if ("string" !== typeof a2) throw Error(p2(284));
      if (!c._owner) throw Error(p2(290, a2));
    }
    return a2;
  }
  function Mg(a2, b2) {
    a2 = Object.prototype.toString.call(b2);
    throw Error(p2(31, "[object Object]" === a2 ? "object with keys {" + Object.keys(b2).join(", ") + "}" : a2));
  }
  function Ng(a2) {
    var b2 = a2._init;
    return b2(a2._payload);
  }
  function Og(a2) {
    function b2(b3, c2) {
      if (a2) {
        var d2 = b3.deletions;
        null === d2 ? (b3.deletions = [c2], b3.flags |= 16) : d2.push(c2);
      }
    }
    function c(c2, d2) {
      if (!a2) return null;
      for (; null !== d2; ) b2(c2, d2), d2 = d2.sibling;
      return null;
    }
    function d(a3, b3) {
      for (a3 = /* @__PURE__ */ new Map(); null !== b3; ) null !== b3.key ? a3.set(b3.key, b3) : a3.set(b3.index, b3), b3 = b3.sibling;
      return a3;
    }
    function e2(a3, b3) {
      a3 = Pg(a3, b3);
      a3.index = 0;
      a3.sibling = null;
      return a3;
    }
    function f2(b3, c2, d2) {
      b3.index = d2;
      if (!a2) return b3.flags |= 1048576, c2;
      d2 = b3.alternate;
      if (null !== d2) return d2 = d2.index, d2 < c2 ? (b3.flags |= 2, c2) : d2;
      b3.flags |= 2;
      return c2;
    }
    function g2(b3) {
      a2 && null === b3.alternate && (b3.flags |= 2);
      return b3;
    }
    function h2(a3, b3, c2, d2) {
      if (null === b3 || 6 !== b3.tag) return b3 = Qg(c2, a3.mode, d2), b3.return = a3, b3;
      b3 = e2(b3, c2);
      b3.return = a3;
      return b3;
    }
    function k2(a3, b3, c2, d2) {
      var f3 = c2.type;
      if (f3 === ya2) return m2(a3, b3, c2.props.children, d2, c2.key);
      if (null !== b3 && (b3.elementType === f3 || "object" === typeof f3 && null !== f3 && f3.$$typeof === Ha2 && Ng(f3) === b3.type)) return d2 = e2(b3, c2.props), d2.ref = Lg(a3, b3, c2), d2.return = a3, d2;
      d2 = Rg(c2.type, c2.key, c2.props, null, a3.mode, d2);
      d2.ref = Lg(a3, b3, c2);
      d2.return = a3;
      return d2;
    }
    function l2(a3, b3, c2, d2) {
      if (null === b3 || 4 !== b3.tag || b3.stateNode.containerInfo !== c2.containerInfo || b3.stateNode.implementation !== c2.implementation) return b3 = Sg(c2, a3.mode, d2), b3.return = a3, b3;
      b3 = e2(b3, c2.children || []);
      b3.return = a3;
      return b3;
    }
    function m2(a3, b3, c2, d2, f3) {
      if (null === b3 || 7 !== b3.tag) return b3 = Tg(c2, a3.mode, d2, f3), b3.return = a3, b3;
      b3 = e2(b3, c2);
      b3.return = a3;
      return b3;
    }
    function q2(a3, b3, c2) {
      if ("string" === typeof b3 && "" !== b3 || "number" === typeof b3) return b3 = Qg("" + b3, a3.mode, c2), b3.return = a3, b3;
      if ("object" === typeof b3 && null !== b3) {
        switch (b3.$$typeof) {
          case va2:
            return c2 = Rg(b3.type, b3.key, b3.props, null, a3.mode, c2), c2.ref = Lg(a3, null, b3), c2.return = a3, c2;
          case wa2:
            return b3 = Sg(b3, a3.mode, c2), b3.return = a3, b3;
          case Ha2:
            var d2 = b3._init;
            return q2(a3, d2(b3._payload), c2);
        }
        if (eb(b3) || Ka2(b3)) return b3 = Tg(b3, a3.mode, c2, null), b3.return = a3, b3;
        Mg(a3, b3);
      }
      return null;
    }
    function r2(a3, b3, c2, d2) {
      var e3 = null !== b3 ? b3.key : null;
      if ("string" === typeof c2 && "" !== c2 || "number" === typeof c2) return null !== e3 ? null : h2(a3, b3, "" + c2, d2);
      if ("object" === typeof c2 && null !== c2) {
        switch (c2.$$typeof) {
          case va2:
            return c2.key === e3 ? k2(a3, b3, c2, d2) : null;
          case wa2:
            return c2.key === e3 ? l2(a3, b3, c2, d2) : null;
          case Ha2:
            return e3 = c2._init, r2(
              a3,
              b3,
              e3(c2._payload),
              d2
            );
        }
        if (eb(c2) || Ka2(c2)) return null !== e3 ? null : m2(a3, b3, c2, d2, null);
        Mg(a3, c2);
      }
      return null;
    }
    function y(a3, b3, c2, d2, e3) {
      if ("string" === typeof d2 && "" !== d2 || "number" === typeof d2) return a3 = a3.get(c2) || null, h2(b3, a3, "" + d2, e3);
      if ("object" === typeof d2 && null !== d2) {
        switch (d2.$$typeof) {
          case va2:
            return a3 = a3.get(null === d2.key ? c2 : d2.key) || null, k2(b3, a3, d2, e3);
          case wa2:
            return a3 = a3.get(null === d2.key ? c2 : d2.key) || null, l2(b3, a3, d2, e3);
          case Ha2:
            var f3 = d2._init;
            return y(a3, b3, c2, f3(d2._payload), e3);
        }
        if (eb(d2) || Ka2(d2)) return a3 = a3.get(c2) || null, m2(b3, a3, d2, e3, null);
        Mg(b3, d2);
      }
      return null;
    }
    function n(e3, g3, h3, k3) {
      for (var l3 = null, m3 = null, u2 = g3, w2 = g3 = 0, x2 = null; null !== u2 && w2 < h3.length; w2++) {
        u2.index > w2 ? (x2 = u2, u2 = null) : x2 = u2.sibling;
        var n2 = r2(e3, u2, h3[w2], k3);
        if (null === n2) {
          null === u2 && (u2 = x2);
          break;
        }
        a2 && u2 && null === n2.alternate && b2(e3, u2);
        g3 = f2(n2, g3, w2);
        null === m3 ? l3 = n2 : m3.sibling = n2;
        m3 = n2;
        u2 = x2;
      }
      if (w2 === h3.length) return c(e3, u2), I2 && tg(e3, w2), l3;
      if (null === u2) {
        for (; w2 < h3.length; w2++) u2 = q2(e3, h3[w2], k3), null !== u2 && (g3 = f2(u2, g3, w2), null === m3 ? l3 = u2 : m3.sibling = u2, m3 = u2);
        I2 && tg(e3, w2);
        return l3;
      }
      for (u2 = d(e3, u2); w2 < h3.length; w2++) x2 = y(u2, e3, w2, h3[w2], k3), null !== x2 && (a2 && null !== x2.alternate && u2.delete(null === x2.key ? w2 : x2.key), g3 = f2(x2, g3, w2), null === m3 ? l3 = x2 : m3.sibling = x2, m3 = x2);
      a2 && u2.forEach(function(a3) {
        return b2(e3, a3);
      });
      I2 && tg(e3, w2);
      return l3;
    }
    function t2(e3, g3, h3, k3) {
      var l3 = Ka2(h3);
      if ("function" !== typeof l3) throw Error(p2(150));
      h3 = l3.call(h3);
      if (null == h3) throw Error(p2(151));
      for (var u2 = l3 = null, m3 = g3, w2 = g3 = 0, x2 = null, n2 = h3.next(); null !== m3 && !n2.done; w2++, n2 = h3.next()) {
        m3.index > w2 ? (x2 = m3, m3 = null) : x2 = m3.sibling;
        var t3 = r2(e3, m3, n2.value, k3);
        if (null === t3) {
          null === m3 && (m3 = x2);
          break;
        }
        a2 && m3 && null === t3.alternate && b2(e3, m3);
        g3 = f2(t3, g3, w2);
        null === u2 ? l3 = t3 : u2.sibling = t3;
        u2 = t3;
        m3 = x2;
      }
      if (n2.done) return c(
        e3,
        m3
      ), I2 && tg(e3, w2), l3;
      if (null === m3) {
        for (; !n2.done; w2++, n2 = h3.next()) n2 = q2(e3, n2.value, k3), null !== n2 && (g3 = f2(n2, g3, w2), null === u2 ? l3 = n2 : u2.sibling = n2, u2 = n2);
        I2 && tg(e3, w2);
        return l3;
      }
      for (m3 = d(e3, m3); !n2.done; w2++, n2 = h3.next()) n2 = y(m3, e3, w2, n2.value, k3), null !== n2 && (a2 && null !== n2.alternate && m3.delete(null === n2.key ? w2 : n2.key), g3 = f2(n2, g3, w2), null === u2 ? l3 = n2 : u2.sibling = n2, u2 = n2);
      a2 && m3.forEach(function(a3) {
        return b2(e3, a3);
      });
      I2 && tg(e3, w2);
      return l3;
    }
    function J2(a3, d2, f3, h3) {
      "object" === typeof f3 && null !== f3 && f3.type === ya2 && null === f3.key && (f3 = f3.props.children);
      if ("object" === typeof f3 && null !== f3) {
        switch (f3.$$typeof) {
          case va2:
            a: {
              for (var k3 = f3.key, l3 = d2; null !== l3; ) {
                if (l3.key === k3) {
                  k3 = f3.type;
                  if (k3 === ya2) {
                    if (7 === l3.tag) {
                      c(a3, l3.sibling);
                      d2 = e2(l3, f3.props.children);
                      d2.return = a3;
                      a3 = d2;
                      break a;
                    }
                  } else if (l3.elementType === k3 || "object" === typeof k3 && null !== k3 && k3.$$typeof === Ha2 && Ng(k3) === l3.type) {
                    c(a3, l3.sibling);
                    d2 = e2(l3, f3.props);
                    d2.ref = Lg(a3, l3, f3);
                    d2.return = a3;
                    a3 = d2;
                    break a;
                  }
                  c(a3, l3);
                  break;
                } else b2(a3, l3);
                l3 = l3.sibling;
              }
              f3.type === ya2 ? (d2 = Tg(f3.props.children, a3.mode, h3, f3.key), d2.return = a3, a3 = d2) : (h3 = Rg(f3.type, f3.key, f3.props, null, a3.mode, h3), h3.ref = Lg(a3, d2, f3), h3.return = a3, a3 = h3);
            }
            return g2(a3);
          case wa2:
            a: {
              for (l3 = f3.key; null !== d2; ) {
                if (d2.key === l3) if (4 === d2.tag && d2.stateNode.containerInfo === f3.containerInfo && d2.stateNode.implementation === f3.implementation) {
                  c(a3, d2.sibling);
                  d2 = e2(d2, f3.children || []);
                  d2.return = a3;
                  a3 = d2;
                  break a;
                } else {
                  c(a3, d2);
                  break;
                }
                else b2(a3, d2);
                d2 = d2.sibling;
              }
              d2 = Sg(f3, a3.mode, h3);
              d2.return = a3;
              a3 = d2;
            }
            return g2(a3);
          case Ha2:
            return l3 = f3._init, J2(a3, d2, l3(f3._payload), h3);
        }
        if (eb(f3)) return n(a3, d2, f3, h3);
        if (Ka2(f3)) return t2(a3, d2, f3, h3);
        Mg(a3, f3);
      }
      return "string" === typeof f3 && "" !== f3 || "number" === typeof f3 ? (f3 = "" + f3, null !== d2 && 6 === d2.tag ? (c(a3, d2.sibling), d2 = e2(d2, f3), d2.return = a3, a3 = d2) : (c(a3, d2), d2 = Qg(f3, a3.mode, h3), d2.return = a3, a3 = d2), g2(a3)) : c(a3, d2);
    }
    return J2;
  }
  var Ug = Og(true), Vg = Og(false), Wg = Uf2(null), Xg = null, Yg = null, Zg = null;
  function $g() {
    Zg = Yg = Xg = null;
  }
  function ah(a2) {
    var b2 = Wg.current;
    E2(Wg);
    a2._currentValue = b2;
  }
  function bh(a2, b2, c) {
    for (; null !== a2; ) {
      var d = a2.alternate;
      (a2.childLanes & b2) !== b2 ? (a2.childLanes |= b2, null !== d && (d.childLanes |= b2)) : null !== d && (d.childLanes & b2) !== b2 && (d.childLanes |= b2);
      if (a2 === c) break;
      a2 = a2.return;
    }
  }
  function ch(a2, b2) {
    Xg = a2;
    Zg = Yg = null;
    a2 = a2.dependencies;
    null !== a2 && null !== a2.firstContext && (0 !== (a2.lanes & b2) && (dh = true), a2.firstContext = null);
  }
  function eh(a2) {
    var b2 = a2._currentValue;
    if (Zg !== a2) if (a2 = { context: a2, memoizedValue: b2, next: null }, null === Yg) {
      if (null === Xg) throw Error(p2(308));
      Yg = a2;
      Xg.dependencies = { lanes: 0, firstContext: a2 };
    } else Yg = Yg.next = a2;
    return b2;
  }
  var fh = null;
  function gh(a2) {
    null === fh ? fh = [a2] : fh.push(a2);
  }
  function hh(a2, b2, c, d) {
    var e2 = b2.interleaved;
    null === e2 ? (c.next = c, gh(b2)) : (c.next = e2.next, e2.next = c);
    b2.interleaved = c;
    return ih(a2, d);
  }
  function ih(a2, b2) {
    a2.lanes |= b2;
    var c = a2.alternate;
    null !== c && (c.lanes |= b2);
    c = a2;
    for (a2 = a2.return; null !== a2; ) a2.childLanes |= b2, c = a2.alternate, null !== c && (c.childLanes |= b2), c = a2, a2 = a2.return;
    return 3 === c.tag ? c.stateNode : null;
  }
  var jh = false;
  function kh(a2) {
    a2.updateQueue = { baseState: a2.memoizedState, firstBaseUpdate: null, lastBaseUpdate: null, shared: { pending: null, interleaved: null, lanes: 0 }, effects: null };
  }
  function lh(a2, b2) {
    a2 = a2.updateQueue;
    b2.updateQueue === a2 && (b2.updateQueue = { baseState: a2.baseState, firstBaseUpdate: a2.firstBaseUpdate, lastBaseUpdate: a2.lastBaseUpdate, shared: a2.shared, effects: a2.effects });
  }
  function mh(a2, b2) {
    return { eventTime: a2, lane: b2, tag: 0, payload: null, callback: null, next: null };
  }
  function nh(a2, b2, c) {
    var d = a2.updateQueue;
    if (null === d) return null;
    d = d.shared;
    if (0 !== (K2 & 2)) {
      var e2 = d.pending;
      null === e2 ? b2.next = b2 : (b2.next = e2.next, e2.next = b2);
      d.pending = b2;
      return ih(a2, c);
    }
    e2 = d.interleaved;
    null === e2 ? (b2.next = b2, gh(d)) : (b2.next = e2.next, e2.next = b2);
    d.interleaved = b2;
    return ih(a2, c);
  }
  function oh(a2, b2, c) {
    b2 = b2.updateQueue;
    if (null !== b2 && (b2 = b2.shared, 0 !== (c & 4194240))) {
      var d = b2.lanes;
      d &= a2.pendingLanes;
      c |= d;
      b2.lanes = c;
      Cc2(a2, c);
    }
  }
  function ph(a2, b2) {
    var c = a2.updateQueue, d = a2.alternate;
    if (null !== d && (d = d.updateQueue, c === d)) {
      var e2 = null, f2 = null;
      c = c.firstBaseUpdate;
      if (null !== c) {
        do {
          var g2 = { eventTime: c.eventTime, lane: c.lane, tag: c.tag, payload: c.payload, callback: c.callback, next: null };
          null === f2 ? e2 = f2 = g2 : f2 = f2.next = g2;
          c = c.next;
        } while (null !== c);
        null === f2 ? e2 = f2 = b2 : f2 = f2.next = b2;
      } else e2 = f2 = b2;
      c = { baseState: d.baseState, firstBaseUpdate: e2, lastBaseUpdate: f2, shared: d.shared, effects: d.effects };
      a2.updateQueue = c;
      return;
    }
    a2 = c.lastBaseUpdate;
    null === a2 ? c.firstBaseUpdate = b2 : a2.next = b2;
    c.lastBaseUpdate = b2;
  }
  function qh(a2, b2, c, d) {
    var e2 = a2.updateQueue;
    jh = false;
    var f2 = e2.firstBaseUpdate, g2 = e2.lastBaseUpdate, h2 = e2.shared.pending;
    if (null !== h2) {
      e2.shared.pending = null;
      var k2 = h2, l2 = k2.next;
      k2.next = null;
      null === g2 ? f2 = l2 : g2.next = l2;
      g2 = k2;
      var m2 = a2.alternate;
      null !== m2 && (m2 = m2.updateQueue, h2 = m2.lastBaseUpdate, h2 !== g2 && (null === h2 ? m2.firstBaseUpdate = l2 : h2.next = l2, m2.lastBaseUpdate = k2));
    }
    if (null !== f2) {
      var q2 = e2.baseState;
      g2 = 0;
      m2 = l2 = k2 = null;
      h2 = f2;
      do {
        var r2 = h2.lane, y = h2.eventTime;
        if ((d & r2) === r2) {
          null !== m2 && (m2 = m2.next = {
            eventTime: y,
            lane: 0,
            tag: h2.tag,
            payload: h2.payload,
            callback: h2.callback,
            next: null
          });
          a: {
            var n = a2, t2 = h2;
            r2 = b2;
            y = c;
            switch (t2.tag) {
              case 1:
                n = t2.payload;
                if ("function" === typeof n) {
                  q2 = n.call(y, q2, r2);
                  break a;
                }
                q2 = n;
                break a;
              case 3:
                n.flags = n.flags & -65537 | 128;
              case 0:
                n = t2.payload;
                r2 = "function" === typeof n ? n.call(y, q2, r2) : n;
                if (null === r2 || void 0 === r2) break a;
                q2 = A({}, q2, r2);
                break a;
              case 2:
                jh = true;
            }
          }
          null !== h2.callback && 0 !== h2.lane && (a2.flags |= 64, r2 = e2.effects, null === r2 ? e2.effects = [h2] : r2.push(h2));
        } else y = { eventTime: y, lane: r2, tag: h2.tag, payload: h2.payload, callback: h2.callback, next: null }, null === m2 ? (l2 = m2 = y, k2 = q2) : m2 = m2.next = y, g2 |= r2;
        h2 = h2.next;
        if (null === h2) if (h2 = e2.shared.pending, null === h2) break;
        else r2 = h2, h2 = r2.next, r2.next = null, e2.lastBaseUpdate = r2, e2.shared.pending = null;
      } while (1);
      null === m2 && (k2 = q2);
      e2.baseState = k2;
      e2.firstBaseUpdate = l2;
      e2.lastBaseUpdate = m2;
      b2 = e2.shared.interleaved;
      if (null !== b2) {
        e2 = b2;
        do
          g2 |= e2.lane, e2 = e2.next;
        while (e2 !== b2);
      } else null === f2 && (e2.shared.lanes = 0);
      rh |= g2;
      a2.lanes = g2;
      a2.memoizedState = q2;
    }
  }
  function sh(a2, b2, c) {
    a2 = b2.effects;
    b2.effects = null;
    if (null !== a2) for (b2 = 0; b2 < a2.length; b2++) {
      var d = a2[b2], e2 = d.callback;
      if (null !== e2) {
        d.callback = null;
        d = c;
        if ("function" !== typeof e2) throw Error(p2(191, e2));
        e2.call(d);
      }
    }
  }
  var th = {}, uh = Uf2(th), vh = Uf2(th), wh = Uf2(th);
  function xh(a2) {
    if (a2 === th) throw Error(p2(174));
    return a2;
  }
  function yh(a2, b2) {
    G2(wh, b2);
    G2(vh, a2);
    G2(uh, th);
    a2 = b2.nodeType;
    switch (a2) {
      case 9:
      case 11:
        b2 = (b2 = b2.documentElement) ? b2.namespaceURI : lb(null, "");
        break;
      default:
        a2 = 8 === a2 ? b2.parentNode : b2, b2 = a2.namespaceURI || null, a2 = a2.tagName, b2 = lb(b2, a2);
    }
    E2(uh);
    G2(uh, b2);
  }
  function zh() {
    E2(uh);
    E2(vh);
    E2(wh);
  }
  function Ah(a2) {
    xh(wh.current);
    var b2 = xh(uh.current);
    var c = lb(b2, a2.type);
    b2 !== c && (G2(vh, a2), G2(uh, c));
  }
  function Bh(a2) {
    vh.current === a2 && (E2(uh), E2(vh));
  }
  var L2 = Uf2(0);
  function Ch(a2) {
    for (var b2 = a2; null !== b2; ) {
      if (13 === b2.tag) {
        var c = b2.memoizedState;
        if (null !== c && (c = c.dehydrated, null === c || "$?" === c.data || "$!" === c.data)) return b2;
      } else if (19 === b2.tag && void 0 !== b2.memoizedProps.revealOrder) {
        if (0 !== (b2.flags & 128)) return b2;
      } else if (null !== b2.child) {
        b2.child.return = b2;
        b2 = b2.child;
        continue;
      }
      if (b2 === a2) break;
      for (; null === b2.sibling; ) {
        if (null === b2.return || b2.return === a2) return null;
        b2 = b2.return;
      }
      b2.sibling.return = b2.return;
      b2 = b2.sibling;
    }
    return null;
  }
  var Dh = [];
  function Eh() {
    for (var a2 = 0; a2 < Dh.length; a2++) Dh[a2]._workInProgressVersionPrimary = null;
    Dh.length = 0;
  }
  var Fh = ua2.ReactCurrentDispatcher, Gh = ua2.ReactCurrentBatchConfig, Hh = 0, M2 = null, N2 = null, O2 = null, Ih = false, Jh = false, Kh = 0, Lh = 0;
  function P2() {
    throw Error(p2(321));
  }
  function Mh(a2, b2) {
    if (null === b2) return false;
    for (var c = 0; c < b2.length && c < a2.length; c++) if (!He2(a2[c], b2[c])) return false;
    return true;
  }
  function Nh(a2, b2, c, d, e2, f2) {
    Hh = f2;
    M2 = b2;
    b2.memoizedState = null;
    b2.updateQueue = null;
    b2.lanes = 0;
    Fh.current = null === a2 || null === a2.memoizedState ? Oh : Ph;
    a2 = c(d, e2);
    if (Jh) {
      f2 = 0;
      do {
        Jh = false;
        Kh = 0;
        if (25 <= f2) throw Error(p2(301));
        f2 += 1;
        O2 = N2 = null;
        b2.updateQueue = null;
        Fh.current = Qh;
        a2 = c(d, e2);
      } while (Jh);
    }
    Fh.current = Rh;
    b2 = null !== N2 && null !== N2.next;
    Hh = 0;
    O2 = N2 = M2 = null;
    Ih = false;
    if (b2) throw Error(p2(300));
    return a2;
  }
  function Sh() {
    var a2 = 0 !== Kh;
    Kh = 0;
    return a2;
  }
  function Th() {
    var a2 = { memoizedState: null, baseState: null, baseQueue: null, queue: null, next: null };
    null === O2 ? M2.memoizedState = O2 = a2 : O2 = O2.next = a2;
    return O2;
  }
  function Uh() {
    if (null === N2) {
      var a2 = M2.alternate;
      a2 = null !== a2 ? a2.memoizedState : null;
    } else a2 = N2.next;
    var b2 = null === O2 ? M2.memoizedState : O2.next;
    if (null !== b2) O2 = b2, N2 = a2;
    else {
      if (null === a2) throw Error(p2(310));
      N2 = a2;
      a2 = { memoizedState: N2.memoizedState, baseState: N2.baseState, baseQueue: N2.baseQueue, queue: N2.queue, next: null };
      null === O2 ? M2.memoizedState = O2 = a2 : O2 = O2.next = a2;
    }
    return O2;
  }
  function Vh(a2, b2) {
    return "function" === typeof b2 ? b2(a2) : b2;
  }
  function Wh(a2) {
    var b2 = Uh(), c = b2.queue;
    if (null === c) throw Error(p2(311));
    c.lastRenderedReducer = a2;
    var d = N2, e2 = d.baseQueue, f2 = c.pending;
    if (null !== f2) {
      if (null !== e2) {
        var g2 = e2.next;
        e2.next = f2.next;
        f2.next = g2;
      }
      d.baseQueue = e2 = f2;
      c.pending = null;
    }
    if (null !== e2) {
      f2 = e2.next;
      d = d.baseState;
      var h2 = g2 = null, k2 = null, l2 = f2;
      do {
        var m2 = l2.lane;
        if ((Hh & m2) === m2) null !== k2 && (k2 = k2.next = { lane: 0, action: l2.action, hasEagerState: l2.hasEagerState, eagerState: l2.eagerState, next: null }), d = l2.hasEagerState ? l2.eagerState : a2(d, l2.action);
        else {
          var q2 = {
            lane: m2,
            action: l2.action,
            hasEagerState: l2.hasEagerState,
            eagerState: l2.eagerState,
            next: null
          };
          null === k2 ? (h2 = k2 = q2, g2 = d) : k2 = k2.next = q2;
          M2.lanes |= m2;
          rh |= m2;
        }
        l2 = l2.next;
      } while (null !== l2 && l2 !== f2);
      null === k2 ? g2 = d : k2.next = h2;
      He2(d, b2.memoizedState) || (dh = true);
      b2.memoizedState = d;
      b2.baseState = g2;
      b2.baseQueue = k2;
      c.lastRenderedState = d;
    }
    a2 = c.interleaved;
    if (null !== a2) {
      e2 = a2;
      do
        f2 = e2.lane, M2.lanes |= f2, rh |= f2, e2 = e2.next;
      while (e2 !== a2);
    } else null === e2 && (c.lanes = 0);
    return [b2.memoizedState, c.dispatch];
  }
  function Xh(a2) {
    var b2 = Uh(), c = b2.queue;
    if (null === c) throw Error(p2(311));
    c.lastRenderedReducer = a2;
    var d = c.dispatch, e2 = c.pending, f2 = b2.memoizedState;
    if (null !== e2) {
      c.pending = null;
      var g2 = e2 = e2.next;
      do
        f2 = a2(f2, g2.action), g2 = g2.next;
      while (g2 !== e2);
      He2(f2, b2.memoizedState) || (dh = true);
      b2.memoizedState = f2;
      null === b2.baseQueue && (b2.baseState = f2);
      c.lastRenderedState = f2;
    }
    return [f2, d];
  }
  function Yh() {
  }
  function Zh(a2, b2) {
    var c = M2, d = Uh(), e2 = b2(), f2 = !He2(d.memoizedState, e2);
    f2 && (d.memoizedState = e2, dh = true);
    d = d.queue;
    $h(ai2.bind(null, c, d, a2), [a2]);
    if (d.getSnapshot !== b2 || f2 || null !== O2 && O2.memoizedState.tag & 1) {
      c.flags |= 2048;
      bi2(9, ci2.bind(null, c, d, e2, b2), void 0, null);
      if (null === Q2) throw Error(p2(349));
      0 !== (Hh & 30) || di2(c, b2, e2);
    }
    return e2;
  }
  function di2(a2, b2, c) {
    a2.flags |= 16384;
    a2 = { getSnapshot: b2, value: c };
    b2 = M2.updateQueue;
    null === b2 ? (b2 = { lastEffect: null, stores: null }, M2.updateQueue = b2, b2.stores = [a2]) : (c = b2.stores, null === c ? b2.stores = [a2] : c.push(a2));
  }
  function ci2(a2, b2, c, d) {
    b2.value = c;
    b2.getSnapshot = d;
    ei2(b2) && fi2(a2);
  }
  function ai2(a2, b2, c) {
    return c(function() {
      ei2(b2) && fi2(a2);
    });
  }
  function ei2(a2) {
    var b2 = a2.getSnapshot;
    a2 = a2.value;
    try {
      var c = b2();
      return !He2(a2, c);
    } catch (d) {
      return true;
    }
  }
  function fi2(a2) {
    var b2 = ih(a2, 1);
    null !== b2 && gi2(b2, a2, 1, -1);
  }
  function hi2(a2) {
    var b2 = Th();
    "function" === typeof a2 && (a2 = a2());
    b2.memoizedState = b2.baseState = a2;
    a2 = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: Vh, lastRenderedState: a2 };
    b2.queue = a2;
    a2 = a2.dispatch = ii2.bind(null, M2, a2);
    return [b2.memoizedState, a2];
  }
  function bi2(a2, b2, c, d) {
    a2 = { tag: a2, create: b2, destroy: c, deps: d, next: null };
    b2 = M2.updateQueue;
    null === b2 ? (b2 = { lastEffect: null, stores: null }, M2.updateQueue = b2, b2.lastEffect = a2.next = a2) : (c = b2.lastEffect, null === c ? b2.lastEffect = a2.next = a2 : (d = c.next, c.next = a2, a2.next = d, b2.lastEffect = a2));
    return a2;
  }
  function ji() {
    return Uh().memoizedState;
  }
  function ki2(a2, b2, c, d) {
    var e2 = Th();
    M2.flags |= a2;
    e2.memoizedState = bi2(1 | b2, c, void 0, void 0 === d ? null : d);
  }
  function li2(a2, b2, c, d) {
    var e2 = Uh();
    d = void 0 === d ? null : d;
    var f2 = void 0;
    if (null !== N2) {
      var g2 = N2.memoizedState;
      f2 = g2.destroy;
      if (null !== d && Mh(d, g2.deps)) {
        e2.memoizedState = bi2(b2, c, f2, d);
        return;
      }
    }
    M2.flags |= a2;
    e2.memoizedState = bi2(1 | b2, c, f2, d);
  }
  function mi2(a2, b2) {
    return ki2(8390656, 8, a2, b2);
  }
  function $h(a2, b2) {
    return li2(2048, 8, a2, b2);
  }
  function ni2(a2, b2) {
    return li2(4, 2, a2, b2);
  }
  function oi2(a2, b2) {
    return li2(4, 4, a2, b2);
  }
  function pi2(a2, b2) {
    if ("function" === typeof b2) return a2 = a2(), b2(a2), function() {
      b2(null);
    };
    if (null !== b2 && void 0 !== b2) return a2 = a2(), b2.current = a2, function() {
      b2.current = null;
    };
  }
  function qi2(a2, b2, c) {
    c = null !== c && void 0 !== c ? c.concat([a2]) : null;
    return li2(4, 4, pi2.bind(null, b2, a2), c);
  }
  function ri2() {
  }
  function si2(a2, b2) {
    var c = Uh();
    b2 = void 0 === b2 ? null : b2;
    var d = c.memoizedState;
    if (null !== d && null !== b2 && Mh(b2, d[1])) return d[0];
    c.memoizedState = [a2, b2];
    return a2;
  }
  function ti2(a2, b2) {
    var c = Uh();
    b2 = void 0 === b2 ? null : b2;
    var d = c.memoizedState;
    if (null !== d && null !== b2 && Mh(b2, d[1])) return d[0];
    a2 = a2();
    c.memoizedState = [a2, b2];
    return a2;
  }
  function ui2(a2, b2, c) {
    if (0 === (Hh & 21)) return a2.baseState && (a2.baseState = false, dh = true), a2.memoizedState = c;
    He2(c, b2) || (c = yc(), M2.lanes |= c, rh |= c, a2.baseState = true);
    return b2;
  }
  function vi2(a2, b2) {
    var c = C;
    C = 0 !== c && 4 > c ? c : 4;
    a2(true);
    var d = Gh.transition;
    Gh.transition = {};
    try {
      a2(false), b2();
    } finally {
      C = c, Gh.transition = d;
    }
  }
  function wi2() {
    return Uh().memoizedState;
  }
  function xi2(a2, b2, c) {
    var d = yi2(a2);
    c = { lane: d, action: c, hasEagerState: false, eagerState: null, next: null };
    if (zi(a2)) Ai2(b2, c);
    else if (c = hh(a2, b2, c, d), null !== c) {
      var e2 = R();
      gi2(c, a2, d, e2);
      Bi2(c, b2, d);
    }
  }
  function ii2(a2, b2, c) {
    var d = yi2(a2), e2 = { lane: d, action: c, hasEagerState: false, eagerState: null, next: null };
    if (zi(a2)) Ai2(b2, e2);
    else {
      var f2 = a2.alternate;
      if (0 === a2.lanes && (null === f2 || 0 === f2.lanes) && (f2 = b2.lastRenderedReducer, null !== f2)) try {
        var g2 = b2.lastRenderedState, h2 = f2(g2, c);
        e2.hasEagerState = true;
        e2.eagerState = h2;
        if (He2(h2, g2)) {
          var k2 = b2.interleaved;
          null === k2 ? (e2.next = e2, gh(b2)) : (e2.next = k2.next, k2.next = e2);
          b2.interleaved = e2;
          return;
        }
      } catch (l2) {
      } finally {
      }
      c = hh(a2, b2, e2, d);
      null !== c && (e2 = R(), gi2(c, a2, d, e2), Bi2(c, b2, d));
    }
  }
  function zi(a2) {
    var b2 = a2.alternate;
    return a2 === M2 || null !== b2 && b2 === M2;
  }
  function Ai2(a2, b2) {
    Jh = Ih = true;
    var c = a2.pending;
    null === c ? b2.next = b2 : (b2.next = c.next, c.next = b2);
    a2.pending = b2;
  }
  function Bi2(a2, b2, c) {
    if (0 !== (c & 4194240)) {
      var d = b2.lanes;
      d &= a2.pendingLanes;
      c |= d;
      b2.lanes = c;
      Cc2(a2, c);
    }
  }
  var Rh = { readContext: eh, useCallback: P2, useContext: P2, useEffect: P2, useImperativeHandle: P2, useInsertionEffect: P2, useLayoutEffect: P2, useMemo: P2, useReducer: P2, useRef: P2, useState: P2, useDebugValue: P2, useDeferredValue: P2, useTransition: P2, useMutableSource: P2, useSyncExternalStore: P2, useId: P2, unstable_isNewReconciler: false }, Oh = { readContext: eh, useCallback: function(a2, b2) {
    Th().memoizedState = [a2, void 0 === b2 ? null : b2];
    return a2;
  }, useContext: eh, useEffect: mi2, useImperativeHandle: function(a2, b2, c) {
    c = null !== c && void 0 !== c ? c.concat([a2]) : null;
    return ki2(
      4194308,
      4,
      pi2.bind(null, b2, a2),
      c
    );
  }, useLayoutEffect: function(a2, b2) {
    return ki2(4194308, 4, a2, b2);
  }, useInsertionEffect: function(a2, b2) {
    return ki2(4, 2, a2, b2);
  }, useMemo: function(a2, b2) {
    var c = Th();
    b2 = void 0 === b2 ? null : b2;
    a2 = a2();
    c.memoizedState = [a2, b2];
    return a2;
  }, useReducer: function(a2, b2, c) {
    var d = Th();
    b2 = void 0 !== c ? c(b2) : b2;
    d.memoizedState = d.baseState = b2;
    a2 = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: a2, lastRenderedState: b2 };
    d.queue = a2;
    a2 = a2.dispatch = xi2.bind(null, M2, a2);
    return [d.memoizedState, a2];
  }, useRef: function(a2) {
    var b2 = Th();
    a2 = { current: a2 };
    return b2.memoizedState = a2;
  }, useState: hi2, useDebugValue: ri2, useDeferredValue: function(a2) {
    return Th().memoizedState = a2;
  }, useTransition: function() {
    var a2 = hi2(false), b2 = a2[0];
    a2 = vi2.bind(null, a2[1]);
    Th().memoizedState = a2;
    return [b2, a2];
  }, useMutableSource: function() {
  }, useSyncExternalStore: function(a2, b2, c) {
    var d = M2, e2 = Th();
    if (I2) {
      if (void 0 === c) throw Error(p2(407));
      c = c();
    } else {
      c = b2();
      if (null === Q2) throw Error(p2(349));
      0 !== (Hh & 30) || di2(d, b2, c);
    }
    e2.memoizedState = c;
    var f2 = { value: c, getSnapshot: b2 };
    e2.queue = f2;
    mi2(ai2.bind(
      null,
      d,
      f2,
      a2
    ), [a2]);
    d.flags |= 2048;
    bi2(9, ci2.bind(null, d, f2, c, b2), void 0, null);
    return c;
  }, useId: function() {
    var a2 = Th(), b2 = Q2.identifierPrefix;
    if (I2) {
      var c = sg;
      var d = rg;
      c = (d & ~(1 << 32 - oc2(d) - 1)).toString(32) + c;
      b2 = ":" + b2 + "R" + c;
      c = Kh++;
      0 < c && (b2 += "H" + c.toString(32));
      b2 += ":";
    } else c = Lh++, b2 = ":" + b2 + "r" + c.toString(32) + ":";
    return a2.memoizedState = b2;
  }, unstable_isNewReconciler: false }, Ph = {
    readContext: eh,
    useCallback: si2,
    useContext: eh,
    useEffect: $h,
    useImperativeHandle: qi2,
    useInsertionEffect: ni2,
    useLayoutEffect: oi2,
    useMemo: ti2,
    useReducer: Wh,
    useRef: ji,
    useState: function() {
      return Wh(Vh);
    },
    useDebugValue: ri2,
    useDeferredValue: function(a2) {
      var b2 = Uh();
      return ui2(b2, N2.memoizedState, a2);
    },
    useTransition: function() {
      var a2 = Wh(Vh)[0], b2 = Uh().memoizedState;
      return [a2, b2];
    },
    useMutableSource: Yh,
    useSyncExternalStore: Zh,
    useId: wi2,
    unstable_isNewReconciler: false
  }, Qh = { readContext: eh, useCallback: si2, useContext: eh, useEffect: $h, useImperativeHandle: qi2, useInsertionEffect: ni2, useLayoutEffect: oi2, useMemo: ti2, useReducer: Xh, useRef: ji, useState: function() {
    return Xh(Vh);
  }, useDebugValue: ri2, useDeferredValue: function(a2) {
    var b2 = Uh();
    return null === N2 ? b2.memoizedState = a2 : ui2(b2, N2.memoizedState, a2);
  }, useTransition: function() {
    var a2 = Xh(Vh)[0], b2 = Uh().memoizedState;
    return [a2, b2];
  }, useMutableSource: Yh, useSyncExternalStore: Zh, useId: wi2, unstable_isNewReconciler: false };
  function Ci2(a2, b2) {
    if (a2 && a2.defaultProps) {
      b2 = A({}, b2);
      a2 = a2.defaultProps;
      for (var c in a2) void 0 === b2[c] && (b2[c] = a2[c]);
      return b2;
    }
    return b2;
  }
  function Di2(a2, b2, c, d) {
    b2 = a2.memoizedState;
    c = c(d, b2);
    c = null === c || void 0 === c ? b2 : A({}, b2, c);
    a2.memoizedState = c;
    0 === a2.lanes && (a2.updateQueue.baseState = c);
  }
  var Ei2 = { isMounted: function(a2) {
    return (a2 = a2._reactInternals) ? Vb(a2) === a2 : false;
  }, enqueueSetState: function(a2, b2, c) {
    a2 = a2._reactInternals;
    var d = R(), e2 = yi2(a2), f2 = mh(d, e2);
    f2.payload = b2;
    void 0 !== c && null !== c && (f2.callback = c);
    b2 = nh(a2, f2, e2);
    null !== b2 && (gi2(b2, a2, e2, d), oh(b2, a2, e2));
  }, enqueueReplaceState: function(a2, b2, c) {
    a2 = a2._reactInternals;
    var d = R(), e2 = yi2(a2), f2 = mh(d, e2);
    f2.tag = 1;
    f2.payload = b2;
    void 0 !== c && null !== c && (f2.callback = c);
    b2 = nh(a2, f2, e2);
    null !== b2 && (gi2(b2, a2, e2, d), oh(b2, a2, e2));
  }, enqueueForceUpdate: function(a2, b2) {
    a2 = a2._reactInternals;
    var c = R(), d = yi2(a2), e2 = mh(c, d);
    e2.tag = 2;
    void 0 !== b2 && null !== b2 && (e2.callback = b2);
    b2 = nh(a2, e2, d);
    null !== b2 && (gi2(b2, a2, d, c), oh(b2, a2, d));
  } };
  function Fi2(a2, b2, c, d, e2, f2, g2) {
    a2 = a2.stateNode;
    return "function" === typeof a2.shouldComponentUpdate ? a2.shouldComponentUpdate(d, f2, g2) : b2.prototype && b2.prototype.isPureReactComponent ? !Ie2(c, d) || !Ie2(e2, f2) : true;
  }
  function Gi2(a2, b2, c) {
    var d = false, e2 = Vf2;
    var f2 = b2.contextType;
    "object" === typeof f2 && null !== f2 ? f2 = eh(f2) : (e2 = Zf2(b2) ? Xf2 : H2.current, d = b2.contextTypes, f2 = (d = null !== d && void 0 !== d) ? Yf2(a2, e2) : Vf2);
    b2 = new b2(c, f2);
    a2.memoizedState = null !== b2.state && void 0 !== b2.state ? b2.state : null;
    b2.updater = Ei2;
    a2.stateNode = b2;
    b2._reactInternals = a2;
    d && (a2 = a2.stateNode, a2.__reactInternalMemoizedUnmaskedChildContext = e2, a2.__reactInternalMemoizedMaskedChildContext = f2);
    return b2;
  }
  function Hi2(a2, b2, c, d) {
    a2 = b2.state;
    "function" === typeof b2.componentWillReceiveProps && b2.componentWillReceiveProps(c, d);
    "function" === typeof b2.UNSAFE_componentWillReceiveProps && b2.UNSAFE_componentWillReceiveProps(c, d);
    b2.state !== a2 && Ei2.enqueueReplaceState(b2, b2.state, null);
  }
  function Ii2(a2, b2, c, d) {
    var e2 = a2.stateNode;
    e2.props = c;
    e2.state = a2.memoizedState;
    e2.refs = {};
    kh(a2);
    var f2 = b2.contextType;
    "object" === typeof f2 && null !== f2 ? e2.context = eh(f2) : (f2 = Zf2(b2) ? Xf2 : H2.current, e2.context = Yf2(a2, f2));
    e2.state = a2.memoizedState;
    f2 = b2.getDerivedStateFromProps;
    "function" === typeof f2 && (Di2(a2, b2, f2, c), e2.state = a2.memoizedState);
    "function" === typeof b2.getDerivedStateFromProps || "function" === typeof e2.getSnapshotBeforeUpdate || "function" !== typeof e2.UNSAFE_componentWillMount && "function" !== typeof e2.componentWillMount || (b2 = e2.state, "function" === typeof e2.componentWillMount && e2.componentWillMount(), "function" === typeof e2.UNSAFE_componentWillMount && e2.UNSAFE_componentWillMount(), b2 !== e2.state && Ei2.enqueueReplaceState(e2, e2.state, null), qh(a2, c, e2, d), e2.state = a2.memoizedState);
    "function" === typeof e2.componentDidMount && (a2.flags |= 4194308);
  }
  function Ji2(a2, b2) {
    try {
      var c = "", d = b2;
      do
        c += Pa2(d), d = d.return;
      while (d);
      var e2 = c;
    } catch (f2) {
      e2 = "\nError generating stack: " + f2.message + "\n" + f2.stack;
    }
    return { value: a2, source: b2, stack: e2, digest: null };
  }
  function Ki2(a2, b2, c) {
    return { value: a2, source: null, stack: null != c ? c : null, digest: null != b2 ? b2 : null };
  }
  function Li2(a2, b2) {
    try {
      console.error(b2.value);
    } catch (c) {
      setTimeout(function() {
        throw c;
      });
    }
  }
  var Mi2 = "function" === typeof WeakMap ? WeakMap : Map;
  function Ni(a2, b2, c) {
    c = mh(-1, c);
    c.tag = 3;
    c.payload = { element: null };
    var d = b2.value;
    c.callback = function() {
      Oi || (Oi = true, Pi = d);
      Li2(a2, b2);
    };
    return c;
  }
  function Qi2(a2, b2, c) {
    c = mh(-1, c);
    c.tag = 3;
    var d = a2.type.getDerivedStateFromError;
    if ("function" === typeof d) {
      var e2 = b2.value;
      c.payload = function() {
        return d(e2);
      };
      c.callback = function() {
        Li2(a2, b2);
      };
    }
    var f2 = a2.stateNode;
    null !== f2 && "function" === typeof f2.componentDidCatch && (c.callback = function() {
      Li2(a2, b2);
      "function" !== typeof d && (null === Ri2 ? Ri2 = /* @__PURE__ */ new Set([this]) : Ri2.add(this));
      var c2 = b2.stack;
      this.componentDidCatch(b2.value, { componentStack: null !== c2 ? c2 : "" });
    });
    return c;
  }
  function Si2(a2, b2, c) {
    var d = a2.pingCache;
    if (null === d) {
      d = a2.pingCache = new Mi2();
      var e2 = /* @__PURE__ */ new Set();
      d.set(b2, e2);
    } else e2 = d.get(b2), void 0 === e2 && (e2 = /* @__PURE__ */ new Set(), d.set(b2, e2));
    e2.has(c) || (e2.add(c), a2 = Ti2.bind(null, a2, b2, c), b2.then(a2, a2));
  }
  function Ui(a2) {
    do {
      var b2;
      if (b2 = 13 === a2.tag) b2 = a2.memoizedState, b2 = null !== b2 ? null !== b2.dehydrated ? true : false : true;
      if (b2) return a2;
      a2 = a2.return;
    } while (null !== a2);
    return null;
  }
  function Vi2(a2, b2, c, d, e2) {
    if (0 === (a2.mode & 1)) return a2 === b2 ? a2.flags |= 65536 : (a2.flags |= 128, c.flags |= 131072, c.flags &= -52805, 1 === c.tag && (null === c.alternate ? c.tag = 17 : (b2 = mh(-1, 1), b2.tag = 2, nh(c, b2, 1))), c.lanes |= 1), a2;
    a2.flags |= 65536;
    a2.lanes = e2;
    return a2;
  }
  var Wi2 = ua2.ReactCurrentOwner, dh = false;
  function Xi2(a2, b2, c, d) {
    b2.child = null === a2 ? Vg(b2, null, c, d) : Ug(b2, a2.child, c, d);
  }
  function Yi2(a2, b2, c, d, e2) {
    c = c.render;
    var f2 = b2.ref;
    ch(b2, e2);
    d = Nh(a2, b2, c, d, f2, e2);
    c = Sh();
    if (null !== a2 && !dh) return b2.updateQueue = a2.updateQueue, b2.flags &= -2053, a2.lanes &= ~e2, Zi(a2, b2, e2);
    I2 && c && vg(b2);
    b2.flags |= 1;
    Xi2(a2, b2, d, e2);
    return b2.child;
  }
  function $i2(a2, b2, c, d, e2) {
    if (null === a2) {
      var f2 = c.type;
      if ("function" === typeof f2 && !aj(f2) && void 0 === f2.defaultProps && null === c.compare && void 0 === c.defaultProps) return b2.tag = 15, b2.type = f2, bj(a2, b2, f2, d, e2);
      a2 = Rg(c.type, null, d, b2, b2.mode, e2);
      a2.ref = b2.ref;
      a2.return = b2;
      return b2.child = a2;
    }
    f2 = a2.child;
    if (0 === (a2.lanes & e2)) {
      var g2 = f2.memoizedProps;
      c = c.compare;
      c = null !== c ? c : Ie2;
      if (c(g2, d) && a2.ref === b2.ref) return Zi(a2, b2, e2);
    }
    b2.flags |= 1;
    a2 = Pg(f2, d);
    a2.ref = b2.ref;
    a2.return = b2;
    return b2.child = a2;
  }
  function bj(a2, b2, c, d, e2) {
    if (null !== a2) {
      var f2 = a2.memoizedProps;
      if (Ie2(f2, d) && a2.ref === b2.ref) if (dh = false, b2.pendingProps = d = f2, 0 !== (a2.lanes & e2)) 0 !== (a2.flags & 131072) && (dh = true);
      else return b2.lanes = a2.lanes, Zi(a2, b2, e2);
    }
    return cj(a2, b2, c, d, e2);
  }
  function dj(a2, b2, c) {
    var d = b2.pendingProps, e2 = d.children, f2 = null !== a2 ? a2.memoizedState : null;
    if ("hidden" === d.mode) if (0 === (b2.mode & 1)) b2.memoizedState = { baseLanes: 0, cachePool: null, transitions: null }, G2(ej, fj), fj |= c;
    else {
      if (0 === (c & 1073741824)) return a2 = null !== f2 ? f2.baseLanes | c : c, b2.lanes = b2.childLanes = 1073741824, b2.memoizedState = { baseLanes: a2, cachePool: null, transitions: null }, b2.updateQueue = null, G2(ej, fj), fj |= a2, null;
      b2.memoizedState = { baseLanes: 0, cachePool: null, transitions: null };
      d = null !== f2 ? f2.baseLanes : c;
      G2(ej, fj);
      fj |= d;
    }
    else null !== f2 ? (d = f2.baseLanes | c, b2.memoizedState = null) : d = c, G2(ej, fj), fj |= d;
    Xi2(a2, b2, e2, c);
    return b2.child;
  }
  function gj(a2, b2) {
    var c = b2.ref;
    if (null === a2 && null !== c || null !== a2 && a2.ref !== c) b2.flags |= 512, b2.flags |= 2097152;
  }
  function cj(a2, b2, c, d, e2) {
    var f2 = Zf2(c) ? Xf2 : H2.current;
    f2 = Yf2(b2, f2);
    ch(b2, e2);
    c = Nh(a2, b2, c, d, f2, e2);
    d = Sh();
    if (null !== a2 && !dh) return b2.updateQueue = a2.updateQueue, b2.flags &= -2053, a2.lanes &= ~e2, Zi(a2, b2, e2);
    I2 && d && vg(b2);
    b2.flags |= 1;
    Xi2(a2, b2, c, e2);
    return b2.child;
  }
  function hj(a2, b2, c, d, e2) {
    if (Zf2(c)) {
      var f2 = true;
      cg(b2);
    } else f2 = false;
    ch(b2, e2);
    if (null === b2.stateNode) ij(a2, b2), Gi2(b2, c, d), Ii2(b2, c, d, e2), d = true;
    else if (null === a2) {
      var g2 = b2.stateNode, h2 = b2.memoizedProps;
      g2.props = h2;
      var k2 = g2.context, l2 = c.contextType;
      "object" === typeof l2 && null !== l2 ? l2 = eh(l2) : (l2 = Zf2(c) ? Xf2 : H2.current, l2 = Yf2(b2, l2));
      var m2 = c.getDerivedStateFromProps, q2 = "function" === typeof m2 || "function" === typeof g2.getSnapshotBeforeUpdate;
      q2 || "function" !== typeof g2.UNSAFE_componentWillReceiveProps && "function" !== typeof g2.componentWillReceiveProps || (h2 !== d || k2 !== l2) && Hi2(b2, g2, d, l2);
      jh = false;
      var r2 = b2.memoizedState;
      g2.state = r2;
      qh(b2, d, g2, e2);
      k2 = b2.memoizedState;
      h2 !== d || r2 !== k2 || Wf2.current || jh ? ("function" === typeof m2 && (Di2(b2, c, m2, d), k2 = b2.memoizedState), (h2 = jh || Fi2(b2, c, h2, d, r2, k2, l2)) ? (q2 || "function" !== typeof g2.UNSAFE_componentWillMount && "function" !== typeof g2.componentWillMount || ("function" === typeof g2.componentWillMount && g2.componentWillMount(), "function" === typeof g2.UNSAFE_componentWillMount && g2.UNSAFE_componentWillMount()), "function" === typeof g2.componentDidMount && (b2.flags |= 4194308)) : ("function" === typeof g2.componentDidMount && (b2.flags |= 4194308), b2.memoizedProps = d, b2.memoizedState = k2), g2.props = d, g2.state = k2, g2.context = l2, d = h2) : ("function" === typeof g2.componentDidMount && (b2.flags |= 4194308), d = false);
    } else {
      g2 = b2.stateNode;
      lh(a2, b2);
      h2 = b2.memoizedProps;
      l2 = b2.type === b2.elementType ? h2 : Ci2(b2.type, h2);
      g2.props = l2;
      q2 = b2.pendingProps;
      r2 = g2.context;
      k2 = c.contextType;
      "object" === typeof k2 && null !== k2 ? k2 = eh(k2) : (k2 = Zf2(c) ? Xf2 : H2.current, k2 = Yf2(b2, k2));
      var y = c.getDerivedStateFromProps;
      (m2 = "function" === typeof y || "function" === typeof g2.getSnapshotBeforeUpdate) || "function" !== typeof g2.UNSAFE_componentWillReceiveProps && "function" !== typeof g2.componentWillReceiveProps || (h2 !== q2 || r2 !== k2) && Hi2(b2, g2, d, k2);
      jh = false;
      r2 = b2.memoizedState;
      g2.state = r2;
      qh(b2, d, g2, e2);
      var n = b2.memoizedState;
      h2 !== q2 || r2 !== n || Wf2.current || jh ? ("function" === typeof y && (Di2(b2, c, y, d), n = b2.memoizedState), (l2 = jh || Fi2(b2, c, l2, d, r2, n, k2) || false) ? (m2 || "function" !== typeof g2.UNSAFE_componentWillUpdate && "function" !== typeof g2.componentWillUpdate || ("function" === typeof g2.componentWillUpdate && g2.componentWillUpdate(d, n, k2), "function" === typeof g2.UNSAFE_componentWillUpdate && g2.UNSAFE_componentWillUpdate(d, n, k2)), "function" === typeof g2.componentDidUpdate && (b2.flags |= 4), "function" === typeof g2.getSnapshotBeforeUpdate && (b2.flags |= 1024)) : ("function" !== typeof g2.componentDidUpdate || h2 === a2.memoizedProps && r2 === a2.memoizedState || (b2.flags |= 4), "function" !== typeof g2.getSnapshotBeforeUpdate || h2 === a2.memoizedProps && r2 === a2.memoizedState || (b2.flags |= 1024), b2.memoizedProps = d, b2.memoizedState = n), g2.props = d, g2.state = n, g2.context = k2, d = l2) : ("function" !== typeof g2.componentDidUpdate || h2 === a2.memoizedProps && r2 === a2.memoizedState || (b2.flags |= 4), "function" !== typeof g2.getSnapshotBeforeUpdate || h2 === a2.memoizedProps && r2 === a2.memoizedState || (b2.flags |= 1024), d = false);
    }
    return jj(a2, b2, c, d, f2, e2);
  }
  function jj(a2, b2, c, d, e2, f2) {
    gj(a2, b2);
    var g2 = 0 !== (b2.flags & 128);
    if (!d && !g2) return e2 && dg(b2, c, false), Zi(a2, b2, f2);
    d = b2.stateNode;
    Wi2.current = b2;
    var h2 = g2 && "function" !== typeof c.getDerivedStateFromError ? null : d.render();
    b2.flags |= 1;
    null !== a2 && g2 ? (b2.child = Ug(b2, a2.child, null, f2), b2.child = Ug(b2, null, h2, f2)) : Xi2(a2, b2, h2, f2);
    b2.memoizedState = d.state;
    e2 && dg(b2, c, true);
    return b2.child;
  }
  function kj(a2) {
    var b2 = a2.stateNode;
    b2.pendingContext ? ag(a2, b2.pendingContext, b2.pendingContext !== b2.context) : b2.context && ag(a2, b2.context, false);
    yh(a2, b2.containerInfo);
  }
  function lj(a2, b2, c, d, e2) {
    Ig();
    Jg(e2);
    b2.flags |= 256;
    Xi2(a2, b2, c, d);
    return b2.child;
  }
  var mj = { dehydrated: null, treeContext: null, retryLane: 0 };
  function nj(a2) {
    return { baseLanes: a2, cachePool: null, transitions: null };
  }
  function oj(a2, b2, c) {
    var d = b2.pendingProps, e2 = L2.current, f2 = false, g2 = 0 !== (b2.flags & 128), h2;
    (h2 = g2) || (h2 = null !== a2 && null === a2.memoizedState ? false : 0 !== (e2 & 2));
    if (h2) f2 = true, b2.flags &= -129;
    else if (null === a2 || null !== a2.memoizedState) e2 |= 1;
    G2(L2, e2 & 1);
    if (null === a2) {
      Eg(b2);
      a2 = b2.memoizedState;
      if (null !== a2 && (a2 = a2.dehydrated, null !== a2)) return 0 === (b2.mode & 1) ? b2.lanes = 1 : "$!" === a2.data ? b2.lanes = 8 : b2.lanes = 1073741824, null;
      g2 = d.children;
      a2 = d.fallback;
      return f2 ? (d = b2.mode, f2 = b2.child, g2 = { mode: "hidden", children: g2 }, 0 === (d & 1) && null !== f2 ? (f2.childLanes = 0, f2.pendingProps = g2) : f2 = pj(g2, d, 0, null), a2 = Tg(a2, d, c, null), f2.return = b2, a2.return = b2, f2.sibling = a2, b2.child = f2, b2.child.memoizedState = nj(c), b2.memoizedState = mj, a2) : qj(b2, g2);
    }
    e2 = a2.memoizedState;
    if (null !== e2 && (h2 = e2.dehydrated, null !== h2)) return rj(a2, b2, g2, d, h2, e2, c);
    if (f2) {
      f2 = d.fallback;
      g2 = b2.mode;
      e2 = a2.child;
      h2 = e2.sibling;
      var k2 = { mode: "hidden", children: d.children };
      0 === (g2 & 1) && b2.child !== e2 ? (d = b2.child, d.childLanes = 0, d.pendingProps = k2, b2.deletions = null) : (d = Pg(e2, k2), d.subtreeFlags = e2.subtreeFlags & 14680064);
      null !== h2 ? f2 = Pg(h2, f2) : (f2 = Tg(f2, g2, c, null), f2.flags |= 2);
      f2.return = b2;
      d.return = b2;
      d.sibling = f2;
      b2.child = d;
      d = f2;
      f2 = b2.child;
      g2 = a2.child.memoizedState;
      g2 = null === g2 ? nj(c) : { baseLanes: g2.baseLanes | c, cachePool: null, transitions: g2.transitions };
      f2.memoizedState = g2;
      f2.childLanes = a2.childLanes & ~c;
      b2.memoizedState = mj;
      return d;
    }
    f2 = a2.child;
    a2 = f2.sibling;
    d = Pg(f2, { mode: "visible", children: d.children });
    0 === (b2.mode & 1) && (d.lanes = c);
    d.return = b2;
    d.sibling = null;
    null !== a2 && (c = b2.deletions, null === c ? (b2.deletions = [a2], b2.flags |= 16) : c.push(a2));
    b2.child = d;
    b2.memoizedState = null;
    return d;
  }
  function qj(a2, b2) {
    b2 = pj({ mode: "visible", children: b2 }, a2.mode, 0, null);
    b2.return = a2;
    return a2.child = b2;
  }
  function sj(a2, b2, c, d) {
    null !== d && Jg(d);
    Ug(b2, a2.child, null, c);
    a2 = qj(b2, b2.pendingProps.children);
    a2.flags |= 2;
    b2.memoizedState = null;
    return a2;
  }
  function rj(a2, b2, c, d, e2, f2, g2) {
    if (c) {
      if (b2.flags & 256) return b2.flags &= -257, d = Ki2(Error(p2(422))), sj(a2, b2, g2, d);
      if (null !== b2.memoizedState) return b2.child = a2.child, b2.flags |= 128, null;
      f2 = d.fallback;
      e2 = b2.mode;
      d = pj({ mode: "visible", children: d.children }, e2, 0, null);
      f2 = Tg(f2, e2, g2, null);
      f2.flags |= 2;
      d.return = b2;
      f2.return = b2;
      d.sibling = f2;
      b2.child = d;
      0 !== (b2.mode & 1) && Ug(b2, a2.child, null, g2);
      b2.child.memoizedState = nj(g2);
      b2.memoizedState = mj;
      return f2;
    }
    if (0 === (b2.mode & 1)) return sj(a2, b2, g2, null);
    if ("$!" === e2.data) {
      d = e2.nextSibling && e2.nextSibling.dataset;
      if (d) var h2 = d.dgst;
      d = h2;
      f2 = Error(p2(419));
      d = Ki2(f2, d, void 0);
      return sj(a2, b2, g2, d);
    }
    h2 = 0 !== (g2 & a2.childLanes);
    if (dh || h2) {
      d = Q2;
      if (null !== d) {
        switch (g2 & -g2) {
          case 4:
            e2 = 2;
            break;
          case 16:
            e2 = 8;
            break;
          case 64:
          case 128:
          case 256:
          case 512:
          case 1024:
          case 2048:
          case 4096:
          case 8192:
          case 16384:
          case 32768:
          case 65536:
          case 131072:
          case 262144:
          case 524288:
          case 1048576:
          case 2097152:
          case 4194304:
          case 8388608:
          case 16777216:
          case 33554432:
          case 67108864:
            e2 = 32;
            break;
          case 536870912:
            e2 = 268435456;
            break;
          default:
            e2 = 0;
        }
        e2 = 0 !== (e2 & (d.suspendedLanes | g2)) ? 0 : e2;
        0 !== e2 && e2 !== f2.retryLane && (f2.retryLane = e2, ih(a2, e2), gi2(d, a2, e2, -1));
      }
      tj();
      d = Ki2(Error(p2(421)));
      return sj(a2, b2, g2, d);
    }
    if ("$?" === e2.data) return b2.flags |= 128, b2.child = a2.child, b2 = uj.bind(null, a2), e2._reactRetry = b2, null;
    a2 = f2.treeContext;
    yg = Lf2(e2.nextSibling);
    xg = b2;
    I2 = true;
    zg = null;
    null !== a2 && (og[pg++] = rg, og[pg++] = sg, og[pg++] = qg, rg = a2.id, sg = a2.overflow, qg = b2);
    b2 = qj(b2, d.children);
    b2.flags |= 4096;
    return b2;
  }
  function vj(a2, b2, c) {
    a2.lanes |= b2;
    var d = a2.alternate;
    null !== d && (d.lanes |= b2);
    bh(a2.return, b2, c);
  }
  function wj(a2, b2, c, d, e2) {
    var f2 = a2.memoizedState;
    null === f2 ? a2.memoizedState = { isBackwards: b2, rendering: null, renderingStartTime: 0, last: d, tail: c, tailMode: e2 } : (f2.isBackwards = b2, f2.rendering = null, f2.renderingStartTime = 0, f2.last = d, f2.tail = c, f2.tailMode = e2);
  }
  function xj(a2, b2, c) {
    var d = b2.pendingProps, e2 = d.revealOrder, f2 = d.tail;
    Xi2(a2, b2, d.children, c);
    d = L2.current;
    if (0 !== (d & 2)) d = d & 1 | 2, b2.flags |= 128;
    else {
      if (null !== a2 && 0 !== (a2.flags & 128)) a: for (a2 = b2.child; null !== a2; ) {
        if (13 === a2.tag) null !== a2.memoizedState && vj(a2, c, b2);
        else if (19 === a2.tag) vj(a2, c, b2);
        else if (null !== a2.child) {
          a2.child.return = a2;
          a2 = a2.child;
          continue;
        }
        if (a2 === b2) break a;
        for (; null === a2.sibling; ) {
          if (null === a2.return || a2.return === b2) break a;
          a2 = a2.return;
        }
        a2.sibling.return = a2.return;
        a2 = a2.sibling;
      }
      d &= 1;
    }
    G2(L2, d);
    if (0 === (b2.mode & 1)) b2.memoizedState = null;
    else switch (e2) {
      case "forwards":
        c = b2.child;
        for (e2 = null; null !== c; ) a2 = c.alternate, null !== a2 && null === Ch(a2) && (e2 = c), c = c.sibling;
        c = e2;
        null === c ? (e2 = b2.child, b2.child = null) : (e2 = c.sibling, c.sibling = null);
        wj(b2, false, e2, c, f2);
        break;
      case "backwards":
        c = null;
        e2 = b2.child;
        for (b2.child = null; null !== e2; ) {
          a2 = e2.alternate;
          if (null !== a2 && null === Ch(a2)) {
            b2.child = e2;
            break;
          }
          a2 = e2.sibling;
          e2.sibling = c;
          c = e2;
          e2 = a2;
        }
        wj(b2, true, c, null, f2);
        break;
      case "together":
        wj(b2, false, null, null, void 0);
        break;
      default:
        b2.memoizedState = null;
    }
    return b2.child;
  }
  function ij(a2, b2) {
    0 === (b2.mode & 1) && null !== a2 && (a2.alternate = null, b2.alternate = null, b2.flags |= 2);
  }
  function Zi(a2, b2, c) {
    null !== a2 && (b2.dependencies = a2.dependencies);
    rh |= b2.lanes;
    if (0 === (c & b2.childLanes)) return null;
    if (null !== a2 && b2.child !== a2.child) throw Error(p2(153));
    if (null !== b2.child) {
      a2 = b2.child;
      c = Pg(a2, a2.pendingProps);
      b2.child = c;
      for (c.return = b2; null !== a2.sibling; ) a2 = a2.sibling, c = c.sibling = Pg(a2, a2.pendingProps), c.return = b2;
      c.sibling = null;
    }
    return b2.child;
  }
  function yj(a2, b2, c) {
    switch (b2.tag) {
      case 3:
        kj(b2);
        Ig();
        break;
      case 5:
        Ah(b2);
        break;
      case 1:
        Zf2(b2.type) && cg(b2);
        break;
      case 4:
        yh(b2, b2.stateNode.containerInfo);
        break;
      case 10:
        var d = b2.type._context, e2 = b2.memoizedProps.value;
        G2(Wg, d._currentValue);
        d._currentValue = e2;
        break;
      case 13:
        d = b2.memoizedState;
        if (null !== d) {
          if (null !== d.dehydrated) return G2(L2, L2.current & 1), b2.flags |= 128, null;
          if (0 !== (c & b2.child.childLanes)) return oj(a2, b2, c);
          G2(L2, L2.current & 1);
          a2 = Zi(a2, b2, c);
          return null !== a2 ? a2.sibling : null;
        }
        G2(L2, L2.current & 1);
        break;
      case 19:
        d = 0 !== (c & b2.childLanes);
        if (0 !== (a2.flags & 128)) {
          if (d) return xj(a2, b2, c);
          b2.flags |= 128;
        }
        e2 = b2.memoizedState;
        null !== e2 && (e2.rendering = null, e2.tail = null, e2.lastEffect = null);
        G2(L2, L2.current);
        if (d) break;
        else return null;
      case 22:
      case 23:
        return b2.lanes = 0, dj(a2, b2, c);
    }
    return Zi(a2, b2, c);
  }
  var zj, Aj, Bj, Cj;
  zj = function(a2, b2) {
    for (var c = b2.child; null !== c; ) {
      if (5 === c.tag || 6 === c.tag) a2.appendChild(c.stateNode);
      else if (4 !== c.tag && null !== c.child) {
        c.child.return = c;
        c = c.child;
        continue;
      }
      if (c === b2) break;
      for (; null === c.sibling; ) {
        if (null === c.return || c.return === b2) return;
        c = c.return;
      }
      c.sibling.return = c.return;
      c = c.sibling;
    }
  };
  Aj = function() {
  };
  Bj = function(a2, b2, c, d) {
    var e2 = a2.memoizedProps;
    if (e2 !== d) {
      a2 = b2.stateNode;
      xh(uh.current);
      var f2 = null;
      switch (c) {
        case "input":
          e2 = Ya2(a2, e2);
          d = Ya2(a2, d);
          f2 = [];
          break;
        case "select":
          e2 = A({}, e2, { value: void 0 });
          d = A({}, d, { value: void 0 });
          f2 = [];
          break;
        case "textarea":
          e2 = gb(a2, e2);
          d = gb(a2, d);
          f2 = [];
          break;
        default:
          "function" !== typeof e2.onClick && "function" === typeof d.onClick && (a2.onclick = Bf2);
      }
      ub(c, d);
      var g2;
      c = null;
      for (l2 in e2) if (!d.hasOwnProperty(l2) && e2.hasOwnProperty(l2) && null != e2[l2]) if ("style" === l2) {
        var h2 = e2[l2];
        for (g2 in h2) h2.hasOwnProperty(g2) && (c || (c = {}), c[g2] = "");
      } else "dangerouslySetInnerHTML" !== l2 && "children" !== l2 && "suppressContentEditableWarning" !== l2 && "suppressHydrationWarning" !== l2 && "autoFocus" !== l2 && (ea2.hasOwnProperty(l2) ? f2 || (f2 = []) : (f2 = f2 || []).push(l2, null));
      for (l2 in d) {
        var k2 = d[l2];
        h2 = null != e2 ? e2[l2] : void 0;
        if (d.hasOwnProperty(l2) && k2 !== h2 && (null != k2 || null != h2)) if ("style" === l2) if (h2) {
          for (g2 in h2) !h2.hasOwnProperty(g2) || k2 && k2.hasOwnProperty(g2) || (c || (c = {}), c[g2] = "");
          for (g2 in k2) k2.hasOwnProperty(g2) && h2[g2] !== k2[g2] && (c || (c = {}), c[g2] = k2[g2]);
        } else c || (f2 || (f2 = []), f2.push(
          l2,
          c
        )), c = k2;
        else "dangerouslySetInnerHTML" === l2 ? (k2 = k2 ? k2.__html : void 0, h2 = h2 ? h2.__html : void 0, null != k2 && h2 !== k2 && (f2 = f2 || []).push(l2, k2)) : "children" === l2 ? "string" !== typeof k2 && "number" !== typeof k2 || (f2 = f2 || []).push(l2, "" + k2) : "suppressContentEditableWarning" !== l2 && "suppressHydrationWarning" !== l2 && (ea2.hasOwnProperty(l2) ? (null != k2 && "onScroll" === l2 && D2("scroll", a2), f2 || h2 === k2 || (f2 = [])) : (f2 = f2 || []).push(l2, k2));
      }
      c && (f2 = f2 || []).push("style", c);
      var l2 = f2;
      if (b2.updateQueue = l2) b2.flags |= 4;
    }
  };
  Cj = function(a2, b2, c, d) {
    c !== d && (b2.flags |= 4);
  };
  function Dj(a2, b2) {
    if (!I2) switch (a2.tailMode) {
      case "hidden":
        b2 = a2.tail;
        for (var c = null; null !== b2; ) null !== b2.alternate && (c = b2), b2 = b2.sibling;
        null === c ? a2.tail = null : c.sibling = null;
        break;
      case "collapsed":
        c = a2.tail;
        for (var d = null; null !== c; ) null !== c.alternate && (d = c), c = c.sibling;
        null === d ? b2 || null === a2.tail ? a2.tail = null : a2.tail.sibling = null : d.sibling = null;
    }
  }
  function S2(a2) {
    var b2 = null !== a2.alternate && a2.alternate.child === a2.child, c = 0, d = 0;
    if (b2) for (var e2 = a2.child; null !== e2; ) c |= e2.lanes | e2.childLanes, d |= e2.subtreeFlags & 14680064, d |= e2.flags & 14680064, e2.return = a2, e2 = e2.sibling;
    else for (e2 = a2.child; null !== e2; ) c |= e2.lanes | e2.childLanes, d |= e2.subtreeFlags, d |= e2.flags, e2.return = a2, e2 = e2.sibling;
    a2.subtreeFlags |= d;
    a2.childLanes = c;
    return b2;
  }
  function Ej(a2, b2, c) {
    var d = b2.pendingProps;
    wg(b2);
    switch (b2.tag) {
      case 2:
      case 16:
      case 15:
      case 0:
      case 11:
      case 7:
      case 8:
      case 12:
      case 9:
      case 14:
        return S2(b2), null;
      case 1:
        return Zf2(b2.type) && $f2(), S2(b2), null;
      case 3:
        d = b2.stateNode;
        zh();
        E2(Wf2);
        E2(H2);
        Eh();
        d.pendingContext && (d.context = d.pendingContext, d.pendingContext = null);
        if (null === a2 || null === a2.child) Gg(b2) ? b2.flags |= 4 : null === a2 || a2.memoizedState.isDehydrated && 0 === (b2.flags & 256) || (b2.flags |= 1024, null !== zg && (Fj(zg), zg = null));
        Aj(a2, b2);
        S2(b2);
        return null;
      case 5:
        Bh(b2);
        var e2 = xh(wh.current);
        c = b2.type;
        if (null !== a2 && null != b2.stateNode) Bj(a2, b2, c, d, e2), a2.ref !== b2.ref && (b2.flags |= 512, b2.flags |= 2097152);
        else {
          if (!d) {
            if (null === b2.stateNode) throw Error(p2(166));
            S2(b2);
            return null;
          }
          a2 = xh(uh.current);
          if (Gg(b2)) {
            d = b2.stateNode;
            c = b2.type;
            var f2 = b2.memoizedProps;
            d[Of2] = b2;
            d[Pf2] = f2;
            a2 = 0 !== (b2.mode & 1);
            switch (c) {
              case "dialog":
                D2("cancel", d);
                D2("close", d);
                break;
              case "iframe":
              case "object":
              case "embed":
                D2("load", d);
                break;
              case "video":
              case "audio":
                for (e2 = 0; e2 < lf2.length; e2++) D2(lf2[e2], d);
                break;
              case "source":
                D2("error", d);
                break;
              case "img":
              case "image":
              case "link":
                D2(
                  "error",
                  d
                );
                D2("load", d);
                break;
              case "details":
                D2("toggle", d);
                break;
              case "input":
                Za2(d, f2);
                D2("invalid", d);
                break;
              case "select":
                d._wrapperState = { wasMultiple: !!f2.multiple };
                D2("invalid", d);
                break;
              case "textarea":
                hb(d, f2), D2("invalid", d);
            }
            ub(c, f2);
            e2 = null;
            for (var g2 in f2) if (f2.hasOwnProperty(g2)) {
              var h2 = f2[g2];
              "children" === g2 ? "string" === typeof h2 ? d.textContent !== h2 && (true !== f2.suppressHydrationWarning && Af2(d.textContent, h2, a2), e2 = ["children", h2]) : "number" === typeof h2 && d.textContent !== "" + h2 && (true !== f2.suppressHydrationWarning && Af2(
                d.textContent,
                h2,
                a2
              ), e2 = ["children", "" + h2]) : ea2.hasOwnProperty(g2) && null != h2 && "onScroll" === g2 && D2("scroll", d);
            }
            switch (c) {
              case "input":
                Va2(d);
                db(d, f2, true);
                break;
              case "textarea":
                Va2(d);
                jb(d);
                break;
              case "select":
              case "option":
                break;
              default:
                "function" === typeof f2.onClick && (d.onclick = Bf2);
            }
            d = e2;
            b2.updateQueue = d;
            null !== d && (b2.flags |= 4);
          } else {
            g2 = 9 === e2.nodeType ? e2 : e2.ownerDocument;
            "http://www.w3.org/1999/xhtml" === a2 && (a2 = kb(c));
            "http://www.w3.org/1999/xhtml" === a2 ? "script" === c ? (a2 = g2.createElement("div"), a2.innerHTML = "<script><\/script>", a2 = a2.removeChild(a2.firstChild)) : "string" === typeof d.is ? a2 = g2.createElement(c, { is: d.is }) : (a2 = g2.createElement(c), "select" === c && (g2 = a2, d.multiple ? g2.multiple = true : d.size && (g2.size = d.size))) : a2 = g2.createElementNS(a2, c);
            a2[Of2] = b2;
            a2[Pf2] = d;
            zj(a2, b2, false, false);
            b2.stateNode = a2;
            a: {
              g2 = vb(c, d);
              switch (c) {
                case "dialog":
                  D2("cancel", a2);
                  D2("close", a2);
                  e2 = d;
                  break;
                case "iframe":
                case "object":
                case "embed":
                  D2("load", a2);
                  e2 = d;
                  break;
                case "video":
                case "audio":
                  for (e2 = 0; e2 < lf2.length; e2++) D2(lf2[e2], a2);
                  e2 = d;
                  break;
                case "source":
                  D2("error", a2);
                  e2 = d;
                  break;
                case "img":
                case "image":
                case "link":
                  D2(
                    "error",
                    a2
                  );
                  D2("load", a2);
                  e2 = d;
                  break;
                case "details":
                  D2("toggle", a2);
                  e2 = d;
                  break;
                case "input":
                  Za2(a2, d);
                  e2 = Ya2(a2, d);
                  D2("invalid", a2);
                  break;
                case "option":
                  e2 = d;
                  break;
                case "select":
                  a2._wrapperState = { wasMultiple: !!d.multiple };
                  e2 = A({}, d, { value: void 0 });
                  D2("invalid", a2);
                  break;
                case "textarea":
                  hb(a2, d);
                  e2 = gb(a2, d);
                  D2("invalid", a2);
                  break;
                default:
                  e2 = d;
              }
              ub(c, e2);
              h2 = e2;
              for (f2 in h2) if (h2.hasOwnProperty(f2)) {
                var k2 = h2[f2];
                "style" === f2 ? sb(a2, k2) : "dangerouslySetInnerHTML" === f2 ? (k2 = k2 ? k2.__html : void 0, null != k2 && nb(a2, k2)) : "children" === f2 ? "string" === typeof k2 ? ("textarea" !== c || "" !== k2) && ob(a2, k2) : "number" === typeof k2 && ob(a2, "" + k2) : "suppressContentEditableWarning" !== f2 && "suppressHydrationWarning" !== f2 && "autoFocus" !== f2 && (ea2.hasOwnProperty(f2) ? null != k2 && "onScroll" === f2 && D2("scroll", a2) : null != k2 && ta2(a2, f2, k2, g2));
              }
              switch (c) {
                case "input":
                  Va2(a2);
                  db(a2, d, false);
                  break;
                case "textarea":
                  Va2(a2);
                  jb(a2);
                  break;
                case "option":
                  null != d.value && a2.setAttribute("value", "" + Sa2(d.value));
                  break;
                case "select":
                  a2.multiple = !!d.multiple;
                  f2 = d.value;
                  null != f2 ? fb(a2, !!d.multiple, f2, false) : null != d.defaultValue && fb(
                    a2,
                    !!d.multiple,
                    d.defaultValue,
                    true
                  );
                  break;
                default:
                  "function" === typeof e2.onClick && (a2.onclick = Bf2);
              }
              switch (c) {
                case "button":
                case "input":
                case "select":
                case "textarea":
                  d = !!d.autoFocus;
                  break a;
                case "img":
                  d = true;
                  break a;
                default:
                  d = false;
              }
            }
            d && (b2.flags |= 4);
          }
          null !== b2.ref && (b2.flags |= 512, b2.flags |= 2097152);
        }
        S2(b2);
        return null;
      case 6:
        if (a2 && null != b2.stateNode) Cj(a2, b2, a2.memoizedProps, d);
        else {
          if ("string" !== typeof d && null === b2.stateNode) throw Error(p2(166));
          c = xh(wh.current);
          xh(uh.current);
          if (Gg(b2)) {
            d = b2.stateNode;
            c = b2.memoizedProps;
            d[Of2] = b2;
            if (f2 = d.nodeValue !== c) {
              if (a2 = xg, null !== a2) switch (a2.tag) {
                case 3:
                  Af2(d.nodeValue, c, 0 !== (a2.mode & 1));
                  break;
                case 5:
                  true !== a2.memoizedProps.suppressHydrationWarning && Af2(d.nodeValue, c, 0 !== (a2.mode & 1));
              }
            }
            f2 && (b2.flags |= 4);
          } else d = (9 === c.nodeType ? c : c.ownerDocument).createTextNode(d), d[Of2] = b2, b2.stateNode = d;
        }
        S2(b2);
        return null;
      case 13:
        E2(L2);
        d = b2.memoizedState;
        if (null === a2 || null !== a2.memoizedState && null !== a2.memoizedState.dehydrated) {
          if (I2 && null !== yg && 0 !== (b2.mode & 1) && 0 === (b2.flags & 128)) Hg(), Ig(), b2.flags |= 98560, f2 = false;
          else if (f2 = Gg(b2), null !== d && null !== d.dehydrated) {
            if (null === a2) {
              if (!f2) throw Error(p2(318));
              f2 = b2.memoizedState;
              f2 = null !== f2 ? f2.dehydrated : null;
              if (!f2) throw Error(p2(317));
              f2[Of2] = b2;
            } else Ig(), 0 === (b2.flags & 128) && (b2.memoizedState = null), b2.flags |= 4;
            S2(b2);
            f2 = false;
          } else null !== zg && (Fj(zg), zg = null), f2 = true;
          if (!f2) return b2.flags & 65536 ? b2 : null;
        }
        if (0 !== (b2.flags & 128)) return b2.lanes = c, b2;
        d = null !== d;
        d !== (null !== a2 && null !== a2.memoizedState) && d && (b2.child.flags |= 8192, 0 !== (b2.mode & 1) && (null === a2 || 0 !== (L2.current & 1) ? 0 === T2 && (T2 = 3) : tj()));
        null !== b2.updateQueue && (b2.flags |= 4);
        S2(b2);
        return null;
      case 4:
        return zh(), Aj(a2, b2), null === a2 && sf2(b2.stateNode.containerInfo), S2(b2), null;
      case 10:
        return ah(b2.type._context), S2(b2), null;
      case 17:
        return Zf2(b2.type) && $f2(), S2(b2), null;
      case 19:
        E2(L2);
        f2 = b2.memoizedState;
        if (null === f2) return S2(b2), null;
        d = 0 !== (b2.flags & 128);
        g2 = f2.rendering;
        if (null === g2) if (d) Dj(f2, false);
        else {
          if (0 !== T2 || null !== a2 && 0 !== (a2.flags & 128)) for (a2 = b2.child; null !== a2; ) {
            g2 = Ch(a2);
            if (null !== g2) {
              b2.flags |= 128;
              Dj(f2, false);
              d = g2.updateQueue;
              null !== d && (b2.updateQueue = d, b2.flags |= 4);
              b2.subtreeFlags = 0;
              d = c;
              for (c = b2.child; null !== c; ) f2 = c, a2 = d, f2.flags &= 14680066, g2 = f2.alternate, null === g2 ? (f2.childLanes = 0, f2.lanes = a2, f2.child = null, f2.subtreeFlags = 0, f2.memoizedProps = null, f2.memoizedState = null, f2.updateQueue = null, f2.dependencies = null, f2.stateNode = null) : (f2.childLanes = g2.childLanes, f2.lanes = g2.lanes, f2.child = g2.child, f2.subtreeFlags = 0, f2.deletions = null, f2.memoizedProps = g2.memoizedProps, f2.memoizedState = g2.memoizedState, f2.updateQueue = g2.updateQueue, f2.type = g2.type, a2 = g2.dependencies, f2.dependencies = null === a2 ? null : { lanes: a2.lanes, firstContext: a2.firstContext }), c = c.sibling;
              G2(L2, L2.current & 1 | 2);
              return b2.child;
            }
            a2 = a2.sibling;
          }
          null !== f2.tail && B2() > Gj && (b2.flags |= 128, d = true, Dj(f2, false), b2.lanes = 4194304);
        }
        else {
          if (!d) if (a2 = Ch(g2), null !== a2) {
            if (b2.flags |= 128, d = true, c = a2.updateQueue, null !== c && (b2.updateQueue = c, b2.flags |= 4), Dj(f2, true), null === f2.tail && "hidden" === f2.tailMode && !g2.alternate && !I2) return S2(b2), null;
          } else 2 * B2() - f2.renderingStartTime > Gj && 1073741824 !== c && (b2.flags |= 128, d = true, Dj(f2, false), b2.lanes = 4194304);
          f2.isBackwards ? (g2.sibling = b2.child, b2.child = g2) : (c = f2.last, null !== c ? c.sibling = g2 : b2.child = g2, f2.last = g2);
        }
        if (null !== f2.tail) return b2 = f2.tail, f2.rendering = b2, f2.tail = b2.sibling, f2.renderingStartTime = B2(), b2.sibling = null, c = L2.current, G2(L2, d ? c & 1 | 2 : c & 1), b2;
        S2(b2);
        return null;
      case 22:
      case 23:
        return Hj(), d = null !== b2.memoizedState, null !== a2 && null !== a2.memoizedState !== d && (b2.flags |= 8192), d && 0 !== (b2.mode & 1) ? 0 !== (fj & 1073741824) && (S2(b2), b2.subtreeFlags & 6 && (b2.flags |= 8192)) : S2(b2), null;
      case 24:
        return null;
      case 25:
        return null;
    }
    throw Error(p2(156, b2.tag));
  }
  function Ij(a2, b2) {
    wg(b2);
    switch (b2.tag) {
      case 1:
        return Zf2(b2.type) && $f2(), a2 = b2.flags, a2 & 65536 ? (b2.flags = a2 & -65537 | 128, b2) : null;
      case 3:
        return zh(), E2(Wf2), E2(H2), Eh(), a2 = b2.flags, 0 !== (a2 & 65536) && 0 === (a2 & 128) ? (b2.flags = a2 & -65537 | 128, b2) : null;
      case 5:
        return Bh(b2), null;
      case 13:
        E2(L2);
        a2 = b2.memoizedState;
        if (null !== a2 && null !== a2.dehydrated) {
          if (null === b2.alternate) throw Error(p2(340));
          Ig();
        }
        a2 = b2.flags;
        return a2 & 65536 ? (b2.flags = a2 & -65537 | 128, b2) : null;
      case 19:
        return E2(L2), null;
      case 4:
        return zh(), null;
      case 10:
        return ah(b2.type._context), null;
      case 22:
      case 23:
        return Hj(), null;
      case 24:
        return null;
      default:
        return null;
    }
  }
  var Jj = false, U2 = false, Kj = "function" === typeof WeakSet ? WeakSet : Set, V2 = null;
  function Lj(a2, b2) {
    var c = a2.ref;
    if (null !== c) if ("function" === typeof c) try {
      c(null);
    } catch (d) {
      W2(a2, b2, d);
    }
    else c.current = null;
  }
  function Mj(a2, b2, c) {
    try {
      c();
    } catch (d) {
      W2(a2, b2, d);
    }
  }
  var Nj = false;
  function Oj(a2, b2) {
    Cf2 = dd2;
    a2 = Me2();
    if (Ne2(a2)) {
      if ("selectionStart" in a2) var c = { start: a2.selectionStart, end: a2.selectionEnd };
      else a: {
        c = (c = a2.ownerDocument) && c.defaultView || window;
        var d = c.getSelection && c.getSelection();
        if (d && 0 !== d.rangeCount) {
          c = d.anchorNode;
          var e2 = d.anchorOffset, f2 = d.focusNode;
          d = d.focusOffset;
          try {
            c.nodeType, f2.nodeType;
          } catch (F2) {
            c = null;
            break a;
          }
          var g2 = 0, h2 = -1, k2 = -1, l2 = 0, m2 = 0, q2 = a2, r2 = null;
          b: for (; ; ) {
            for (var y; ; ) {
              q2 !== c || 0 !== e2 && 3 !== q2.nodeType || (h2 = g2 + e2);
              q2 !== f2 || 0 !== d && 3 !== q2.nodeType || (k2 = g2 + d);
              3 === q2.nodeType && (g2 += q2.nodeValue.length);
              if (null === (y = q2.firstChild)) break;
              r2 = q2;
              q2 = y;
            }
            for (; ; ) {
              if (q2 === a2) break b;
              r2 === c && ++l2 === e2 && (h2 = g2);
              r2 === f2 && ++m2 === d && (k2 = g2);
              if (null !== (y = q2.nextSibling)) break;
              q2 = r2;
              r2 = q2.parentNode;
            }
            q2 = y;
          }
          c = -1 === h2 || -1 === k2 ? null : { start: h2, end: k2 };
        } else c = null;
      }
      c = c || { start: 0, end: 0 };
    } else c = null;
    Df2 = { focusedElem: a2, selectionRange: c };
    dd2 = false;
    for (V2 = b2; null !== V2; ) if (b2 = V2, a2 = b2.child, 0 !== (b2.subtreeFlags & 1028) && null !== a2) a2.return = b2, V2 = a2;
    else for (; null !== V2; ) {
      b2 = V2;
      try {
        var n = b2.alternate;
        if (0 !== (b2.flags & 1024)) switch (b2.tag) {
          case 0:
          case 11:
          case 15:
            break;
          case 1:
            if (null !== n) {
              var t2 = n.memoizedProps, J2 = n.memoizedState, x2 = b2.stateNode, w2 = x2.getSnapshotBeforeUpdate(b2.elementType === b2.type ? t2 : Ci2(b2.type, t2), J2);
              x2.__reactInternalSnapshotBeforeUpdate = w2;
            }
            break;
          case 3:
            var u2 = b2.stateNode.containerInfo;
            1 === u2.nodeType ? u2.textContent = "" : 9 === u2.nodeType && u2.documentElement && u2.removeChild(u2.documentElement);
            break;
          case 5:
          case 6:
          case 4:
          case 17:
            break;
          default:
            throw Error(p2(163));
        }
      } catch (F2) {
        W2(b2, b2.return, F2);
      }
      a2 = b2.sibling;
      if (null !== a2) {
        a2.return = b2.return;
        V2 = a2;
        break;
      }
      V2 = b2.return;
    }
    n = Nj;
    Nj = false;
    return n;
  }
  function Pj(a2, b2, c) {
    var d = b2.updateQueue;
    d = null !== d ? d.lastEffect : null;
    if (null !== d) {
      var e2 = d = d.next;
      do {
        if ((e2.tag & a2) === a2) {
          var f2 = e2.destroy;
          e2.destroy = void 0;
          void 0 !== f2 && Mj(b2, c, f2);
        }
        e2 = e2.next;
      } while (e2 !== d);
    }
  }
  function Qj(a2, b2) {
    b2 = b2.updateQueue;
    b2 = null !== b2 ? b2.lastEffect : null;
    if (null !== b2) {
      var c = b2 = b2.next;
      do {
        if ((c.tag & a2) === a2) {
          var d = c.create;
          c.destroy = d();
        }
        c = c.next;
      } while (c !== b2);
    }
  }
  function Rj(a2) {
    var b2 = a2.ref;
    if (null !== b2) {
      var c = a2.stateNode;
      switch (a2.tag) {
        case 5:
          a2 = c;
          break;
        default:
          a2 = c;
      }
      "function" === typeof b2 ? b2(a2) : b2.current = a2;
    }
  }
  function Sj(a2) {
    var b2 = a2.alternate;
    null !== b2 && (a2.alternate = null, Sj(b2));
    a2.child = null;
    a2.deletions = null;
    a2.sibling = null;
    5 === a2.tag && (b2 = a2.stateNode, null !== b2 && (delete b2[Of2], delete b2[Pf2], delete b2[of2], delete b2[Qf2], delete b2[Rf2]));
    a2.stateNode = null;
    a2.return = null;
    a2.dependencies = null;
    a2.memoizedProps = null;
    a2.memoizedState = null;
    a2.pendingProps = null;
    a2.stateNode = null;
    a2.updateQueue = null;
  }
  function Tj(a2) {
    return 5 === a2.tag || 3 === a2.tag || 4 === a2.tag;
  }
  function Uj(a2) {
    a: for (; ; ) {
      for (; null === a2.sibling; ) {
        if (null === a2.return || Tj(a2.return)) return null;
        a2 = a2.return;
      }
      a2.sibling.return = a2.return;
      for (a2 = a2.sibling; 5 !== a2.tag && 6 !== a2.tag && 18 !== a2.tag; ) {
        if (a2.flags & 2) continue a;
        if (null === a2.child || 4 === a2.tag) continue a;
        else a2.child.return = a2, a2 = a2.child;
      }
      if (!(a2.flags & 2)) return a2.stateNode;
    }
  }
  function Vj(a2, b2, c) {
    var d = a2.tag;
    if (5 === d || 6 === d) a2 = a2.stateNode, b2 ? 8 === c.nodeType ? c.parentNode.insertBefore(a2, b2) : c.insertBefore(a2, b2) : (8 === c.nodeType ? (b2 = c.parentNode, b2.insertBefore(a2, c)) : (b2 = c, b2.appendChild(a2)), c = c._reactRootContainer, null !== c && void 0 !== c || null !== b2.onclick || (b2.onclick = Bf2));
    else if (4 !== d && (a2 = a2.child, null !== a2)) for (Vj(a2, b2, c), a2 = a2.sibling; null !== a2; ) Vj(a2, b2, c), a2 = a2.sibling;
  }
  function Wj(a2, b2, c) {
    var d = a2.tag;
    if (5 === d || 6 === d) a2 = a2.stateNode, b2 ? c.insertBefore(a2, b2) : c.appendChild(a2);
    else if (4 !== d && (a2 = a2.child, null !== a2)) for (Wj(a2, b2, c), a2 = a2.sibling; null !== a2; ) Wj(a2, b2, c), a2 = a2.sibling;
  }
  var X2 = null, Xj = false;
  function Yj(a2, b2, c) {
    for (c = c.child; null !== c; ) Zj(a2, b2, c), c = c.sibling;
  }
  function Zj(a2, b2, c) {
    if (lc && "function" === typeof lc.onCommitFiberUnmount) try {
      lc.onCommitFiberUnmount(kc, c);
    } catch (h2) {
    }
    switch (c.tag) {
      case 5:
        U2 || Lj(c, b2);
      case 6:
        var d = X2, e2 = Xj;
        X2 = null;
        Yj(a2, b2, c);
        X2 = d;
        Xj = e2;
        null !== X2 && (Xj ? (a2 = X2, c = c.stateNode, 8 === a2.nodeType ? a2.parentNode.removeChild(c) : a2.removeChild(c)) : X2.removeChild(c.stateNode));
        break;
      case 18:
        null !== X2 && (Xj ? (a2 = X2, c = c.stateNode, 8 === a2.nodeType ? Kf2(a2.parentNode, c) : 1 === a2.nodeType && Kf2(a2, c), bd2(a2)) : Kf2(X2, c.stateNode));
        break;
      case 4:
        d = X2;
        e2 = Xj;
        X2 = c.stateNode.containerInfo;
        Xj = true;
        Yj(a2, b2, c);
        X2 = d;
        Xj = e2;
        break;
      case 0:
      case 11:
      case 14:
      case 15:
        if (!U2 && (d = c.updateQueue, null !== d && (d = d.lastEffect, null !== d))) {
          e2 = d = d.next;
          do {
            var f2 = e2, g2 = f2.destroy;
            f2 = f2.tag;
            void 0 !== g2 && (0 !== (f2 & 2) ? Mj(c, b2, g2) : 0 !== (f2 & 4) && Mj(c, b2, g2));
            e2 = e2.next;
          } while (e2 !== d);
        }
        Yj(a2, b2, c);
        break;
      case 1:
        if (!U2 && (Lj(c, b2), d = c.stateNode, "function" === typeof d.componentWillUnmount)) try {
          d.props = c.memoizedProps, d.state = c.memoizedState, d.componentWillUnmount();
        } catch (h2) {
          W2(c, b2, h2);
        }
        Yj(a2, b2, c);
        break;
      case 21:
        Yj(a2, b2, c);
        break;
      case 22:
        c.mode & 1 ? (U2 = (d = U2) || null !== c.memoizedState, Yj(a2, b2, c), U2 = d) : Yj(a2, b2, c);
        break;
      default:
        Yj(a2, b2, c);
    }
  }
  function ak(a2) {
    var b2 = a2.updateQueue;
    if (null !== b2) {
      a2.updateQueue = null;
      var c = a2.stateNode;
      null === c && (c = a2.stateNode = new Kj());
      b2.forEach(function(b3) {
        var d = bk.bind(null, a2, b3);
        c.has(b3) || (c.add(b3), b3.then(d, d));
      });
    }
  }
  function ck(a2, b2) {
    var c = b2.deletions;
    if (null !== c) for (var d = 0; d < c.length; d++) {
      var e2 = c[d];
      try {
        var f2 = a2, g2 = b2, h2 = g2;
        a: for (; null !== h2; ) {
          switch (h2.tag) {
            case 5:
              X2 = h2.stateNode;
              Xj = false;
              break a;
            case 3:
              X2 = h2.stateNode.containerInfo;
              Xj = true;
              break a;
            case 4:
              X2 = h2.stateNode.containerInfo;
              Xj = true;
              break a;
          }
          h2 = h2.return;
        }
        if (null === X2) throw Error(p2(160));
        Zj(f2, g2, e2);
        X2 = null;
        Xj = false;
        var k2 = e2.alternate;
        null !== k2 && (k2.return = null);
        e2.return = null;
      } catch (l2) {
        W2(e2, b2, l2);
      }
    }
    if (b2.subtreeFlags & 12854) for (b2 = b2.child; null !== b2; ) dk(b2, a2), b2 = b2.sibling;
  }
  function dk(a2, b2) {
    var c = a2.alternate, d = a2.flags;
    switch (a2.tag) {
      case 0:
      case 11:
      case 14:
      case 15:
        ck(b2, a2);
        ek(a2);
        if (d & 4) {
          try {
            Pj(3, a2, a2.return), Qj(3, a2);
          } catch (t2) {
            W2(a2, a2.return, t2);
          }
          try {
            Pj(5, a2, a2.return);
          } catch (t2) {
            W2(a2, a2.return, t2);
          }
        }
        break;
      case 1:
        ck(b2, a2);
        ek(a2);
        d & 512 && null !== c && Lj(c, c.return);
        break;
      case 5:
        ck(b2, a2);
        ek(a2);
        d & 512 && null !== c && Lj(c, c.return);
        if (a2.flags & 32) {
          var e2 = a2.stateNode;
          try {
            ob(e2, "");
          } catch (t2) {
            W2(a2, a2.return, t2);
          }
        }
        if (d & 4 && (e2 = a2.stateNode, null != e2)) {
          var f2 = a2.memoizedProps, g2 = null !== c ? c.memoizedProps : f2, h2 = a2.type, k2 = a2.updateQueue;
          a2.updateQueue = null;
          if (null !== k2) try {
            "input" === h2 && "radio" === f2.type && null != f2.name && ab(e2, f2);
            vb(h2, g2);
            var l2 = vb(h2, f2);
            for (g2 = 0; g2 < k2.length; g2 += 2) {
              var m2 = k2[g2], q2 = k2[g2 + 1];
              "style" === m2 ? sb(e2, q2) : "dangerouslySetInnerHTML" === m2 ? nb(e2, q2) : "children" === m2 ? ob(e2, q2) : ta2(e2, m2, q2, l2);
            }
            switch (h2) {
              case "input":
                bb(e2, f2);
                break;
              case "textarea":
                ib(e2, f2);
                break;
              case "select":
                var r2 = e2._wrapperState.wasMultiple;
                e2._wrapperState.wasMultiple = !!f2.multiple;
                var y = f2.value;
                null != y ? fb(e2, !!f2.multiple, y, false) : r2 !== !!f2.multiple && (null != f2.defaultValue ? fb(
                  e2,
                  !!f2.multiple,
                  f2.defaultValue,
                  true
                ) : fb(e2, !!f2.multiple, f2.multiple ? [] : "", false));
            }
            e2[Pf2] = f2;
          } catch (t2) {
            W2(a2, a2.return, t2);
          }
        }
        break;
      case 6:
        ck(b2, a2);
        ek(a2);
        if (d & 4) {
          if (null === a2.stateNode) throw Error(p2(162));
          e2 = a2.stateNode;
          f2 = a2.memoizedProps;
          try {
            e2.nodeValue = f2;
          } catch (t2) {
            W2(a2, a2.return, t2);
          }
        }
        break;
      case 3:
        ck(b2, a2);
        ek(a2);
        if (d & 4 && null !== c && c.memoizedState.isDehydrated) try {
          bd2(b2.containerInfo);
        } catch (t2) {
          W2(a2, a2.return, t2);
        }
        break;
      case 4:
        ck(b2, a2);
        ek(a2);
        break;
      case 13:
        ck(b2, a2);
        ek(a2);
        e2 = a2.child;
        e2.flags & 8192 && (f2 = null !== e2.memoizedState, e2.stateNode.isHidden = f2, !f2 || null !== e2.alternate && null !== e2.alternate.memoizedState || (fk = B2()));
        d & 4 && ak(a2);
        break;
      case 22:
        m2 = null !== c && null !== c.memoizedState;
        a2.mode & 1 ? (U2 = (l2 = U2) || m2, ck(b2, a2), U2 = l2) : ck(b2, a2);
        ek(a2);
        if (d & 8192) {
          l2 = null !== a2.memoizedState;
          if ((a2.stateNode.isHidden = l2) && !m2 && 0 !== (a2.mode & 1)) for (V2 = a2, m2 = a2.child; null !== m2; ) {
            for (q2 = V2 = m2; null !== V2; ) {
              r2 = V2;
              y = r2.child;
              switch (r2.tag) {
                case 0:
                case 11:
                case 14:
                case 15:
                  Pj(4, r2, r2.return);
                  break;
                case 1:
                  Lj(r2, r2.return);
                  var n = r2.stateNode;
                  if ("function" === typeof n.componentWillUnmount) {
                    d = r2;
                    c = r2.return;
                    try {
                      b2 = d, n.props = b2.memoizedProps, n.state = b2.memoizedState, n.componentWillUnmount();
                    } catch (t2) {
                      W2(d, c, t2);
                    }
                  }
                  break;
                case 5:
                  Lj(r2, r2.return);
                  break;
                case 22:
                  if (null !== r2.memoizedState) {
                    gk(q2);
                    continue;
                  }
              }
              null !== y ? (y.return = r2, V2 = y) : gk(q2);
            }
            m2 = m2.sibling;
          }
          a: for (m2 = null, q2 = a2; ; ) {
            if (5 === q2.tag) {
              if (null === m2) {
                m2 = q2;
                try {
                  e2 = q2.stateNode, l2 ? (f2 = e2.style, "function" === typeof f2.setProperty ? f2.setProperty("display", "none", "important") : f2.display = "none") : (h2 = q2.stateNode, k2 = q2.memoizedProps.style, g2 = void 0 !== k2 && null !== k2 && k2.hasOwnProperty("display") ? k2.display : null, h2.style.display = rb("display", g2));
                } catch (t2) {
                  W2(a2, a2.return, t2);
                }
              }
            } else if (6 === q2.tag) {
              if (null === m2) try {
                q2.stateNode.nodeValue = l2 ? "" : q2.memoizedProps;
              } catch (t2) {
                W2(a2, a2.return, t2);
              }
            } else if ((22 !== q2.tag && 23 !== q2.tag || null === q2.memoizedState || q2 === a2) && null !== q2.child) {
              q2.child.return = q2;
              q2 = q2.child;
              continue;
            }
            if (q2 === a2) break a;
            for (; null === q2.sibling; ) {
              if (null === q2.return || q2.return === a2) break a;
              m2 === q2 && (m2 = null);
              q2 = q2.return;
            }
            m2 === q2 && (m2 = null);
            q2.sibling.return = q2.return;
            q2 = q2.sibling;
          }
        }
        break;
      case 19:
        ck(b2, a2);
        ek(a2);
        d & 4 && ak(a2);
        break;
      case 21:
        break;
      default:
        ck(
          b2,
          a2
        ), ek(a2);
    }
  }
  function ek(a2) {
    var b2 = a2.flags;
    if (b2 & 2) {
      try {
        a: {
          for (var c = a2.return; null !== c; ) {
            if (Tj(c)) {
              var d = c;
              break a;
            }
            c = c.return;
          }
          throw Error(p2(160));
        }
        switch (d.tag) {
          case 5:
            var e2 = d.stateNode;
            d.flags & 32 && (ob(e2, ""), d.flags &= -33);
            var f2 = Uj(a2);
            Wj(a2, f2, e2);
            break;
          case 3:
          case 4:
            var g2 = d.stateNode.containerInfo, h2 = Uj(a2);
            Vj(a2, h2, g2);
            break;
          default:
            throw Error(p2(161));
        }
      } catch (k2) {
        W2(a2, a2.return, k2);
      }
      a2.flags &= -3;
    }
    b2 & 4096 && (a2.flags &= -4097);
  }
  function hk(a2, b2, c) {
    V2 = a2;
    ik(a2);
  }
  function ik(a2, b2, c) {
    for (var d = 0 !== (a2.mode & 1); null !== V2; ) {
      var e2 = V2, f2 = e2.child;
      if (22 === e2.tag && d) {
        var g2 = null !== e2.memoizedState || Jj;
        if (!g2) {
          var h2 = e2.alternate, k2 = null !== h2 && null !== h2.memoizedState || U2;
          h2 = Jj;
          var l2 = U2;
          Jj = g2;
          if ((U2 = k2) && !l2) for (V2 = e2; null !== V2; ) g2 = V2, k2 = g2.child, 22 === g2.tag && null !== g2.memoizedState ? jk(e2) : null !== k2 ? (k2.return = g2, V2 = k2) : jk(e2);
          for (; null !== f2; ) V2 = f2, ik(f2), f2 = f2.sibling;
          V2 = e2;
          Jj = h2;
          U2 = l2;
        }
        kk(a2);
      } else 0 !== (e2.subtreeFlags & 8772) && null !== f2 ? (f2.return = e2, V2 = f2) : kk(a2);
    }
  }
  function kk(a2) {
    for (; null !== V2; ) {
      var b2 = V2;
      if (0 !== (b2.flags & 8772)) {
        var c = b2.alternate;
        try {
          if (0 !== (b2.flags & 8772)) switch (b2.tag) {
            case 0:
            case 11:
            case 15:
              U2 || Qj(5, b2);
              break;
            case 1:
              var d = b2.stateNode;
              if (b2.flags & 4 && !U2) if (null === c) d.componentDidMount();
              else {
                var e2 = b2.elementType === b2.type ? c.memoizedProps : Ci2(b2.type, c.memoizedProps);
                d.componentDidUpdate(e2, c.memoizedState, d.__reactInternalSnapshotBeforeUpdate);
              }
              var f2 = b2.updateQueue;
              null !== f2 && sh(b2, f2, d);
              break;
            case 3:
              var g2 = b2.updateQueue;
              if (null !== g2) {
                c = null;
                if (null !== b2.child) switch (b2.child.tag) {
                  case 5:
                    c = b2.child.stateNode;
                    break;
                  case 1:
                    c = b2.child.stateNode;
                }
                sh(b2, g2, c);
              }
              break;
            case 5:
              var h2 = b2.stateNode;
              if (null === c && b2.flags & 4) {
                c = h2;
                var k2 = b2.memoizedProps;
                switch (b2.type) {
                  case "button":
                  case "input":
                  case "select":
                  case "textarea":
                    k2.autoFocus && c.focus();
                    break;
                  case "img":
                    k2.src && (c.src = k2.src);
                }
              }
              break;
            case 6:
              break;
            case 4:
              break;
            case 12:
              break;
            case 13:
              if (null === b2.memoizedState) {
                var l2 = b2.alternate;
                if (null !== l2) {
                  var m2 = l2.memoizedState;
                  if (null !== m2) {
                    var q2 = m2.dehydrated;
                    null !== q2 && bd2(q2);
                  }
                }
              }
              break;
            case 19:
            case 17:
            case 21:
            case 22:
            case 23:
            case 25:
              break;
            default:
              throw Error(p2(163));
          }
          U2 || b2.flags & 512 && Rj(b2);
        } catch (r2) {
          W2(b2, b2.return, r2);
        }
      }
      if (b2 === a2) {
        V2 = null;
        break;
      }
      c = b2.sibling;
      if (null !== c) {
        c.return = b2.return;
        V2 = c;
        break;
      }
      V2 = b2.return;
    }
  }
  function gk(a2) {
    for (; null !== V2; ) {
      var b2 = V2;
      if (b2 === a2) {
        V2 = null;
        break;
      }
      var c = b2.sibling;
      if (null !== c) {
        c.return = b2.return;
        V2 = c;
        break;
      }
      V2 = b2.return;
    }
  }
  function jk(a2) {
    for (; null !== V2; ) {
      var b2 = V2;
      try {
        switch (b2.tag) {
          case 0:
          case 11:
          case 15:
            var c = b2.return;
            try {
              Qj(4, b2);
            } catch (k2) {
              W2(b2, c, k2);
            }
            break;
          case 1:
            var d = b2.stateNode;
            if ("function" === typeof d.componentDidMount) {
              var e2 = b2.return;
              try {
                d.componentDidMount();
              } catch (k2) {
                W2(b2, e2, k2);
              }
            }
            var f2 = b2.return;
            try {
              Rj(b2);
            } catch (k2) {
              W2(b2, f2, k2);
            }
            break;
          case 5:
            var g2 = b2.return;
            try {
              Rj(b2);
            } catch (k2) {
              W2(b2, g2, k2);
            }
        }
      } catch (k2) {
        W2(b2, b2.return, k2);
      }
      if (b2 === a2) {
        V2 = null;
        break;
      }
      var h2 = b2.sibling;
      if (null !== h2) {
        h2.return = b2.return;
        V2 = h2;
        break;
      }
      V2 = b2.return;
    }
  }
  var lk = Math.ceil, mk = ua2.ReactCurrentDispatcher, nk = ua2.ReactCurrentOwner, ok = ua2.ReactCurrentBatchConfig, K2 = 0, Q2 = null, Y2 = null, Z2 = 0, fj = 0, ej = Uf2(0), T2 = 0, pk = null, rh = 0, qk = 0, rk = 0, sk = null, tk = null, fk = 0, Gj = Infinity, uk = null, Oi = false, Pi = null, Ri2 = null, vk = false, wk = null, xk = 0, yk = 0, zk = null, Ak = -1, Bk = 0;
  function R() {
    return 0 !== (K2 & 6) ? B2() : -1 !== Ak ? Ak : Ak = B2();
  }
  function yi2(a2) {
    if (0 === (a2.mode & 1)) return 1;
    if (0 !== (K2 & 2) && 0 !== Z2) return Z2 & -Z2;
    if (null !== Kg.transition) return 0 === Bk && (Bk = yc()), Bk;
    a2 = C;
    if (0 !== a2) return a2;
    a2 = window.event;
    a2 = void 0 === a2 ? 16 : jd2(a2.type);
    return a2;
  }
  function gi2(a2, b2, c, d) {
    if (50 < yk) throw yk = 0, zk = null, Error(p2(185));
    Ac2(a2, c, d);
    if (0 === (K2 & 2) || a2 !== Q2) a2 === Q2 && (0 === (K2 & 2) && (qk |= c), 4 === T2 && Ck(a2, Z2)), Dk(a2, d), 1 === c && 0 === K2 && 0 === (b2.mode & 1) && (Gj = B2() + 500, fg && jg());
  }
  function Dk(a2, b2) {
    var c = a2.callbackNode;
    wc(a2, b2);
    var d = uc2(a2, a2 === Q2 ? Z2 : 0);
    if (0 === d) null !== c && bc(c), a2.callbackNode = null, a2.callbackPriority = 0;
    else if (b2 = d & -d, a2.callbackPriority !== b2) {
      null != c && bc(c);
      if (1 === b2) 0 === a2.tag ? ig(Ek.bind(null, a2)) : hg(Ek.bind(null, a2)), Jf2(function() {
        0 === (K2 & 6) && jg();
      }), c = null;
      else {
        switch (Dc2(d)) {
          case 1:
            c = fc;
            break;
          case 4:
            c = gc;
            break;
          case 16:
            c = hc;
            break;
          case 536870912:
            c = jc;
            break;
          default:
            c = hc;
        }
        c = Fk(c, Gk.bind(null, a2));
      }
      a2.callbackPriority = b2;
      a2.callbackNode = c;
    }
  }
  function Gk(a2, b2) {
    Ak = -1;
    Bk = 0;
    if (0 !== (K2 & 6)) throw Error(p2(327));
    var c = a2.callbackNode;
    if (Hk() && a2.callbackNode !== c) return null;
    var d = uc2(a2, a2 === Q2 ? Z2 : 0);
    if (0 === d) return null;
    if (0 !== (d & 30) || 0 !== (d & a2.expiredLanes) || b2) b2 = Ik(a2, d);
    else {
      b2 = d;
      var e2 = K2;
      K2 |= 2;
      var f2 = Jk();
      if (Q2 !== a2 || Z2 !== b2) uk = null, Gj = B2() + 500, Kk(a2, b2);
      do
        try {
          Lk();
          break;
        } catch (h2) {
          Mk(a2, h2);
        }
      while (1);
      $g();
      mk.current = f2;
      K2 = e2;
      null !== Y2 ? b2 = 0 : (Q2 = null, Z2 = 0, b2 = T2);
    }
    if (0 !== b2) {
      2 === b2 && (e2 = xc(a2), 0 !== e2 && (d = e2, b2 = Nk(a2, e2)));
      if (1 === b2) throw c = pk, Kk(a2, 0), Ck(a2, d), Dk(a2, B2()), c;
      if (6 === b2) Ck(a2, d);
      else {
        e2 = a2.current.alternate;
        if (0 === (d & 30) && !Ok(e2) && (b2 = Ik(a2, d), 2 === b2 && (f2 = xc(a2), 0 !== f2 && (d = f2, b2 = Nk(a2, f2))), 1 === b2)) throw c = pk, Kk(a2, 0), Ck(a2, d), Dk(a2, B2()), c;
        a2.finishedWork = e2;
        a2.finishedLanes = d;
        switch (b2) {
          case 0:
          case 1:
            throw Error(p2(345));
          case 2:
            Pk(a2, tk, uk);
            break;
          case 3:
            Ck(a2, d);
            if ((d & 130023424) === d && (b2 = fk + 500 - B2(), 10 < b2)) {
              if (0 !== uc2(a2, 0)) break;
              e2 = a2.suspendedLanes;
              if ((e2 & d) !== d) {
                R();
                a2.pingedLanes |= a2.suspendedLanes & e2;
                break;
              }
              a2.timeoutHandle = Ff2(Pk.bind(null, a2, tk, uk), b2);
              break;
            }
            Pk(a2, tk, uk);
            break;
          case 4:
            Ck(a2, d);
            if ((d & 4194240) === d) break;
            b2 = a2.eventTimes;
            for (e2 = -1; 0 < d; ) {
              var g2 = 31 - oc2(d);
              f2 = 1 << g2;
              g2 = b2[g2];
              g2 > e2 && (e2 = g2);
              d &= ~f2;
            }
            d = e2;
            d = B2() - d;
            d = (120 > d ? 120 : 480 > d ? 480 : 1080 > d ? 1080 : 1920 > d ? 1920 : 3e3 > d ? 3e3 : 4320 > d ? 4320 : 1960 * lk(d / 1960)) - d;
            if (10 < d) {
              a2.timeoutHandle = Ff2(Pk.bind(null, a2, tk, uk), d);
              break;
            }
            Pk(a2, tk, uk);
            break;
          case 5:
            Pk(a2, tk, uk);
            break;
          default:
            throw Error(p2(329));
        }
      }
    }
    Dk(a2, B2());
    return a2.callbackNode === c ? Gk.bind(null, a2) : null;
  }
  function Nk(a2, b2) {
    var c = sk;
    a2.current.memoizedState.isDehydrated && (Kk(a2, b2).flags |= 256);
    a2 = Ik(a2, b2);
    2 !== a2 && (b2 = tk, tk = c, null !== b2 && Fj(b2));
    return a2;
  }
  function Fj(a2) {
    null === tk ? tk = a2 : tk.push.apply(tk, a2);
  }
  function Ok(a2) {
    for (var b2 = a2; ; ) {
      if (b2.flags & 16384) {
        var c = b2.updateQueue;
        if (null !== c && (c = c.stores, null !== c)) for (var d = 0; d < c.length; d++) {
          var e2 = c[d], f2 = e2.getSnapshot;
          e2 = e2.value;
          try {
            if (!He2(f2(), e2)) return false;
          } catch (g2) {
            return false;
          }
        }
      }
      c = b2.child;
      if (b2.subtreeFlags & 16384 && null !== c) c.return = b2, b2 = c;
      else {
        if (b2 === a2) break;
        for (; null === b2.sibling; ) {
          if (null === b2.return || b2.return === a2) return true;
          b2 = b2.return;
        }
        b2.sibling.return = b2.return;
        b2 = b2.sibling;
      }
    }
    return true;
  }
  function Ck(a2, b2) {
    b2 &= ~rk;
    b2 &= ~qk;
    a2.suspendedLanes |= b2;
    a2.pingedLanes &= ~b2;
    for (a2 = a2.expirationTimes; 0 < b2; ) {
      var c = 31 - oc2(b2), d = 1 << c;
      a2[c] = -1;
      b2 &= ~d;
    }
  }
  function Ek(a2) {
    if (0 !== (K2 & 6)) throw Error(p2(327));
    Hk();
    var b2 = uc2(a2, 0);
    if (0 === (b2 & 1)) return Dk(a2, B2()), null;
    var c = Ik(a2, b2);
    if (0 !== a2.tag && 2 === c) {
      var d = xc(a2);
      0 !== d && (b2 = d, c = Nk(a2, d));
    }
    if (1 === c) throw c = pk, Kk(a2, 0), Ck(a2, b2), Dk(a2, B2()), c;
    if (6 === c) throw Error(p2(345));
    a2.finishedWork = a2.current.alternate;
    a2.finishedLanes = b2;
    Pk(a2, tk, uk);
    Dk(a2, B2());
    return null;
  }
  function Qk(a2, b2) {
    var c = K2;
    K2 |= 1;
    try {
      return a2(b2);
    } finally {
      K2 = c, 0 === K2 && (Gj = B2() + 500, fg && jg());
    }
  }
  function Rk(a2) {
    null !== wk && 0 === wk.tag && 0 === (K2 & 6) && Hk();
    var b2 = K2;
    K2 |= 1;
    var c = ok.transition, d = C;
    try {
      if (ok.transition = null, C = 1, a2) return a2();
    } finally {
      C = d, ok.transition = c, K2 = b2, 0 === (K2 & 6) && jg();
    }
  }
  function Hj() {
    fj = ej.current;
    E2(ej);
  }
  function Kk(a2, b2) {
    a2.finishedWork = null;
    a2.finishedLanes = 0;
    var c = a2.timeoutHandle;
    -1 !== c && (a2.timeoutHandle = -1, Gf2(c));
    if (null !== Y2) for (c = Y2.return; null !== c; ) {
      var d = c;
      wg(d);
      switch (d.tag) {
        case 1:
          d = d.type.childContextTypes;
          null !== d && void 0 !== d && $f2();
          break;
        case 3:
          zh();
          E2(Wf2);
          E2(H2);
          Eh();
          break;
        case 5:
          Bh(d);
          break;
        case 4:
          zh();
          break;
        case 13:
          E2(L2);
          break;
        case 19:
          E2(L2);
          break;
        case 10:
          ah(d.type._context);
          break;
        case 22:
        case 23:
          Hj();
      }
      c = c.return;
    }
    Q2 = a2;
    Y2 = a2 = Pg(a2.current, null);
    Z2 = fj = b2;
    T2 = 0;
    pk = null;
    rk = qk = rh = 0;
    tk = sk = null;
    if (null !== fh) {
      for (b2 = 0; b2 < fh.length; b2++) if (c = fh[b2], d = c.interleaved, null !== d) {
        c.interleaved = null;
        var e2 = d.next, f2 = c.pending;
        if (null !== f2) {
          var g2 = f2.next;
          f2.next = e2;
          d.next = g2;
        }
        c.pending = d;
      }
      fh = null;
    }
    return a2;
  }
  function Mk(a2, b2) {
    do {
      var c = Y2;
      try {
        $g();
        Fh.current = Rh;
        if (Ih) {
          for (var d = M2.memoizedState; null !== d; ) {
            var e2 = d.queue;
            null !== e2 && (e2.pending = null);
            d = d.next;
          }
          Ih = false;
        }
        Hh = 0;
        O2 = N2 = M2 = null;
        Jh = false;
        Kh = 0;
        nk.current = null;
        if (null === c || null === c.return) {
          T2 = 1;
          pk = b2;
          Y2 = null;
          break;
        }
        a: {
          var f2 = a2, g2 = c.return, h2 = c, k2 = b2;
          b2 = Z2;
          h2.flags |= 32768;
          if (null !== k2 && "object" === typeof k2 && "function" === typeof k2.then) {
            var l2 = k2, m2 = h2, q2 = m2.tag;
            if (0 === (m2.mode & 1) && (0 === q2 || 11 === q2 || 15 === q2)) {
              var r2 = m2.alternate;
              r2 ? (m2.updateQueue = r2.updateQueue, m2.memoizedState = r2.memoizedState, m2.lanes = r2.lanes) : (m2.updateQueue = null, m2.memoizedState = null);
            }
            var y = Ui(g2);
            if (null !== y) {
              y.flags &= -257;
              Vi2(y, g2, h2, f2, b2);
              y.mode & 1 && Si2(f2, l2, b2);
              b2 = y;
              k2 = l2;
              var n = b2.updateQueue;
              if (null === n) {
                var t2 = /* @__PURE__ */ new Set();
                t2.add(k2);
                b2.updateQueue = t2;
              } else n.add(k2);
              break a;
            } else {
              if (0 === (b2 & 1)) {
                Si2(f2, l2, b2);
                tj();
                break a;
              }
              k2 = Error(p2(426));
            }
          } else if (I2 && h2.mode & 1) {
            var J2 = Ui(g2);
            if (null !== J2) {
              0 === (J2.flags & 65536) && (J2.flags |= 256);
              Vi2(J2, g2, h2, f2, b2);
              Jg(Ji2(k2, h2));
              break a;
            }
          }
          f2 = k2 = Ji2(k2, h2);
          4 !== T2 && (T2 = 2);
          null === sk ? sk = [f2] : sk.push(f2);
          f2 = g2;
          do {
            switch (f2.tag) {
              case 3:
                f2.flags |= 65536;
                b2 &= -b2;
                f2.lanes |= b2;
                var x2 = Ni(f2, k2, b2);
                ph(f2, x2);
                break a;
              case 1:
                h2 = k2;
                var w2 = f2.type, u2 = f2.stateNode;
                if (0 === (f2.flags & 128) && ("function" === typeof w2.getDerivedStateFromError || null !== u2 && "function" === typeof u2.componentDidCatch && (null === Ri2 || !Ri2.has(u2)))) {
                  f2.flags |= 65536;
                  b2 &= -b2;
                  f2.lanes |= b2;
                  var F2 = Qi2(f2, h2, b2);
                  ph(f2, F2);
                  break a;
                }
            }
            f2 = f2.return;
          } while (null !== f2);
        }
        Sk(c);
      } catch (na2) {
        b2 = na2;
        Y2 === c && null !== c && (Y2 = c = c.return);
        continue;
      }
      break;
    } while (1);
  }
  function Jk() {
    var a2 = mk.current;
    mk.current = Rh;
    return null === a2 ? Rh : a2;
  }
  function tj() {
    if (0 === T2 || 3 === T2 || 2 === T2) T2 = 4;
    null === Q2 || 0 === (rh & 268435455) && 0 === (qk & 268435455) || Ck(Q2, Z2);
  }
  function Ik(a2, b2) {
    var c = K2;
    K2 |= 2;
    var d = Jk();
    if (Q2 !== a2 || Z2 !== b2) uk = null, Kk(a2, b2);
    do
      try {
        Tk();
        break;
      } catch (e2) {
        Mk(a2, e2);
      }
    while (1);
    $g();
    K2 = c;
    mk.current = d;
    if (null !== Y2) throw Error(p2(261));
    Q2 = null;
    Z2 = 0;
    return T2;
  }
  function Tk() {
    for (; null !== Y2; ) Uk(Y2);
  }
  function Lk() {
    for (; null !== Y2 && !cc(); ) Uk(Y2);
  }
  function Uk(a2) {
    var b2 = Vk(a2.alternate, a2, fj);
    a2.memoizedProps = a2.pendingProps;
    null === b2 ? Sk(a2) : Y2 = b2;
    nk.current = null;
  }
  function Sk(a2) {
    var b2 = a2;
    do {
      var c = b2.alternate;
      a2 = b2.return;
      if (0 === (b2.flags & 32768)) {
        if (c = Ej(c, b2, fj), null !== c) {
          Y2 = c;
          return;
        }
      } else {
        c = Ij(c, b2);
        if (null !== c) {
          c.flags &= 32767;
          Y2 = c;
          return;
        }
        if (null !== a2) a2.flags |= 32768, a2.subtreeFlags = 0, a2.deletions = null;
        else {
          T2 = 6;
          Y2 = null;
          return;
        }
      }
      b2 = b2.sibling;
      if (null !== b2) {
        Y2 = b2;
        return;
      }
      Y2 = b2 = a2;
    } while (null !== b2);
    0 === T2 && (T2 = 5);
  }
  function Pk(a2, b2, c) {
    var d = C, e2 = ok.transition;
    try {
      ok.transition = null, C = 1, Wk(a2, b2, c, d);
    } finally {
      ok.transition = e2, C = d;
    }
    return null;
  }
  function Wk(a2, b2, c, d) {
    do
      Hk();
    while (null !== wk);
    if (0 !== (K2 & 6)) throw Error(p2(327));
    c = a2.finishedWork;
    var e2 = a2.finishedLanes;
    if (null === c) return null;
    a2.finishedWork = null;
    a2.finishedLanes = 0;
    if (c === a2.current) throw Error(p2(177));
    a2.callbackNode = null;
    a2.callbackPriority = 0;
    var f2 = c.lanes | c.childLanes;
    Bc2(a2, f2);
    a2 === Q2 && (Y2 = Q2 = null, Z2 = 0);
    0 === (c.subtreeFlags & 2064) && 0 === (c.flags & 2064) || vk || (vk = true, Fk(hc, function() {
      Hk();
      return null;
    }));
    f2 = 0 !== (c.flags & 15990);
    if (0 !== (c.subtreeFlags & 15990) || f2) {
      f2 = ok.transition;
      ok.transition = null;
      var g2 = C;
      C = 1;
      var h2 = K2;
      K2 |= 4;
      nk.current = null;
      Oj(a2, c);
      dk(c, a2);
      Oe(Df2);
      dd2 = !!Cf2;
      Df2 = Cf2 = null;
      a2.current = c;
      hk(c);
      dc();
      K2 = h2;
      C = g2;
      ok.transition = f2;
    } else a2.current = c;
    vk && (vk = false, wk = a2, xk = e2);
    f2 = a2.pendingLanes;
    0 === f2 && (Ri2 = null);
    mc(c.stateNode);
    Dk(a2, B2());
    if (null !== b2) for (d = a2.onRecoverableError, c = 0; c < b2.length; c++) e2 = b2[c], d(e2.value, { componentStack: e2.stack, digest: e2.digest });
    if (Oi) throw Oi = false, a2 = Pi, Pi = null, a2;
    0 !== (xk & 1) && 0 !== a2.tag && Hk();
    f2 = a2.pendingLanes;
    0 !== (f2 & 1) ? a2 === zk ? yk++ : (yk = 0, zk = a2) : yk = 0;
    jg();
    return null;
  }
  function Hk() {
    if (null !== wk) {
      var a2 = Dc2(xk), b2 = ok.transition, c = C;
      try {
        ok.transition = null;
        C = 16 > a2 ? 16 : a2;
        if (null === wk) var d = false;
        else {
          a2 = wk;
          wk = null;
          xk = 0;
          if (0 !== (K2 & 6)) throw Error(p2(331));
          var e2 = K2;
          K2 |= 4;
          for (V2 = a2.current; null !== V2; ) {
            var f2 = V2, g2 = f2.child;
            if (0 !== (V2.flags & 16)) {
              var h2 = f2.deletions;
              if (null !== h2) {
                for (var k2 = 0; k2 < h2.length; k2++) {
                  var l2 = h2[k2];
                  for (V2 = l2; null !== V2; ) {
                    var m2 = V2;
                    switch (m2.tag) {
                      case 0:
                      case 11:
                      case 15:
                        Pj(8, m2, f2);
                    }
                    var q2 = m2.child;
                    if (null !== q2) q2.return = m2, V2 = q2;
                    else for (; null !== V2; ) {
                      m2 = V2;
                      var r2 = m2.sibling, y = m2.return;
                      Sj(m2);
                      if (m2 === l2) {
                        V2 = null;
                        break;
                      }
                      if (null !== r2) {
                        r2.return = y;
                        V2 = r2;
                        break;
                      }
                      V2 = y;
                    }
                  }
                }
                var n = f2.alternate;
                if (null !== n) {
                  var t2 = n.child;
                  if (null !== t2) {
                    n.child = null;
                    do {
                      var J2 = t2.sibling;
                      t2.sibling = null;
                      t2 = J2;
                    } while (null !== t2);
                  }
                }
                V2 = f2;
              }
            }
            if (0 !== (f2.subtreeFlags & 2064) && null !== g2) g2.return = f2, V2 = g2;
            else b: for (; null !== V2; ) {
              f2 = V2;
              if (0 !== (f2.flags & 2048)) switch (f2.tag) {
                case 0:
                case 11:
                case 15:
                  Pj(9, f2, f2.return);
              }
              var x2 = f2.sibling;
              if (null !== x2) {
                x2.return = f2.return;
                V2 = x2;
                break b;
              }
              V2 = f2.return;
            }
          }
          var w2 = a2.current;
          for (V2 = w2; null !== V2; ) {
            g2 = V2;
            var u2 = g2.child;
            if (0 !== (g2.subtreeFlags & 2064) && null !== u2) u2.return = g2, V2 = u2;
            else b: for (g2 = w2; null !== V2; ) {
              h2 = V2;
              if (0 !== (h2.flags & 2048)) try {
                switch (h2.tag) {
                  case 0:
                  case 11:
                  case 15:
                    Qj(9, h2);
                }
              } catch (na2) {
                W2(h2, h2.return, na2);
              }
              if (h2 === g2) {
                V2 = null;
                break b;
              }
              var F2 = h2.sibling;
              if (null !== F2) {
                F2.return = h2.return;
                V2 = F2;
                break b;
              }
              V2 = h2.return;
            }
          }
          K2 = e2;
          jg();
          if (lc && "function" === typeof lc.onPostCommitFiberRoot) try {
            lc.onPostCommitFiberRoot(kc, a2);
          } catch (na2) {
          }
          d = true;
        }
        return d;
      } finally {
        C = c, ok.transition = b2;
      }
    }
    return false;
  }
  function Xk(a2, b2, c) {
    b2 = Ji2(c, b2);
    b2 = Ni(a2, b2, 1);
    a2 = nh(a2, b2, 1);
    b2 = R();
    null !== a2 && (Ac2(a2, 1, b2), Dk(a2, b2));
  }
  function W2(a2, b2, c) {
    if (3 === a2.tag) Xk(a2, a2, c);
    else for (; null !== b2; ) {
      if (3 === b2.tag) {
        Xk(b2, a2, c);
        break;
      } else if (1 === b2.tag) {
        var d = b2.stateNode;
        if ("function" === typeof b2.type.getDerivedStateFromError || "function" === typeof d.componentDidCatch && (null === Ri2 || !Ri2.has(d))) {
          a2 = Ji2(c, a2);
          a2 = Qi2(b2, a2, 1);
          b2 = nh(b2, a2, 1);
          a2 = R();
          null !== b2 && (Ac2(b2, 1, a2), Dk(b2, a2));
          break;
        }
      }
      b2 = b2.return;
    }
  }
  function Ti2(a2, b2, c) {
    var d = a2.pingCache;
    null !== d && d.delete(b2);
    b2 = R();
    a2.pingedLanes |= a2.suspendedLanes & c;
    Q2 === a2 && (Z2 & c) === c && (4 === T2 || 3 === T2 && (Z2 & 130023424) === Z2 && 500 > B2() - fk ? Kk(a2, 0) : rk |= c);
    Dk(a2, b2);
  }
  function Yk(a2, b2) {
    0 === b2 && (0 === (a2.mode & 1) ? b2 = 1 : (b2 = sc, sc <<= 1, 0 === (sc & 130023424) && (sc = 4194304)));
    var c = R();
    a2 = ih(a2, b2);
    null !== a2 && (Ac2(a2, b2, c), Dk(a2, c));
  }
  function uj(a2) {
    var b2 = a2.memoizedState, c = 0;
    null !== b2 && (c = b2.retryLane);
    Yk(a2, c);
  }
  function bk(a2, b2) {
    var c = 0;
    switch (a2.tag) {
      case 13:
        var d = a2.stateNode;
        var e2 = a2.memoizedState;
        null !== e2 && (c = e2.retryLane);
        break;
      case 19:
        d = a2.stateNode;
        break;
      default:
        throw Error(p2(314));
    }
    null !== d && d.delete(b2);
    Yk(a2, c);
  }
  var Vk;
  Vk = function(a2, b2, c) {
    if (null !== a2) if (a2.memoizedProps !== b2.pendingProps || Wf2.current) dh = true;
    else {
      if (0 === (a2.lanes & c) && 0 === (b2.flags & 128)) return dh = false, yj(a2, b2, c);
      dh = 0 !== (a2.flags & 131072) ? true : false;
    }
    else dh = false, I2 && 0 !== (b2.flags & 1048576) && ug(b2, ng, b2.index);
    b2.lanes = 0;
    switch (b2.tag) {
      case 2:
        var d = b2.type;
        ij(a2, b2);
        a2 = b2.pendingProps;
        var e2 = Yf2(b2, H2.current);
        ch(b2, c);
        e2 = Nh(null, b2, d, a2, e2, c);
        var f2 = Sh();
        b2.flags |= 1;
        "object" === typeof e2 && null !== e2 && "function" === typeof e2.render && void 0 === e2.$$typeof ? (b2.tag = 1, b2.memoizedState = null, b2.updateQueue = null, Zf2(d) ? (f2 = true, cg(b2)) : f2 = false, b2.memoizedState = null !== e2.state && void 0 !== e2.state ? e2.state : null, kh(b2), e2.updater = Ei2, b2.stateNode = e2, e2._reactInternals = b2, Ii2(b2, d, a2, c), b2 = jj(null, b2, d, true, f2, c)) : (b2.tag = 0, I2 && f2 && vg(b2), Xi2(null, b2, e2, c), b2 = b2.child);
        return b2;
      case 16:
        d = b2.elementType;
        a: {
          ij(a2, b2);
          a2 = b2.pendingProps;
          e2 = d._init;
          d = e2(d._payload);
          b2.type = d;
          e2 = b2.tag = Zk(d);
          a2 = Ci2(d, a2);
          switch (e2) {
            case 0:
              b2 = cj(null, b2, d, a2, c);
              break a;
            case 1:
              b2 = hj(null, b2, d, a2, c);
              break a;
            case 11:
              b2 = Yi2(null, b2, d, a2, c);
              break a;
            case 14:
              b2 = $i2(null, b2, d, Ci2(d.type, a2), c);
              break a;
          }
          throw Error(p2(
            306,
            d,
            ""
          ));
        }
        return b2;
      case 0:
        return d = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d ? e2 : Ci2(d, e2), cj(a2, b2, d, e2, c);
      case 1:
        return d = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d ? e2 : Ci2(d, e2), hj(a2, b2, d, e2, c);
      case 3:
        a: {
          kj(b2);
          if (null === a2) throw Error(p2(387));
          d = b2.pendingProps;
          f2 = b2.memoizedState;
          e2 = f2.element;
          lh(a2, b2);
          qh(b2, d, null, c);
          var g2 = b2.memoizedState;
          d = g2.element;
          if (f2.isDehydrated) if (f2 = { element: d, isDehydrated: false, cache: g2.cache, pendingSuspenseBoundaries: g2.pendingSuspenseBoundaries, transitions: g2.transitions }, b2.updateQueue.baseState = f2, b2.memoizedState = f2, b2.flags & 256) {
            e2 = Ji2(Error(p2(423)), b2);
            b2 = lj(a2, b2, d, c, e2);
            break a;
          } else if (d !== e2) {
            e2 = Ji2(Error(p2(424)), b2);
            b2 = lj(a2, b2, d, c, e2);
            break a;
          } else for (yg = Lf2(b2.stateNode.containerInfo.firstChild), xg = b2, I2 = true, zg = null, c = Vg(b2, null, d, c), b2.child = c; c; ) c.flags = c.flags & -3 | 4096, c = c.sibling;
          else {
            Ig();
            if (d === e2) {
              b2 = Zi(a2, b2, c);
              break a;
            }
            Xi2(a2, b2, d, c);
          }
          b2 = b2.child;
        }
        return b2;
      case 5:
        return Ah(b2), null === a2 && Eg(b2), d = b2.type, e2 = b2.pendingProps, f2 = null !== a2 ? a2.memoizedProps : null, g2 = e2.children, Ef2(d, e2) ? g2 = null : null !== f2 && Ef2(d, f2) && (b2.flags |= 32), gj(a2, b2), Xi2(a2, b2, g2, c), b2.child;
      case 6:
        return null === a2 && Eg(b2), null;
      case 13:
        return oj(a2, b2, c);
      case 4:
        return yh(b2, b2.stateNode.containerInfo), d = b2.pendingProps, null === a2 ? b2.child = Ug(b2, null, d, c) : Xi2(a2, b2, d, c), b2.child;
      case 11:
        return d = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d ? e2 : Ci2(d, e2), Yi2(a2, b2, d, e2, c);
      case 7:
        return Xi2(a2, b2, b2.pendingProps, c), b2.child;
      case 8:
        return Xi2(a2, b2, b2.pendingProps.children, c), b2.child;
      case 12:
        return Xi2(a2, b2, b2.pendingProps.children, c), b2.child;
      case 10:
        a: {
          d = b2.type._context;
          e2 = b2.pendingProps;
          f2 = b2.memoizedProps;
          g2 = e2.value;
          G2(Wg, d._currentValue);
          d._currentValue = g2;
          if (null !== f2) if (He2(f2.value, g2)) {
            if (f2.children === e2.children && !Wf2.current) {
              b2 = Zi(a2, b2, c);
              break a;
            }
          } else for (f2 = b2.child, null !== f2 && (f2.return = b2); null !== f2; ) {
            var h2 = f2.dependencies;
            if (null !== h2) {
              g2 = f2.child;
              for (var k2 = h2.firstContext; null !== k2; ) {
                if (k2.context === d) {
                  if (1 === f2.tag) {
                    k2 = mh(-1, c & -c);
                    k2.tag = 2;
                    var l2 = f2.updateQueue;
                    if (null !== l2) {
                      l2 = l2.shared;
                      var m2 = l2.pending;
                      null === m2 ? k2.next = k2 : (k2.next = m2.next, m2.next = k2);
                      l2.pending = k2;
                    }
                  }
                  f2.lanes |= c;
                  k2 = f2.alternate;
                  null !== k2 && (k2.lanes |= c);
                  bh(
                    f2.return,
                    c,
                    b2
                  );
                  h2.lanes |= c;
                  break;
                }
                k2 = k2.next;
              }
            } else if (10 === f2.tag) g2 = f2.type === b2.type ? null : f2.child;
            else if (18 === f2.tag) {
              g2 = f2.return;
              if (null === g2) throw Error(p2(341));
              g2.lanes |= c;
              h2 = g2.alternate;
              null !== h2 && (h2.lanes |= c);
              bh(g2, c, b2);
              g2 = f2.sibling;
            } else g2 = f2.child;
            if (null !== g2) g2.return = f2;
            else for (g2 = f2; null !== g2; ) {
              if (g2 === b2) {
                g2 = null;
                break;
              }
              f2 = g2.sibling;
              if (null !== f2) {
                f2.return = g2.return;
                g2 = f2;
                break;
              }
              g2 = g2.return;
            }
            f2 = g2;
          }
          Xi2(a2, b2, e2.children, c);
          b2 = b2.child;
        }
        return b2;
      case 9:
        return e2 = b2.type, d = b2.pendingProps.children, ch(b2, c), e2 = eh(e2), d = d(e2), b2.flags |= 1, Xi2(a2, b2, d, c), b2.child;
      case 14:
        return d = b2.type, e2 = Ci2(d, b2.pendingProps), e2 = Ci2(d.type, e2), $i2(a2, b2, d, e2, c);
      case 15:
        return bj(a2, b2, b2.type, b2.pendingProps, c);
      case 17:
        return d = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d ? e2 : Ci2(d, e2), ij(a2, b2), b2.tag = 1, Zf2(d) ? (a2 = true, cg(b2)) : a2 = false, ch(b2, c), Gi2(b2, d, e2), Ii2(b2, d, e2, c), jj(null, b2, d, true, a2, c);
      case 19:
        return xj(a2, b2, c);
      case 22:
        return dj(a2, b2, c);
    }
    throw Error(p2(156, b2.tag));
  };
  function Fk(a2, b2) {
    return ac(a2, b2);
  }
  function $k(a2, b2, c, d) {
    this.tag = a2;
    this.key = c;
    this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
    this.index = 0;
    this.ref = null;
    this.pendingProps = b2;
    this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
    this.mode = d;
    this.subtreeFlags = this.flags = 0;
    this.deletions = null;
    this.childLanes = this.lanes = 0;
    this.alternate = null;
  }
  function Bg(a2, b2, c, d) {
    return new $k(a2, b2, c, d);
  }
  function aj(a2) {
    a2 = a2.prototype;
    return !(!a2 || !a2.isReactComponent);
  }
  function Zk(a2) {
    if ("function" === typeof a2) return aj(a2) ? 1 : 0;
    if (void 0 !== a2 && null !== a2) {
      a2 = a2.$$typeof;
      if (a2 === Da2) return 11;
      if (a2 === Ga2) return 14;
    }
    return 2;
  }
  function Pg(a2, b2) {
    var c = a2.alternate;
    null === c ? (c = Bg(a2.tag, b2, a2.key, a2.mode), c.elementType = a2.elementType, c.type = a2.type, c.stateNode = a2.stateNode, c.alternate = a2, a2.alternate = c) : (c.pendingProps = b2, c.type = a2.type, c.flags = 0, c.subtreeFlags = 0, c.deletions = null);
    c.flags = a2.flags & 14680064;
    c.childLanes = a2.childLanes;
    c.lanes = a2.lanes;
    c.child = a2.child;
    c.memoizedProps = a2.memoizedProps;
    c.memoizedState = a2.memoizedState;
    c.updateQueue = a2.updateQueue;
    b2 = a2.dependencies;
    c.dependencies = null === b2 ? null : { lanes: b2.lanes, firstContext: b2.firstContext };
    c.sibling = a2.sibling;
    c.index = a2.index;
    c.ref = a2.ref;
    return c;
  }
  function Rg(a2, b2, c, d, e2, f2) {
    var g2 = 2;
    d = a2;
    if ("function" === typeof a2) aj(a2) && (g2 = 1);
    else if ("string" === typeof a2) g2 = 5;
    else a: switch (a2) {
      case ya2:
        return Tg(c.children, e2, f2, b2);
      case za2:
        g2 = 8;
        e2 |= 8;
        break;
      case Aa2:
        return a2 = Bg(12, c, b2, e2 | 2), a2.elementType = Aa2, a2.lanes = f2, a2;
      case Ea2:
        return a2 = Bg(13, c, b2, e2), a2.elementType = Ea2, a2.lanes = f2, a2;
      case Fa2:
        return a2 = Bg(19, c, b2, e2), a2.elementType = Fa2, a2.lanes = f2, a2;
      case Ia2:
        return pj(c, e2, f2, b2);
      default:
        if ("object" === typeof a2 && null !== a2) switch (a2.$$typeof) {
          case Ba2:
            g2 = 10;
            break a;
          case Ca2:
            g2 = 9;
            break a;
          case Da2:
            g2 = 11;
            break a;
          case Ga2:
            g2 = 14;
            break a;
          case Ha2:
            g2 = 16;
            d = null;
            break a;
        }
        throw Error(p2(130, null == a2 ? a2 : typeof a2, ""));
    }
    b2 = Bg(g2, c, b2, e2);
    b2.elementType = a2;
    b2.type = d;
    b2.lanes = f2;
    return b2;
  }
  function Tg(a2, b2, c, d) {
    a2 = Bg(7, a2, d, b2);
    a2.lanes = c;
    return a2;
  }
  function pj(a2, b2, c, d) {
    a2 = Bg(22, a2, d, b2);
    a2.elementType = Ia2;
    a2.lanes = c;
    a2.stateNode = { isHidden: false };
    return a2;
  }
  function Qg(a2, b2, c) {
    a2 = Bg(6, a2, null, b2);
    a2.lanes = c;
    return a2;
  }
  function Sg(a2, b2, c) {
    b2 = Bg(4, null !== a2.children ? a2.children : [], a2.key, b2);
    b2.lanes = c;
    b2.stateNode = { containerInfo: a2.containerInfo, pendingChildren: null, implementation: a2.implementation };
    return b2;
  }
  function al2(a2, b2, c, d, e2) {
    this.tag = b2;
    this.containerInfo = a2;
    this.finishedWork = this.pingCache = this.current = this.pendingChildren = null;
    this.timeoutHandle = -1;
    this.callbackNode = this.pendingContext = this.context = null;
    this.callbackPriority = 0;
    this.eventTimes = zc(0);
    this.expirationTimes = zc(-1);
    this.entangledLanes = this.finishedLanes = this.mutableReadLanes = this.expiredLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
    this.entanglements = zc(0);
    this.identifierPrefix = d;
    this.onRecoverableError = e2;
    this.mutableSourceEagerHydrationData = null;
  }
  function bl2(a2, b2, c, d, e2, f2, g2, h2, k2) {
    a2 = new al2(a2, b2, c, h2, k2);
    1 === b2 ? (b2 = 1, true === f2 && (b2 |= 8)) : b2 = 0;
    f2 = Bg(3, null, null, b2);
    a2.current = f2;
    f2.stateNode = a2;
    f2.memoizedState = { element: d, isDehydrated: c, cache: null, transitions: null, pendingSuspenseBoundaries: null };
    kh(f2);
    return a2;
  }
  function cl2(a2, b2, c) {
    var d = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
    return { $$typeof: wa2, key: null == d ? null : "" + d, children: a2, containerInfo: b2, implementation: c };
  }
  function dl2(a2) {
    if (!a2) return Vf2;
    a2 = a2._reactInternals;
    a: {
      if (Vb(a2) !== a2 || 1 !== a2.tag) throw Error(p2(170));
      var b2 = a2;
      do {
        switch (b2.tag) {
          case 3:
            b2 = b2.stateNode.context;
            break a;
          case 1:
            if (Zf2(b2.type)) {
              b2 = b2.stateNode.__reactInternalMemoizedMergedChildContext;
              break a;
            }
        }
        b2 = b2.return;
      } while (null !== b2);
      throw Error(p2(171));
    }
    if (1 === a2.tag) {
      var c = a2.type;
      if (Zf2(c)) return bg(a2, c, b2);
    }
    return b2;
  }
  function el2(a2, b2, c, d, e2, f2, g2, h2, k2) {
    a2 = bl2(c, d, true, a2, e2, f2, g2, h2, k2);
    a2.context = dl2(null);
    c = a2.current;
    d = R();
    e2 = yi2(c);
    f2 = mh(d, e2);
    f2.callback = void 0 !== b2 && null !== b2 ? b2 : null;
    nh(c, f2, e2);
    a2.current.lanes = e2;
    Ac2(a2, e2, d);
    Dk(a2, d);
    return a2;
  }
  function fl2(a2, b2, c, d) {
    var e2 = b2.current, f2 = R(), g2 = yi2(e2);
    c = dl2(c);
    null === b2.context ? b2.context = c : b2.pendingContext = c;
    b2 = mh(f2, g2);
    b2.payload = { element: a2 };
    d = void 0 === d ? null : d;
    null !== d && (b2.callback = d);
    a2 = nh(e2, b2, g2);
    null !== a2 && (gi2(a2, e2, g2, f2), oh(a2, e2, g2));
    return g2;
  }
  function gl2(a2) {
    a2 = a2.current;
    if (!a2.child) return null;
    switch (a2.child.tag) {
      case 5:
        return a2.child.stateNode;
      default:
        return a2.child.stateNode;
    }
  }
  function hl2(a2, b2) {
    a2 = a2.memoizedState;
    if (null !== a2 && null !== a2.dehydrated) {
      var c = a2.retryLane;
      a2.retryLane = 0 !== c && c < b2 ? c : b2;
    }
  }
  function il2(a2, b2) {
    hl2(a2, b2);
    (a2 = a2.alternate) && hl2(a2, b2);
  }
  function jl2() {
    return null;
  }
  var kl2 = "function" === typeof reportError ? reportError : function(a2) {
    console.error(a2);
  };
  function ll2(a2) {
    this._internalRoot = a2;
  }
  ml2.prototype.render = ll2.prototype.render = function(a2) {
    var b2 = this._internalRoot;
    if (null === b2) throw Error(p2(409));
    fl2(a2, b2, null, null);
  };
  ml2.prototype.unmount = ll2.prototype.unmount = function() {
    var a2 = this._internalRoot;
    if (null !== a2) {
      this._internalRoot = null;
      var b2 = a2.containerInfo;
      Rk(function() {
        fl2(null, a2, null, null);
      });
      b2[uf2] = null;
    }
  };
  function ml2(a2) {
    this._internalRoot = a2;
  }
  ml2.prototype.unstable_scheduleHydration = function(a2) {
    if (a2) {
      var b2 = Hc2();
      a2 = { blockedOn: null, target: a2, priority: b2 };
      for (var c = 0; c < Qc2.length && 0 !== b2 && b2 < Qc2[c].priority; c++) ;
      Qc2.splice(c, 0, a2);
      0 === c && Vc2(a2);
    }
  };
  function nl2(a2) {
    return !(!a2 || 1 !== a2.nodeType && 9 !== a2.nodeType && 11 !== a2.nodeType);
  }
  function ol2(a2) {
    return !(!a2 || 1 !== a2.nodeType && 9 !== a2.nodeType && 11 !== a2.nodeType && (8 !== a2.nodeType || " react-mount-point-unstable " !== a2.nodeValue));
  }
  function pl2() {
  }
  function ql2(a2, b2, c, d, e2) {
    if (e2) {
      if ("function" === typeof d) {
        var f2 = d;
        d = function() {
          var a3 = gl2(g2);
          f2.call(a3);
        };
      }
      var g2 = el2(b2, d, a2, 0, null, false, false, "", pl2);
      a2._reactRootContainer = g2;
      a2[uf2] = g2.current;
      sf2(8 === a2.nodeType ? a2.parentNode : a2);
      Rk();
      return g2;
    }
    for (; e2 = a2.lastChild; ) a2.removeChild(e2);
    if ("function" === typeof d) {
      var h2 = d;
      d = function() {
        var a3 = gl2(k2);
        h2.call(a3);
      };
    }
    var k2 = bl2(a2, 0, false, null, null, false, false, "", pl2);
    a2._reactRootContainer = k2;
    a2[uf2] = k2.current;
    sf2(8 === a2.nodeType ? a2.parentNode : a2);
    Rk(function() {
      fl2(b2, k2, c, d);
    });
    return k2;
  }
  function rl2(a2, b2, c, d, e2) {
    var f2 = c._reactRootContainer;
    if (f2) {
      var g2 = f2;
      if ("function" === typeof e2) {
        var h2 = e2;
        e2 = function() {
          var a3 = gl2(g2);
          h2.call(a3);
        };
      }
      fl2(b2, g2, a2, e2);
    } else g2 = ql2(c, b2, a2, e2, d);
    return gl2(g2);
  }
  Ec2 = function(a2) {
    switch (a2.tag) {
      case 3:
        var b2 = a2.stateNode;
        if (b2.current.memoizedState.isDehydrated) {
          var c = tc2(b2.pendingLanes);
          0 !== c && (Cc2(b2, c | 1), Dk(b2, B2()), 0 === (K2 & 6) && (Gj = B2() + 500, jg()));
        }
        break;
      case 13:
        Rk(function() {
          var b3 = ih(a2, 1);
          if (null !== b3) {
            var c2 = R();
            gi2(b3, a2, 1, c2);
          }
        }), il2(a2, 1);
    }
  };
  Fc2 = function(a2) {
    if (13 === a2.tag) {
      var b2 = ih(a2, 134217728);
      if (null !== b2) {
        var c = R();
        gi2(b2, a2, 134217728, c);
      }
      il2(a2, 134217728);
    }
  };
  Gc2 = function(a2) {
    if (13 === a2.tag) {
      var b2 = yi2(a2), c = ih(a2, b2);
      if (null !== c) {
        var d = R();
        gi2(c, a2, b2, d);
      }
      il2(a2, b2);
    }
  };
  Hc2 = function() {
    return C;
  };
  Ic = function(a2, b2) {
    var c = C;
    try {
      return C = a2, b2();
    } finally {
      C = c;
    }
  };
  yb = function(a2, b2, c) {
    switch (b2) {
      case "input":
        bb(a2, c);
        b2 = c.name;
        if ("radio" === c.type && null != b2) {
          for (c = a2; c.parentNode; ) c = c.parentNode;
          c = c.querySelectorAll("input[name=" + JSON.stringify("" + b2) + '][type="radio"]');
          for (b2 = 0; b2 < c.length; b2++) {
            var d = c[b2];
            if (d !== a2 && d.form === a2.form) {
              var e2 = Db(d);
              if (!e2) throw Error(p2(90));
              Wa2(d);
              bb(d, e2);
            }
          }
        }
        break;
      case "textarea":
        ib(a2, c);
        break;
      case "select":
        b2 = c.value, null != b2 && fb(a2, !!c.multiple, b2, false);
    }
  };
  Gb = Qk;
  Hb = Rk;
  var sl2 = { usingClientEntryPoint: false, Events: [Cb, ue2, Db, Eb, Fb, Qk] }, tl2 = { findFiberByHostInstance: Wc2, bundleType: 0, version: "18.3.1", rendererPackageName: "react-dom" };
  var ul2 = { bundleType: tl2.bundleType, version: tl2.version, rendererPackageName: tl2.rendererPackageName, rendererConfig: tl2.rendererConfig, overrideHookState: null, overrideHookStateDeletePath: null, overrideHookStateRenamePath: null, overrideProps: null, overridePropsDeletePath: null, overridePropsRenamePath: null, setErrorHandler: null, setSuspenseHandler: null, scheduleUpdate: null, currentDispatcherRef: ua2.ReactCurrentDispatcher, findHostInstanceByFiber: function(a2) {
    a2 = Zb(a2);
    return null === a2 ? null : a2.stateNode;
  }, findFiberByHostInstance: tl2.findFiberByHostInstance || jl2, findHostInstancesForRefresh: null, scheduleRefresh: null, scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null, reconcilerVersion: "18.3.1-next-f1338f8080-20240426" };
  if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) {
    var vl2 = __REACT_DEVTOOLS_GLOBAL_HOOK__;
    if (!vl2.isDisabled && vl2.supportsFiber) try {
      kc = vl2.inject(ul2), lc = vl2;
    } catch (a2) {
    }
  }
  reactDom_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = sl2;
  reactDom_production_min.createPortal = function(a2, b2) {
    var c = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null;
    if (!nl2(b2)) throw Error(p2(200));
    return cl2(a2, b2, null, c);
  };
  reactDom_production_min.createRoot = function(a2, b2) {
    if (!nl2(a2)) throw Error(p2(299));
    var c = false, d = "", e2 = kl2;
    null !== b2 && void 0 !== b2 && (true === b2.unstable_strictMode && (c = true), void 0 !== b2.identifierPrefix && (d = b2.identifierPrefix), void 0 !== b2.onRecoverableError && (e2 = b2.onRecoverableError));
    b2 = bl2(a2, 1, false, null, null, c, false, d, e2);
    a2[uf2] = b2.current;
    sf2(8 === a2.nodeType ? a2.parentNode : a2);
    return new ll2(b2);
  };
  reactDom_production_min.findDOMNode = function(a2) {
    if (null == a2) return null;
    if (1 === a2.nodeType) return a2;
    var b2 = a2._reactInternals;
    if (void 0 === b2) {
      if ("function" === typeof a2.render) throw Error(p2(188));
      a2 = Object.keys(a2).join(",");
      throw Error(p2(268, a2));
    }
    a2 = Zb(b2);
    a2 = null === a2 ? null : a2.stateNode;
    return a2;
  };
  reactDom_production_min.flushSync = function(a2) {
    return Rk(a2);
  };
  reactDom_production_min.hydrate = function(a2, b2, c) {
    if (!ol2(b2)) throw Error(p2(200));
    return rl2(null, a2, b2, true, c);
  };
  reactDom_production_min.hydrateRoot = function(a2, b2, c) {
    if (!nl2(a2)) throw Error(p2(405));
    var d = null != c && c.hydratedSources || null, e2 = false, f2 = "", g2 = kl2;
    null !== c && void 0 !== c && (true === c.unstable_strictMode && (e2 = true), void 0 !== c.identifierPrefix && (f2 = c.identifierPrefix), void 0 !== c.onRecoverableError && (g2 = c.onRecoverableError));
    b2 = el2(b2, null, a2, 1, null != c ? c : null, e2, false, f2, g2);
    a2[uf2] = b2.current;
    sf2(a2);
    if (d) for (a2 = 0; a2 < d.length; a2++) c = d[a2], e2 = c._getVersion, e2 = e2(c._source), null == b2.mutableSourceEagerHydrationData ? b2.mutableSourceEagerHydrationData = [c, e2] : b2.mutableSourceEagerHydrationData.push(
      c,
      e2
    );
    return new ml2(b2);
  };
  reactDom_production_min.render = function(a2, b2, c) {
    if (!ol2(b2)) throw Error(p2(200));
    return rl2(null, a2, b2, false, c);
  };
  reactDom_production_min.unmountComponentAtNode = function(a2) {
    if (!ol2(a2)) throw Error(p2(40));
    return a2._reactRootContainer ? (Rk(function() {
      rl2(null, null, a2, false, function() {
        a2._reactRootContainer = null;
        a2[uf2] = null;
      });
    }), true) : false;
  };
  reactDom_production_min.unstable_batchedUpdates = Qk;
  reactDom_production_min.unstable_renderSubtreeIntoContainer = function(a2, b2, c, d) {
    if (!ol2(c)) throw Error(p2(200));
    if (null == a2 || void 0 === a2._reactInternals) throw Error(p2(38));
    return rl2(a2, b2, c, false, d);
  };
  reactDom_production_min.version = "18.3.1-next-f1338f8080-20240426";
  return reactDom_production_min;
}
var hasRequiredReactDom;
function requireReactDom() {
  if (hasRequiredReactDom) return reactDom.exports;
  hasRequiredReactDom = 1;
  function checkDCE() {
    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== "function") {
      return;
    }
    try {
      __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
    } catch (err) {
      console.error(err);
    }
  }
  {
    checkDCE();
    reactDom.exports = requireReactDom_production_min();
  }
  return reactDom.exports;
}
var hasRequiredClient;
function requireClient() {
  if (hasRequiredClient) return client;
  hasRequiredClient = 1;
  var m2 = requireReactDom();
  {
    client.createRoot = m2.createRoot;
    client.hydrateRoot = m2.hydrateRoot;
  }
  return client;
}
var clientExports = requireClient();
const TOAST_LIMIT = 1;
const TOAST_REMOVE_DELAY = 1e6;
let count$2 = 0;
function genId() {
  count$2 = (count$2 + 1) % Number.MAX_SAFE_INTEGER;
  return count$2.toString();
}
const toastTimeouts = /* @__PURE__ */ new Map();
const addToRemoveQueue = (toastId) => {
  if (toastTimeouts.has(toastId)) {
    return;
  }
  const timeout = setTimeout(() => {
    toastTimeouts.delete(toastId);
    dispatch({
      type: "REMOVE_TOAST",
      toastId
    });
  }, TOAST_REMOVE_DELAY);
  toastTimeouts.set(toastId, timeout);
};
const reducer = (state, action) => {
  switch (action.type) {
    case "ADD_TOAST":
      return {
        ...state,
        toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT)
      };
    case "UPDATE_TOAST":
      return {
        ...state,
        toasts: state.toasts.map(
          (t2) => t2.id === action.toast.id ? { ...t2, ...action.toast } : t2
        )
      };
    case "DISMISS_TOAST": {
      const { toastId } = action;
      if (toastId) {
        addToRemoveQueue(toastId);
      } else {
        state.toasts.forEach((toast2) => {
          addToRemoveQueue(toast2.id);
        });
      }
      return {
        ...state,
        toasts: state.toasts.map(
          (t2) => t2.id === toastId || toastId === void 0 ? {
            ...t2,
            open: false
          } : t2
        )
      };
    }
    case "REMOVE_TOAST":
      if (action.toastId === void 0) {
        return {
          ...state,
          toasts: []
        };
      }
      return {
        ...state,
        toasts: state.toasts.filter((t2) => t2.id !== action.toastId)
      };
  }
};
const listeners = [];
let memoryState = { toasts: [] };
function dispatch(action) {
  memoryState = reducer(memoryState, action);
  listeners.forEach((listener) => {
    listener(memoryState);
  });
}
function toast({ ...props }) {
  const id2 = genId();
  const update = (props2) => dispatch({
    type: "UPDATE_TOAST",
    toast: { ...props2, id: id2 }
  });
  const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id2 });
  dispatch({
    type: "ADD_TOAST",
    toast: {
      ...props,
      id: id2,
      open: true,
      onOpenChange: (open) => {
        if (!open) dismiss();
      }
    }
  });
  return {
    id: id2,
    dismiss,
    update
  };
}
function useToast() {
  const [state, setState] = reactExports.useState(memoryState);
  reactExports.useEffect(() => {
    listeners.push(setState);
    return () => {
      const index2 = listeners.indexOf(setState);
      if (index2 > -1) {
        listeners.splice(index2, 1);
      }
    };
  }, [state]);
  return {
    ...state,
    toast,
    dismiss: (toastId) => dispatch({ type: "DISMISS_TOAST", toastId })
  };
}
var reactDomExports = requireReactDom();
const ReactDOM = /* @__PURE__ */ getDefaultExportFromCjs(reactDomExports);
function composeEventHandlers(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
  return function handleEvent(event) {
    originalEventHandler?.(event);
    if (checkForDefaultPrevented === false || !event.defaultPrevented) {
      return ourEventHandler?.(event);
    }
  };
}
function setRef(ref2, value) {
  if (typeof ref2 === "function") {
    return ref2(value);
  } else if (ref2 !== null && ref2 !== void 0) {
    ref2.current = value;
  }
}
function composeRefs(...refs) {
  return (node) => {
    let hasCleanup = false;
    const cleanups = refs.map((ref2) => {
      const cleanup = setRef(ref2, node);
      if (!hasCleanup && typeof cleanup == "function") {
        hasCleanup = true;
      }
      return cleanup;
    });
    if (hasCleanup) {
      return () => {
        for (let i2 = 0; i2 < cleanups.length; i2++) {
          const cleanup = cleanups[i2];
          if (typeof cleanup == "function") {
            cleanup();
          } else {
            setRef(refs[i2], null);
          }
        }
      };
    }
  };
}
function useComposedRefs(...refs) {
  return reactExports.useCallback(composeRefs(...refs), refs);
}
function createContext2(rootComponentName, defaultContext) {
  const Context = reactExports.createContext(defaultContext);
  const Provider2 = (props) => {
    const { children, ...context } = props;
    const value = reactExports.useMemo(() => context, Object.values(context));
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Context.Provider, { value, children });
  };
  Provider2.displayName = rootComponentName + "Provider";
  function useContext2(consumerName) {
    const context = reactExports.useContext(Context);
    if (context) return context;
    if (defaultContext !== void 0) return defaultContext;
    throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
  }
  return [Provider2, useContext2];
}
function createContextScope(scopeName, createContextScopeDeps = []) {
  let defaultContexts = [];
  function createContext3(rootComponentName, defaultContext) {
    const BaseContext = reactExports.createContext(defaultContext);
    const index2 = defaultContexts.length;
    defaultContexts = [...defaultContexts, defaultContext];
    const Provider2 = (props) => {
      const { scope: scope2, children, ...context } = props;
      const Context = scope2?.[scopeName]?.[index2] || BaseContext;
      const value = reactExports.useMemo(() => context, Object.values(context));
      return /* @__PURE__ */ jsxRuntimeExports.jsx(Context.Provider, { value, children });
    };
    Provider2.displayName = rootComponentName + "Provider";
    function useContext2(consumerName, scope2) {
      const Context = scope2?.[scopeName]?.[index2] || BaseContext;
      const context = reactExports.useContext(Context);
      if (context) return context;
      if (defaultContext !== void 0) return defaultContext;
      throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
    }
    return [Provider2, useContext2];
  }
  const createScope = () => {
    const scopeContexts = defaultContexts.map((defaultContext) => {
      return reactExports.createContext(defaultContext);
    });
    return function useScope(scope2) {
      const contexts = scope2?.[scopeName] || scopeContexts;
      return reactExports.useMemo(
        () => ({ [`__scope${scopeName}`]: { ...scope2, [scopeName]: contexts } }),
        [scope2, contexts]
      );
    };
  };
  createScope.scopeName = scopeName;
  return [createContext3, composeContextScopes(createScope, ...createContextScopeDeps)];
}
function composeContextScopes(...scopes) {
  const baseScope = scopes[0];
  if (scopes.length === 1) return baseScope;
  const createScope = () => {
    const scopeHooks = scopes.map((createScope2) => ({
      useScope: createScope2(),
      scopeName: createScope2.scopeName
    }));
    return function useComposedScopes(overrideScopes) {
      const nextScopes = scopeHooks.reduce((nextScopes2, { useScope, scopeName }) => {
        const scopeProps = useScope(overrideScopes);
        const currentScope = scopeProps[`__scope${scopeName}`];
        return { ...nextScopes2, ...currentScope };
      }, {});
      return reactExports.useMemo(() => ({ [`__scope${baseScope.scopeName}`]: nextScopes }), [nextScopes]);
    };
  };
  createScope.scopeName = baseScope.scopeName;
  return createScope;
}
// @__NO_SIDE_EFFECTS__
function createSlot$5(ownerName) {
  const SlotClone = /* @__PURE__ */ createSlotClone$5(ownerName);
  const Slot2 = reactExports.forwardRef((props, forwardedRef) => {
    const { children, ...slotProps } = props;
    const childrenArray = reactExports.Children.toArray(children);
    const slottable = childrenArray.find(isSlottable$5);
    if (slottable) {
      const newElement = slottable.props.children;
      const newChildren = childrenArray.map((child) => {
        if (child === slottable) {
          if (reactExports.Children.count(newElement) > 1) return reactExports.Children.only(null);
          return reactExports.isValidElement(newElement) ? newElement.props.children : null;
        } else {
          return child;
        }
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children: reactExports.isValidElement(newElement) ? reactExports.cloneElement(newElement, void 0, newChildren) : null });
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children });
  });
  Slot2.displayName = `${ownerName}.Slot`;
  return Slot2;
}
// @__NO_SIDE_EFFECTS__
function createSlotClone$5(ownerName) {
  const SlotClone = reactExports.forwardRef((props, forwardedRef) => {
    const { children, ...slotProps } = props;
    if (reactExports.isValidElement(children)) {
      const childrenRef = getElementRef$6(children);
      const props2 = mergeProps$5(slotProps, children.props);
      if (children.type !== reactExports.Fragment) {
        props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;
      }
      return reactExports.cloneElement(children, props2);
    }
    return reactExports.Children.count(children) > 1 ? reactExports.Children.only(null) : null;
  });
  SlotClone.displayName = `${ownerName}.SlotClone`;
  return SlotClone;
}
var SLOTTABLE_IDENTIFIER$6 = /* @__PURE__ */ Symbol("radix.slottable");
function isSlottable$5(child) {
  return reactExports.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER$6;
}
function mergeProps$5(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          const result = childPropValue(...args);
          slotPropValue(...args);
          return result;
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef$6(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}
function createCollection(name2) {
  const PROVIDER_NAME2 = name2 + "CollectionProvider";
  const [createCollectionContext, createCollectionScope2] = createContextScope(PROVIDER_NAME2);
  const [CollectionProviderImpl, useCollectionContext] = createCollectionContext(
    PROVIDER_NAME2,
    { collectionRef: { current: null }, itemMap: /* @__PURE__ */ new Map() }
  );
  const CollectionProvider = (props) => {
    const { scope: scope2, children } = props;
    const ref2 = React.useRef(null);
    const itemMap = React.useRef(/* @__PURE__ */ new Map()).current;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(CollectionProviderImpl, { scope: scope2, itemMap, collectionRef: ref2, children });
  };
  CollectionProvider.displayName = PROVIDER_NAME2;
  const COLLECTION_SLOT_NAME = name2 + "CollectionSlot";
  const CollectionSlotImpl = /* @__PURE__ */ createSlot$5(COLLECTION_SLOT_NAME);
  const CollectionSlot = React.forwardRef(
    (props, forwardedRef) => {
      const { scope: scope2, children } = props;
      const context = useCollectionContext(COLLECTION_SLOT_NAME, scope2);
      const composedRefs = useComposedRefs(forwardedRef, context.collectionRef);
      return /* @__PURE__ */ jsxRuntimeExports.jsx(CollectionSlotImpl, { ref: composedRefs, children });
    }
  );
  CollectionSlot.displayName = COLLECTION_SLOT_NAME;
  const ITEM_SLOT_NAME = name2 + "CollectionItemSlot";
  const ITEM_DATA_ATTR = "data-radix-collection-item";
  const CollectionItemSlotImpl = /* @__PURE__ */ createSlot$5(ITEM_SLOT_NAME);
  const CollectionItemSlot = React.forwardRef(
    (props, forwardedRef) => {
      const { scope: scope2, children, ...itemData } = props;
      const ref2 = React.useRef(null);
      const composedRefs = useComposedRefs(forwardedRef, ref2);
      const context = useCollectionContext(ITEM_SLOT_NAME, scope2);
      React.useEffect(() => {
        context.itemMap.set(ref2, { ref: ref2, ...itemData });
        return () => void context.itemMap.delete(ref2);
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsx(CollectionItemSlotImpl, { ...{ [ITEM_DATA_ATTR]: "" }, ref: composedRefs, children });
    }
  );
  CollectionItemSlot.displayName = ITEM_SLOT_NAME;
  function useCollection2(scope2) {
    const context = useCollectionContext(name2 + "CollectionConsumer", scope2);
    const getItems = React.useCallback(() => {
      const collectionNode = context.collectionRef.current;
      if (!collectionNode) return [];
      const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`));
      const items2 = Array.from(context.itemMap.values());
      const orderedItems = items2.sort(
        (a2, b2) => orderedNodes.indexOf(a2.ref.current) - orderedNodes.indexOf(b2.ref.current)
      );
      return orderedItems;
    }, [context.collectionRef, context.itemMap]);
    return getItems;
  }
  return [
    { Provider: CollectionProvider, Slot: CollectionSlot, ItemSlot: CollectionItemSlot },
    useCollection2,
    createCollectionScope2
  ];
}
// @__NO_SIDE_EFFECTS__
function createSlot$4(ownerName) {
  const SlotClone = /* @__PURE__ */ createSlotClone$4(ownerName);
  const Slot2 = reactExports.forwardRef((props, forwardedRef) => {
    const { children, ...slotProps } = props;
    const childrenArray = reactExports.Children.toArray(children);
    const slottable = childrenArray.find(isSlottable$4);
    if (slottable) {
      const newElement = slottable.props.children;
      const newChildren = childrenArray.map((child) => {
        if (child === slottable) {
          if (reactExports.Children.count(newElement) > 1) return reactExports.Children.only(null);
          return reactExports.isValidElement(newElement) ? newElement.props.children : null;
        } else {
          return child;
        }
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children: reactExports.isValidElement(newElement) ? reactExports.cloneElement(newElement, void 0, newChildren) : null });
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children });
  });
  Slot2.displayName = `${ownerName}.Slot`;
  return Slot2;
}
// @__NO_SIDE_EFFECTS__
function createSlotClone$4(ownerName) {
  const SlotClone = reactExports.forwardRef((props, forwardedRef) => {
    const { children, ...slotProps } = props;
    if (reactExports.isValidElement(children)) {
      const childrenRef = getElementRef$5(children);
      const props2 = mergeProps$4(slotProps, children.props);
      if (children.type !== reactExports.Fragment) {
        props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;
      }
      return reactExports.cloneElement(children, props2);
    }
    return reactExports.Children.count(children) > 1 ? reactExports.Children.only(null) : null;
  });
  SlotClone.displayName = `${ownerName}.SlotClone`;
  return SlotClone;
}
var SLOTTABLE_IDENTIFIER$5 = /* @__PURE__ */ Symbol("radix.slottable");
function isSlottable$4(child) {
  return reactExports.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER$5;
}
function mergeProps$4(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          const result = childPropValue(...args);
          slotPropValue(...args);
          return result;
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef$5(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}
var NODES$1 = [
  "a",
  "button",
  "div",
  "form",
  "h2",
  "h3",
  "img",
  "input",
  "label",
  "li",
  "nav",
  "ol",
  "p",
  "select",
  "span",
  "svg",
  "ul"
];
var Primitive$1 = NODES$1.reduce((primitive, node) => {
  const Slot2 = /* @__PURE__ */ createSlot$4(`Primitive.${node}`);
  const Node2 = reactExports.forwardRef((props, forwardedRef) => {
    const { asChild, ...primitiveProps } = props;
    const Comp = asChild ? Slot2 : node;
    if (typeof window !== "undefined") {
      window[/* @__PURE__ */ Symbol.for("radix-ui")] = true;
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Comp, { ...primitiveProps, ref: forwardedRef });
  });
  Node2.displayName = `Primitive.${node}`;
  return { ...primitive, [node]: Node2 };
}, {});
function dispatchDiscreteCustomEvent(target, event) {
  if (target) reactDomExports.flushSync(() => target.dispatchEvent(event));
}
function useCallbackRef$1(callback) {
  const callbackRef = reactExports.useRef(callback);
  reactExports.useEffect(() => {
    callbackRef.current = callback;
  });
  return reactExports.useMemo(() => (...args) => callbackRef.current?.(...args), []);
}
function useEscapeKeydown(onEscapeKeyDownProp, ownerDocument = globalThis?.document) {
  const onEscapeKeyDown = useCallbackRef$1(onEscapeKeyDownProp);
  reactExports.useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === "Escape") {
        onEscapeKeyDown(event);
      }
    };
    ownerDocument.addEventListener("keydown", handleKeyDown, { capture: true });
    return () => ownerDocument.removeEventListener("keydown", handleKeyDown, { capture: true });
  }, [onEscapeKeyDown, ownerDocument]);
}
var DISMISSABLE_LAYER_NAME = "DismissableLayer";
var CONTEXT_UPDATE = "dismissableLayer.update";
var POINTER_DOWN_OUTSIDE = "dismissableLayer.pointerDownOutside";
var FOCUS_OUTSIDE = "dismissableLayer.focusOutside";
var originalBodyPointerEvents;
var DismissableLayerContext = reactExports.createContext({
  layers: /* @__PURE__ */ new Set(),
  layersWithOutsidePointerEventsDisabled: /* @__PURE__ */ new Set(),
  branches: /* @__PURE__ */ new Set()
});
var DismissableLayer = reactExports.forwardRef(
  (props, forwardedRef) => {
    const {
      disableOutsidePointerEvents = false,
      onEscapeKeyDown,
      onPointerDownOutside,
      onFocusOutside,
      onInteractOutside,
      onDismiss,
      ...layerProps
    } = props;
    const context = reactExports.useContext(DismissableLayerContext);
    const [node, setNode] = reactExports.useState(null);
    const ownerDocument = node?.ownerDocument ?? globalThis?.document;
    const [, force] = reactExports.useState({});
    const composedRefs = useComposedRefs(forwardedRef, (node2) => setNode(node2));
    const layers = Array.from(context.layers);
    const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1);
    const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled);
    const index2 = node ? layers.indexOf(node) : -1;
    const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0;
    const isPointerEventsEnabled = index2 >= highestLayerWithOutsidePointerEventsDisabledIndex;
    const pointerDownOutside = usePointerDownOutside((event) => {
      const target = event.target;
      const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target));
      if (!isPointerEventsEnabled || isPointerDownOnBranch) return;
      onPointerDownOutside?.(event);
      onInteractOutside?.(event);
      if (!event.defaultPrevented) onDismiss?.();
    }, ownerDocument);
    const focusOutside = useFocusOutside((event) => {
      const target = event.target;
      const isFocusInBranch = [...context.branches].some((branch) => branch.contains(target));
      if (isFocusInBranch) return;
      onFocusOutside?.(event);
      onInteractOutside?.(event);
      if (!event.defaultPrevented) onDismiss?.();
    }, ownerDocument);
    useEscapeKeydown((event) => {
      const isHighestLayer = index2 === context.layers.size - 1;
      if (!isHighestLayer) return;
      onEscapeKeyDown?.(event);
      if (!event.defaultPrevented && onDismiss) {
        event.preventDefault();
        onDismiss();
      }
    }, ownerDocument);
    reactExports.useEffect(() => {
      if (!node) return;
      if (disableOutsidePointerEvents) {
        if (context.layersWithOutsidePointerEventsDisabled.size === 0) {
          originalBodyPointerEvents = ownerDocument.body.style.pointerEvents;
          ownerDocument.body.style.pointerEvents = "none";
        }
        context.layersWithOutsidePointerEventsDisabled.add(node);
      }
      context.layers.add(node);
      dispatchUpdate();
      return () => {
        if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) {
          ownerDocument.body.style.pointerEvents = originalBodyPointerEvents;
        }
      };
    }, [node, ownerDocument, disableOutsidePointerEvents, context]);
    reactExports.useEffect(() => {
      return () => {
        if (!node) return;
        context.layers.delete(node);
        context.layersWithOutsidePointerEventsDisabled.delete(node);
        dispatchUpdate();
      };
    }, [node, context]);
    reactExports.useEffect(() => {
      const handleUpdate = () => force({});
      document.addEventListener(CONTEXT_UPDATE, handleUpdate);
      return () => document.removeEventListener(CONTEXT_UPDATE, handleUpdate);
    }, []);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.div,
      {
        ...layerProps,
        ref: composedRefs,
        style: {
          pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? "auto" : "none" : void 0,
          ...props.style
        },
        onFocusCapture: composeEventHandlers(props.onFocusCapture, focusOutside.onFocusCapture),
        onBlurCapture: composeEventHandlers(props.onBlurCapture, focusOutside.onBlurCapture),
        onPointerDownCapture: composeEventHandlers(
          props.onPointerDownCapture,
          pointerDownOutside.onPointerDownCapture
        )
      }
    );
  }
);
DismissableLayer.displayName = DISMISSABLE_LAYER_NAME;
var BRANCH_NAME = "DismissableLayerBranch";
var DismissableLayerBranch = reactExports.forwardRef((props, forwardedRef) => {
  const context = reactExports.useContext(DismissableLayerContext);
  const ref2 = reactExports.useRef(null);
  const composedRefs = useComposedRefs(forwardedRef, ref2);
  reactExports.useEffect(() => {
    const node = ref2.current;
    if (node) {
      context.branches.add(node);
      return () => {
        context.branches.delete(node);
      };
    }
  }, [context.branches]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.div, { ...props, ref: composedRefs });
});
DismissableLayerBranch.displayName = BRANCH_NAME;
function usePointerDownOutside(onPointerDownOutside, ownerDocument = globalThis?.document) {
  const handlePointerDownOutside = useCallbackRef$1(onPointerDownOutside);
  const isPointerInsideReactTreeRef = reactExports.useRef(false);
  const handleClickRef = reactExports.useRef(() => {
  });
  reactExports.useEffect(() => {
    const handlePointerDown = (event) => {
      if (event.target && !isPointerInsideReactTreeRef.current) {
        let handleAndDispatchPointerDownOutsideEvent2 = function() {
          handleAndDispatchCustomEvent$1(
            POINTER_DOWN_OUTSIDE,
            handlePointerDownOutside,
            eventDetail,
            { discrete: true }
          );
        };
        const eventDetail = { originalEvent: event };
        if (event.pointerType === "touch") {
          ownerDocument.removeEventListener("click", handleClickRef.current);
          handleClickRef.current = handleAndDispatchPointerDownOutsideEvent2;
          ownerDocument.addEventListener("click", handleClickRef.current, { once: true });
        } else {
          handleAndDispatchPointerDownOutsideEvent2();
        }
      } else {
        ownerDocument.removeEventListener("click", handleClickRef.current);
      }
      isPointerInsideReactTreeRef.current = false;
    };
    const timerId = window.setTimeout(() => {
      ownerDocument.addEventListener("pointerdown", handlePointerDown);
    }, 0);
    return () => {
      window.clearTimeout(timerId);
      ownerDocument.removeEventListener("pointerdown", handlePointerDown);
      ownerDocument.removeEventListener("click", handleClickRef.current);
    };
  }, [ownerDocument, handlePointerDownOutside]);
  return {
    // ensures we check React component tree (not just DOM tree)
    onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true
  };
}
function useFocusOutside(onFocusOutside, ownerDocument = globalThis?.document) {
  const handleFocusOutside = useCallbackRef$1(onFocusOutside);
  const isFocusInsideReactTreeRef = reactExports.useRef(false);
  reactExports.useEffect(() => {
    const handleFocus = (event) => {
      if (event.target && !isFocusInsideReactTreeRef.current) {
        const eventDetail = { originalEvent: event };
        handleAndDispatchCustomEvent$1(FOCUS_OUTSIDE, handleFocusOutside, eventDetail, {
          discrete: false
        });
      }
    };
    ownerDocument.addEventListener("focusin", handleFocus);
    return () => ownerDocument.removeEventListener("focusin", handleFocus);
  }, [ownerDocument, handleFocusOutside]);
  return {
    onFocusCapture: () => isFocusInsideReactTreeRef.current = true,
    onBlurCapture: () => isFocusInsideReactTreeRef.current = false
  };
}
function dispatchUpdate() {
  const event = new CustomEvent(CONTEXT_UPDATE);
  document.dispatchEvent(event);
}
function handleAndDispatchCustomEvent$1(name2, handler, detail, { discrete }) {
  const target = detail.originalEvent.target;
  const event = new CustomEvent(name2, { bubbles: false, cancelable: true, detail });
  if (handler) target.addEventListener(name2, handler, { once: true });
  if (discrete) {
    dispatchDiscreteCustomEvent(target, event);
  } else {
    target.dispatchEvent(event);
  }
}
var Root$6 = DismissableLayer;
var Branch = DismissableLayerBranch;
var useLayoutEffect2 = globalThis?.document ? reactExports.useLayoutEffect : () => {
};
var PORTAL_NAME$4 = "Portal";
var Portal$3 = reactExports.forwardRef((props, forwardedRef) => {
  const { container: containerProp, ...portalProps } = props;
  const [mounted, setMounted] = reactExports.useState(false);
  useLayoutEffect2(() => setMounted(true), []);
  const container = containerProp || mounted && globalThis?.document?.body;
  return container ? ReactDOM.createPortal(/* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.div, { ...portalProps, ref: forwardedRef }), container) : null;
});
Portal$3.displayName = PORTAL_NAME$4;
function useStateMachine(initialState, machine) {
  return reactExports.useReducer((state, event) => {
    const nextState = machine[state][event];
    return nextState ?? state;
  }, initialState);
}
var Presence = (props) => {
  const { present, children } = props;
  const presence = usePresence(present);
  const child = typeof children === "function" ? children({ present: presence.isPresent }) : reactExports.Children.only(children);
  const ref2 = useComposedRefs(presence.ref, getElementRef$4(child));
  const forceMount = typeof children === "function";
  return forceMount || presence.isPresent ? reactExports.cloneElement(child, { ref: ref2 }) : null;
};
Presence.displayName = "Presence";
function usePresence(present) {
  const [node, setNode] = reactExports.useState();
  const stylesRef = reactExports.useRef(null);
  const prevPresentRef = reactExports.useRef(present);
  const prevAnimationNameRef = reactExports.useRef("none");
  const initialState = present ? "mounted" : "unmounted";
  const [state, send] = useStateMachine(initialState, {
    mounted: {
      UNMOUNT: "unmounted",
      ANIMATION_OUT: "unmountSuspended"
    },
    unmountSuspended: {
      MOUNT: "mounted",
      ANIMATION_END: "unmounted"
    },
    unmounted: {
      MOUNT: "mounted"
    }
  });
  reactExports.useEffect(() => {
    const currentAnimationName = getAnimationName(stylesRef.current);
    prevAnimationNameRef.current = state === "mounted" ? currentAnimationName : "none";
  }, [state]);
  useLayoutEffect2(() => {
    const styles = stylesRef.current;
    const wasPresent = prevPresentRef.current;
    const hasPresentChanged = wasPresent !== present;
    if (hasPresentChanged) {
      const prevAnimationName = prevAnimationNameRef.current;
      const currentAnimationName = getAnimationName(styles);
      if (present) {
        send("MOUNT");
      } else if (currentAnimationName === "none" || styles?.display === "none") {
        send("UNMOUNT");
      } else {
        const isAnimating = prevAnimationName !== currentAnimationName;
        if (wasPresent && isAnimating) {
          send("ANIMATION_OUT");
        } else {
          send("UNMOUNT");
        }
      }
      prevPresentRef.current = present;
    }
  }, [present, send]);
  useLayoutEffect2(() => {
    if (node) {
      let timeoutId;
      const ownerWindow = node.ownerDocument.defaultView ?? window;
      const handleAnimationEnd = (event) => {
        const currentAnimationName = getAnimationName(stylesRef.current);
        const isCurrentAnimation = currentAnimationName.includes(CSS.escape(event.animationName));
        if (event.target === node && isCurrentAnimation) {
          send("ANIMATION_END");
          if (!prevPresentRef.current) {
            const currentFillMode = node.style.animationFillMode;
            node.style.animationFillMode = "forwards";
            timeoutId = ownerWindow.setTimeout(() => {
              if (node.style.animationFillMode === "forwards") {
                node.style.animationFillMode = currentFillMode;
              }
            });
          }
        }
      };
      const handleAnimationStart = (event) => {
        if (event.target === node) {
          prevAnimationNameRef.current = getAnimationName(stylesRef.current);
        }
      };
      node.addEventListener("animationstart", handleAnimationStart);
      node.addEventListener("animationcancel", handleAnimationEnd);
      node.addEventListener("animationend", handleAnimationEnd);
      return () => {
        ownerWindow.clearTimeout(timeoutId);
        node.removeEventListener("animationstart", handleAnimationStart);
        node.removeEventListener("animationcancel", handleAnimationEnd);
        node.removeEventListener("animationend", handleAnimationEnd);
      };
    } else {
      send("ANIMATION_END");
    }
  }, [node, send]);
  return {
    isPresent: ["mounted", "unmountSuspended"].includes(state),
    ref: reactExports.useCallback((node2) => {
      stylesRef.current = node2 ? getComputedStyle(node2) : null;
      setNode(node2);
    }, [])
  };
}
function getAnimationName(styles) {
  return styles?.animationName || "none";
}
function getElementRef$4(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}
var useInsertionEffect = React$1[" useInsertionEffect ".trim().toString()] || useLayoutEffect2;
function useControllableState({
  prop,
  defaultProp,
  onChange = () => {
  },
  caller
}) {
  const [uncontrolledProp, setUncontrolledProp, onChangeRef] = useUncontrolledState({
    defaultProp,
    onChange
  });
  const isControlled = prop !== void 0;
  const value = isControlled ? prop : uncontrolledProp;
  {
    const isControlledRef = reactExports.useRef(prop !== void 0);
    reactExports.useEffect(() => {
      const wasControlled = isControlledRef.current;
      if (wasControlled !== isControlled) {
        const from = wasControlled ? "controlled" : "uncontrolled";
        const to2 = isControlled ? "controlled" : "uncontrolled";
        console.warn(
          `${caller} is changing from ${from} to ${to2}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`
        );
      }
      isControlledRef.current = isControlled;
    }, [isControlled, caller]);
  }
  const setValue = reactExports.useCallback(
    (nextValue) => {
      if (isControlled) {
        const value2 = isFunction$1(nextValue) ? nextValue(prop) : nextValue;
        if (value2 !== prop) {
          onChangeRef.current?.(value2);
        }
      } else {
        setUncontrolledProp(nextValue);
      }
    },
    [isControlled, prop, setUncontrolledProp, onChangeRef]
  );
  return [value, setValue];
}
function useUncontrolledState({
  defaultProp,
  onChange
}) {
  const [value, setValue] = reactExports.useState(defaultProp);
  const prevValueRef = reactExports.useRef(value);
  const onChangeRef = reactExports.useRef(onChange);
  useInsertionEffect(() => {
    onChangeRef.current = onChange;
  }, [onChange]);
  reactExports.useEffect(() => {
    if (prevValueRef.current !== value) {
      onChangeRef.current?.(value);
      prevValueRef.current = value;
    }
  }, [value, prevValueRef]);
  return [value, setValue, onChangeRef];
}
function isFunction$1(value) {
  return typeof value === "function";
}
var VISUALLY_HIDDEN_STYLES = Object.freeze({
  // See: https://github.com/twbs/bootstrap/blob/main/scss/mixins/_visually-hidden.scss
  position: "absolute",
  border: 0,
  width: 1,
  height: 1,
  padding: 0,
  margin: -1,
  overflow: "hidden",
  clip: "rect(0, 0, 0, 0)",
  whiteSpace: "nowrap",
  wordWrap: "normal"
});
var NAME$2 = "VisuallyHidden";
var VisuallyHidden = reactExports.forwardRef(
  (props, forwardedRef) => {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.span,
      {
        ...props,
        ref: forwardedRef,
        style: { ...VISUALLY_HIDDEN_STYLES, ...props.style }
      }
    );
  }
);
VisuallyHidden.displayName = NAME$2;
var Root$5 = VisuallyHidden;
var PROVIDER_NAME$1 = "ToastProvider";
var [Collection$2, useCollection$2, createCollectionScope$2] = createCollection("Toast");
var [createToastContext] = createContextScope("Toast", [createCollectionScope$2]);
var [ToastProviderProvider, useToastProviderContext] = createToastContext(PROVIDER_NAME$1);
var ToastProvider$1 = (props) => {
  const {
    __scopeToast,
    label = "Notification",
    duration: duration2 = 5e3,
    swipeDirection = "right",
    swipeThreshold = 50,
    children
  } = props;
  const [viewport, setViewport] = reactExports.useState(null);
  const [toastCount, setToastCount] = reactExports.useState(0);
  const isFocusedToastEscapeKeyDownRef = reactExports.useRef(false);
  const isClosePausedRef = reactExports.useRef(false);
  if (!label.trim()) {
    console.error(
      `Invalid prop \`label\` supplied to \`${PROVIDER_NAME$1}\`. Expected non-empty \`string\`.`
    );
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Collection$2.Provider, { scope: __scopeToast, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
    ToastProviderProvider,
    {
      scope: __scopeToast,
      label,
      duration: duration2,
      swipeDirection,
      swipeThreshold,
      toastCount,
      viewport,
      onViewportChange: setViewport,
      onToastAdd: reactExports.useCallback(() => setToastCount((prevCount) => prevCount + 1), []),
      onToastRemove: reactExports.useCallback(() => setToastCount((prevCount) => prevCount - 1), []),
      isFocusedToastEscapeKeyDownRef,
      isClosePausedRef,
      children
    }
  ) });
};
ToastProvider$1.displayName = PROVIDER_NAME$1;
var VIEWPORT_NAME$1 = "ToastViewport";
var VIEWPORT_DEFAULT_HOTKEY = ["F8"];
var VIEWPORT_PAUSE = "toast.viewportPause";
var VIEWPORT_RESUME = "toast.viewportResume";
var ToastViewport$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeToast,
      hotkey = VIEWPORT_DEFAULT_HOTKEY,
      label = "Notifications ({hotkey})",
      ...viewportProps
    } = props;
    const context = useToastProviderContext(VIEWPORT_NAME$1, __scopeToast);
    const getItems = useCollection$2(__scopeToast);
    const wrapperRef = reactExports.useRef(null);
    const headFocusProxyRef = reactExports.useRef(null);
    const tailFocusProxyRef = reactExports.useRef(null);
    const ref2 = reactExports.useRef(null);
    const composedRefs = useComposedRefs(forwardedRef, ref2, context.onViewportChange);
    const hotkeyLabel = hotkey.join("+").replace(/Key/g, "").replace(/Digit/g, "");
    const hasToasts = context.toastCount > 0;
    reactExports.useEffect(() => {
      const handleKeyDown = (event) => {
        const isHotkeyPressed = hotkey.length !== 0 && hotkey.every((key) => event[key] || event.code === key);
        if (isHotkeyPressed) ref2.current?.focus();
      };
      document.addEventListener("keydown", handleKeyDown);
      return () => document.removeEventListener("keydown", handleKeyDown);
    }, [hotkey]);
    reactExports.useEffect(() => {
      const wrapper = wrapperRef.current;
      const viewport = ref2.current;
      if (hasToasts && wrapper && viewport) {
        const handlePause = () => {
          if (!context.isClosePausedRef.current) {
            const pauseEvent = new CustomEvent(VIEWPORT_PAUSE);
            viewport.dispatchEvent(pauseEvent);
            context.isClosePausedRef.current = true;
          }
        };
        const handleResume = () => {
          if (context.isClosePausedRef.current) {
            const resumeEvent = new CustomEvent(VIEWPORT_RESUME);
            viewport.dispatchEvent(resumeEvent);
            context.isClosePausedRef.current = false;
          }
        };
        const handleFocusOutResume = (event) => {
          const isFocusMovingOutside = !wrapper.contains(event.relatedTarget);
          if (isFocusMovingOutside) handleResume();
        };
        const handlePointerLeaveResume = () => {
          const isFocusInside = wrapper.contains(document.activeElement);
          if (!isFocusInside) handleResume();
        };
        wrapper.addEventListener("focusin", handlePause);
        wrapper.addEventListener("focusout", handleFocusOutResume);
        wrapper.addEventListener("pointermove", handlePause);
        wrapper.addEventListener("pointerleave", handlePointerLeaveResume);
        window.addEventListener("blur", handlePause);
        window.addEventListener("focus", handleResume);
        return () => {
          wrapper.removeEventListener("focusin", handlePause);
          wrapper.removeEventListener("focusout", handleFocusOutResume);
          wrapper.removeEventListener("pointermove", handlePause);
          wrapper.removeEventListener("pointerleave", handlePointerLeaveResume);
          window.removeEventListener("blur", handlePause);
          window.removeEventListener("focus", handleResume);
        };
      }
    }, [hasToasts, context.isClosePausedRef]);
    const getSortedTabbableCandidates = reactExports.useCallback(
      ({ tabbingDirection }) => {
        const toastItems = getItems();
        const tabbableCandidates = toastItems.map((toastItem) => {
          const toastNode = toastItem.ref.current;
          const toastTabbableCandidates = [toastNode, ...getTabbableCandidates$1(toastNode)];
          return tabbingDirection === "forwards" ? toastTabbableCandidates : toastTabbableCandidates.reverse();
        });
        return (tabbingDirection === "forwards" ? tabbableCandidates.reverse() : tabbableCandidates).flat();
      },
      [getItems]
    );
    reactExports.useEffect(() => {
      const viewport = ref2.current;
      if (viewport) {
        const handleKeyDown = (event) => {
          const isMetaKey = event.altKey || event.ctrlKey || event.metaKey;
          const isTabKey = event.key === "Tab" && !isMetaKey;
          if (isTabKey) {
            const focusedElement = document.activeElement;
            const isTabbingBackwards = event.shiftKey;
            const targetIsViewport = event.target === viewport;
            if (targetIsViewport && isTabbingBackwards) {
              headFocusProxyRef.current?.focus();
              return;
            }
            const tabbingDirection = isTabbingBackwards ? "backwards" : "forwards";
            const sortedCandidates = getSortedTabbableCandidates({ tabbingDirection });
            const index2 = sortedCandidates.findIndex((candidate) => candidate === focusedElement);
            if (focusFirst$2(sortedCandidates.slice(index2 + 1))) {
              event.preventDefault();
            } else {
              isTabbingBackwards ? headFocusProxyRef.current?.focus() : tailFocusProxyRef.current?.focus();
            }
          }
        };
        viewport.addEventListener("keydown", handleKeyDown);
        return () => viewport.removeEventListener("keydown", handleKeyDown);
      }
    }, [getItems, getSortedTabbableCandidates]);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Branch,
      {
        ref: wrapperRef,
        role: "region",
        "aria-label": label.replace("{hotkey}", hotkeyLabel),
        tabIndex: -1,
        style: { pointerEvents: hasToasts ? void 0 : "none" },
        children: [
          hasToasts && /* @__PURE__ */ jsxRuntimeExports.jsx(
            FocusProxy,
            {
              ref: headFocusProxyRef,
              onFocusFromOutsideViewport: () => {
                const tabbableCandidates = getSortedTabbableCandidates({
                  tabbingDirection: "forwards"
                });
                focusFirst$2(tabbableCandidates);
              }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Collection$2.Slot, { scope: __scopeToast, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.ol, { tabIndex: -1, ...viewportProps, ref: composedRefs }) }),
          hasToasts && /* @__PURE__ */ jsxRuntimeExports.jsx(
            FocusProxy,
            {
              ref: tailFocusProxyRef,
              onFocusFromOutsideViewport: () => {
                const tabbableCandidates = getSortedTabbableCandidates({
                  tabbingDirection: "backwards"
                });
                focusFirst$2(tabbableCandidates);
              }
            }
          )
        ]
      }
    );
  }
);
ToastViewport$1.displayName = VIEWPORT_NAME$1;
var FOCUS_PROXY_NAME = "ToastFocusProxy";
var FocusProxy = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeToast, onFocusFromOutsideViewport, ...proxyProps } = props;
    const context = useToastProviderContext(FOCUS_PROXY_NAME, __scopeToast);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      VisuallyHidden,
      {
        tabIndex: 0,
        ...proxyProps,
        ref: forwardedRef,
        style: { position: "fixed" },
        onFocus: (event) => {
          const prevFocusedElement = event.relatedTarget;
          const isFocusFromOutsideViewport = !context.viewport?.contains(prevFocusedElement);
          if (isFocusFromOutsideViewport) onFocusFromOutsideViewport();
        }
      }
    );
  }
);
FocusProxy.displayName = FOCUS_PROXY_NAME;
var TOAST_NAME = "Toast";
var TOAST_SWIPE_START = "toast.swipeStart";
var TOAST_SWIPE_MOVE = "toast.swipeMove";
var TOAST_SWIPE_CANCEL = "toast.swipeCancel";
var TOAST_SWIPE_END = "toast.swipeEnd";
var Toast$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { forceMount, open: openProp, defaultOpen, onOpenChange, ...toastProps } = props;
    const [open, setOpen] = useControllableState({
      prop: openProp,
      defaultProp: defaultOpen ?? true,
      onChange: onOpenChange,
      caller: TOAST_NAME
    });
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Presence, { present: forceMount || open, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      ToastImpl,
      {
        open,
        ...toastProps,
        ref: forwardedRef,
        onClose: () => setOpen(false),
        onPause: useCallbackRef$1(props.onPause),
        onResume: useCallbackRef$1(props.onResume),
        onSwipeStart: composeEventHandlers(props.onSwipeStart, (event) => {
          event.currentTarget.setAttribute("data-swipe", "start");
        }),
        onSwipeMove: composeEventHandlers(props.onSwipeMove, (event) => {
          const { x: x2, y } = event.detail.delta;
          event.currentTarget.setAttribute("data-swipe", "move");
          event.currentTarget.style.setProperty("--radix-toast-swipe-move-x", `${x2}px`);
          event.currentTarget.style.setProperty("--radix-toast-swipe-move-y", `${y}px`);
        }),
        onSwipeCancel: composeEventHandlers(props.onSwipeCancel, (event) => {
          event.currentTarget.setAttribute("data-swipe", "cancel");
          event.currentTarget.style.removeProperty("--radix-toast-swipe-move-x");
          event.currentTarget.style.removeProperty("--radix-toast-swipe-move-y");
          event.currentTarget.style.removeProperty("--radix-toast-swipe-end-x");
          event.currentTarget.style.removeProperty("--radix-toast-swipe-end-y");
        }),
        onSwipeEnd: composeEventHandlers(props.onSwipeEnd, (event) => {
          const { x: x2, y } = event.detail.delta;
          event.currentTarget.setAttribute("data-swipe", "end");
          event.currentTarget.style.removeProperty("--radix-toast-swipe-move-x");
          event.currentTarget.style.removeProperty("--radix-toast-swipe-move-y");
          event.currentTarget.style.setProperty("--radix-toast-swipe-end-x", `${x2}px`);
          event.currentTarget.style.setProperty("--radix-toast-swipe-end-y", `${y}px`);
          setOpen(false);
        })
      }
    ) });
  }
);
Toast$1.displayName = TOAST_NAME;
var [ToastInteractiveProvider, useToastInteractiveContext] = createToastContext(TOAST_NAME, {
  onClose() {
  }
});
var ToastImpl = reactExports.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeToast,
      type: type2 = "foreground",
      duration: durationProp,
      open,
      onClose,
      onEscapeKeyDown,
      onPause,
      onResume,
      onSwipeStart,
      onSwipeMove,
      onSwipeCancel,
      onSwipeEnd,
      ...toastProps
    } = props;
    const context = useToastProviderContext(TOAST_NAME, __scopeToast);
    const [node, setNode] = reactExports.useState(null);
    const composedRefs = useComposedRefs(forwardedRef, (node2) => setNode(node2));
    const pointerStartRef = reactExports.useRef(null);
    const swipeDeltaRef = reactExports.useRef(null);
    const duration2 = durationProp || context.duration;
    const closeTimerStartTimeRef = reactExports.useRef(0);
    const closeTimerRemainingTimeRef = reactExports.useRef(duration2);
    const closeTimerRef = reactExports.useRef(0);
    const { onToastAdd, onToastRemove } = context;
    const handleClose = useCallbackRef$1(() => {
      const isFocusInToast = node?.contains(document.activeElement);
      if (isFocusInToast) context.viewport?.focus();
      onClose();
    });
    const startTimer = reactExports.useCallback(
      (duration22) => {
        if (!duration22 || duration22 === Infinity) return;
        window.clearTimeout(closeTimerRef.current);
        closeTimerStartTimeRef.current = (/* @__PURE__ */ new Date()).getTime();
        closeTimerRef.current = window.setTimeout(handleClose, duration22);
      },
      [handleClose]
    );
    reactExports.useEffect(() => {
      const viewport = context.viewport;
      if (viewport) {
        const handleResume = () => {
          startTimer(closeTimerRemainingTimeRef.current);
          onResume?.();
        };
        const handlePause = () => {
          const elapsedTime = (/* @__PURE__ */ new Date()).getTime() - closeTimerStartTimeRef.current;
          closeTimerRemainingTimeRef.current = closeTimerRemainingTimeRef.current - elapsedTime;
          window.clearTimeout(closeTimerRef.current);
          onPause?.();
        };
        viewport.addEventListener(VIEWPORT_PAUSE, handlePause);
        viewport.addEventListener(VIEWPORT_RESUME, handleResume);
        return () => {
          viewport.removeEventListener(VIEWPORT_PAUSE, handlePause);
          viewport.removeEventListener(VIEWPORT_RESUME, handleResume);
        };
      }
    }, [context.viewport, duration2, onPause, onResume, startTimer]);
    reactExports.useEffect(() => {
      if (open && !context.isClosePausedRef.current) startTimer(duration2);
    }, [open, duration2, context.isClosePausedRef, startTimer]);
    reactExports.useEffect(() => {
      onToastAdd();
      return () => onToastRemove();
    }, [onToastAdd, onToastRemove]);
    const announceTextContent = reactExports.useMemo(() => {
      return node ? getAnnounceTextContent(node) : null;
    }, [node]);
    if (!context.viewport) return null;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      announceTextContent && /* @__PURE__ */ jsxRuntimeExports.jsx(
        ToastAnnounce,
        {
          __scopeToast,
          role: "status",
          "aria-live": type2 === "foreground" ? "assertive" : "polite",
          children: announceTextContent
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ToastInteractiveProvider, { scope: __scopeToast, onClose: handleClose, children: reactDomExports.createPortal(
        /* @__PURE__ */ jsxRuntimeExports.jsx(Collection$2.ItemSlot, { scope: __scopeToast, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Root$6,
          {
            asChild: true,
            onEscapeKeyDown: composeEventHandlers(onEscapeKeyDown, () => {
              if (!context.isFocusedToastEscapeKeyDownRef.current) handleClose();
              context.isFocusedToastEscapeKeyDownRef.current = false;
            }),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              Primitive$1.li,
              {
                tabIndex: 0,
                "data-state": open ? "open" : "closed",
                "data-swipe-direction": context.swipeDirection,
                ...toastProps,
                ref: composedRefs,
                style: { userSelect: "none", touchAction: "none", ...props.style },
                onKeyDown: composeEventHandlers(props.onKeyDown, (event) => {
                  if (event.key !== "Escape") return;
                  onEscapeKeyDown?.(event.nativeEvent);
                  if (!event.nativeEvent.defaultPrevented) {
                    context.isFocusedToastEscapeKeyDownRef.current = true;
                    handleClose();
                  }
                }),
                onPointerDown: composeEventHandlers(props.onPointerDown, (event) => {
                  if (event.button !== 0) return;
                  pointerStartRef.current = { x: event.clientX, y: event.clientY };
                }),
                onPointerMove: composeEventHandlers(props.onPointerMove, (event) => {
                  if (!pointerStartRef.current) return;
                  const x2 = event.clientX - pointerStartRef.current.x;
                  const y = event.clientY - pointerStartRef.current.y;
                  const hasSwipeMoveStarted = Boolean(swipeDeltaRef.current);
                  const isHorizontalSwipe = ["left", "right"].includes(context.swipeDirection);
                  const clamp2 = ["left", "up"].includes(context.swipeDirection) ? Math.min : Math.max;
                  const clampedX = isHorizontalSwipe ? clamp2(0, x2) : 0;
                  const clampedY = !isHorizontalSwipe ? clamp2(0, y) : 0;
                  const moveStartBuffer = event.pointerType === "touch" ? 10 : 2;
                  const delta = { x: clampedX, y: clampedY };
                  const eventDetail = { originalEvent: event, delta };
                  if (hasSwipeMoveStarted) {
                    swipeDeltaRef.current = delta;
                    handleAndDispatchCustomEvent(TOAST_SWIPE_MOVE, onSwipeMove, eventDetail, {
                      discrete: false
                    });
                  } else if (isDeltaInDirection(delta, context.swipeDirection, moveStartBuffer)) {
                    swipeDeltaRef.current = delta;
                    handleAndDispatchCustomEvent(TOAST_SWIPE_START, onSwipeStart, eventDetail, {
                      discrete: false
                    });
                    event.target.setPointerCapture(event.pointerId);
                  } else if (Math.abs(x2) > moveStartBuffer || Math.abs(y) > moveStartBuffer) {
                    pointerStartRef.current = null;
                  }
                }),
                onPointerUp: composeEventHandlers(props.onPointerUp, (event) => {
                  const delta = swipeDeltaRef.current;
                  const target = event.target;
                  if (target.hasPointerCapture(event.pointerId)) {
                    target.releasePointerCapture(event.pointerId);
                  }
                  swipeDeltaRef.current = null;
                  pointerStartRef.current = null;
                  if (delta) {
                    const toast2 = event.currentTarget;
                    const eventDetail = { originalEvent: event, delta };
                    if (isDeltaInDirection(delta, context.swipeDirection, context.swipeThreshold)) {
                      handleAndDispatchCustomEvent(TOAST_SWIPE_END, onSwipeEnd, eventDetail, {
                        discrete: true
                      });
                    } else {
                      handleAndDispatchCustomEvent(
                        TOAST_SWIPE_CANCEL,
                        onSwipeCancel,
                        eventDetail,
                        {
                          discrete: true
                        }
                      );
                    }
                    toast2.addEventListener("click", (event2) => event2.preventDefault(), {
                      once: true
                    });
                  }
                })
              }
            )
          }
        ) }),
        context.viewport
      ) })
    ] });
  }
);
var ToastAnnounce = (props) => {
  const { __scopeToast, children, ...announceProps } = props;
  const context = useToastProviderContext(TOAST_NAME, __scopeToast);
  const [renderAnnounceText, setRenderAnnounceText] = reactExports.useState(false);
  const [isAnnounced, setIsAnnounced] = reactExports.useState(false);
  useNextFrame(() => setRenderAnnounceText(true));
  reactExports.useEffect(() => {
    const timer = window.setTimeout(() => setIsAnnounced(true), 1e3);
    return () => window.clearTimeout(timer);
  }, []);
  return isAnnounced ? null : /* @__PURE__ */ jsxRuntimeExports.jsx(Portal$3, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(VisuallyHidden, { ...announceProps, children: renderAnnounceText && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    context.label,
    " ",
    children
  ] }) }) });
};
var TITLE_NAME$1 = "ToastTitle";
var ToastTitle$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeToast, ...titleProps } = props;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.div, { ...titleProps, ref: forwardedRef });
  }
);
ToastTitle$1.displayName = TITLE_NAME$1;
var DESCRIPTION_NAME$1 = "ToastDescription";
var ToastDescription$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeToast, ...descriptionProps } = props;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.div, { ...descriptionProps, ref: forwardedRef });
  }
);
ToastDescription$1.displayName = DESCRIPTION_NAME$1;
var ACTION_NAME = "ToastAction";
var ToastAction$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { altText, ...actionProps } = props;
    if (!altText.trim()) {
      console.error(
        `Invalid prop \`altText\` supplied to \`${ACTION_NAME}\`. Expected non-empty \`string\`.`
      );
      return null;
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(ToastAnnounceExclude, { altText, asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(ToastClose$1, { ...actionProps, ref: forwardedRef }) });
  }
);
ToastAction$1.displayName = ACTION_NAME;
var CLOSE_NAME$2 = "ToastClose";
var ToastClose$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeToast, ...closeProps } = props;
    const interactiveContext = useToastInteractiveContext(CLOSE_NAME$2, __scopeToast);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(ToastAnnounceExclude, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.button,
      {
        type: "button",
        ...closeProps,
        ref: forwardedRef,
        onClick: composeEventHandlers(props.onClick, interactiveContext.onClose)
      }
    ) });
  }
);
ToastClose$1.displayName = CLOSE_NAME$2;
var ToastAnnounceExclude = reactExports.forwardRef((props, forwardedRef) => {
  const { __scopeToast, altText, ...announceExcludeProps } = props;
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    Primitive$1.div,
    {
      "data-radix-toast-announce-exclude": "",
      "data-radix-toast-announce-alt": altText || void 0,
      ...announceExcludeProps,
      ref: forwardedRef
    }
  );
});
function getAnnounceTextContent(container) {
  const textContent = [];
  const childNodes = Array.from(container.childNodes);
  childNodes.forEach((node) => {
    if (node.nodeType === node.TEXT_NODE && node.textContent) textContent.push(node.textContent);
    if (isHTMLElement$1(node)) {
      const isHidden2 = node.ariaHidden || node.hidden || node.style.display === "none";
      const isExcluded = node.dataset.radixToastAnnounceExclude === "";
      if (!isHidden2) {
        if (isExcluded) {
          const altText = node.dataset.radixToastAnnounceAlt;
          if (altText) textContent.push(altText);
        } else {
          textContent.push(...getAnnounceTextContent(node));
        }
      }
    }
  });
  return textContent;
}
function handleAndDispatchCustomEvent(name2, handler, detail, { discrete }) {
  const currentTarget = detail.originalEvent.currentTarget;
  const event = new CustomEvent(name2, { bubbles: true, cancelable: true, detail });
  if (handler) currentTarget.addEventListener(name2, handler, { once: true });
  if (discrete) {
    dispatchDiscreteCustomEvent(currentTarget, event);
  } else {
    currentTarget.dispatchEvent(event);
  }
}
var isDeltaInDirection = (delta, direction, threshold = 0) => {
  const deltaX = Math.abs(delta.x);
  const deltaY = Math.abs(delta.y);
  const isDeltaX = deltaX > deltaY;
  if (direction === "left" || direction === "right") {
    return isDeltaX && deltaX > threshold;
  } else {
    return !isDeltaX && deltaY > threshold;
  }
};
function useNextFrame(callback = () => {
}) {
  const fn2 = useCallbackRef$1(callback);
  useLayoutEffect2(() => {
    let raf1 = 0;
    let raf2 = 0;
    raf1 = window.requestAnimationFrame(() => raf2 = window.requestAnimationFrame(fn2));
    return () => {
      window.cancelAnimationFrame(raf1);
      window.cancelAnimationFrame(raf2);
    };
  }, [fn2]);
}
function isHTMLElement$1(node) {
  return node.nodeType === node.ELEMENT_NODE;
}
function getTabbableCandidates$1(container) {
  const nodes = [];
  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
    acceptNode: (node) => {
      const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden";
      if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP;
      return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
    }
  });
  while (walker.nextNode()) nodes.push(walker.currentNode);
  return nodes;
}
function focusFirst$2(candidates) {
  const previouslyFocusedElement = document.activeElement;
  return candidates.some((candidate) => {
    if (candidate === previouslyFocusedElement) return true;
    candidate.focus();
    return document.activeElement !== previouslyFocusedElement;
  });
}
var Provider$1 = ToastProvider$1;
var Viewport$1 = ToastViewport$1;
var Root2$4 = Toast$1;
var Title$1 = ToastTitle$1;
var Description$1 = ToastDescription$1;
var Action = ToastAction$1;
var Close$1 = ToastClose$1;
function r$1(e2) {
  var t2, f2, n = "";
  if ("string" == typeof e2 || "number" == typeof e2) n += e2;
  else if ("object" == typeof e2) if (Array.isArray(e2)) {
    var o2 = e2.length;
    for (t2 = 0; t2 < o2; t2++) e2[t2] && (f2 = r$1(e2[t2])) && (n && (n += " "), n += f2);
  } else for (f2 in e2) e2[f2] && (n && (n += " "), n += f2);
  return n;
}
function clsx() {
  for (var e2, t2, f2 = 0, n = "", o2 = arguments.length; f2 < o2; f2++) (e2 = arguments[f2]) && (t2 = r$1(e2)) && (n && (n += " "), n += t2);
  return n;
}
const falsyToString = (value) => typeof value === "boolean" ? `${value}` : value === 0 ? "0" : value;
const cx = clsx;
const cva = (base, config2) => (props) => {
  var _config_compoundVariants;
  if ((config2 === null || config2 === void 0 ? void 0 : config2.variants) == null) return cx(base, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
  const { variants, defaultVariants } = config2;
  const getVariantClassNames = Object.keys(variants).map((variant) => {
    const variantProp = props === null || props === void 0 ? void 0 : props[variant];
    const defaultVariantProp = defaultVariants === null || defaultVariants === void 0 ? void 0 : defaultVariants[variant];
    if (variantProp === null) return null;
    const variantKey = falsyToString(variantProp) || falsyToString(defaultVariantProp);
    return variants[variant][variantKey];
  });
  const propsWithoutUndefined = props && Object.entries(props).reduce((acc, param) => {
    let [key, value] = param;
    if (value === void 0) {
      return acc;
    }
    acc[key] = value;
    return acc;
  }, {});
  const getCompoundVariantClassNames = config2 === null || config2 === void 0 ? void 0 : (_config_compoundVariants = config2.compoundVariants) === null || _config_compoundVariants === void 0 ? void 0 : _config_compoundVariants.reduce((acc, param) => {
    let { class: cvClass, className: cvClassName, ...compoundVariantOptions } = param;
    return Object.entries(compoundVariantOptions).every((param2) => {
      let [key, value] = param2;
      return Array.isArray(value) ? value.includes({
        ...defaultVariants,
        ...propsWithoutUndefined
      }[key]) : {
        ...defaultVariants,
        ...propsWithoutUndefined
      }[key] === value;
    }) ? [
      ...acc,
      cvClass,
      cvClassName
    ] : acc;
  }, []);
  return cx(base, getVariantClassNames, getCompoundVariantClassNames, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
};
const CLASS_PART_SEPARATOR = "-";
const createClassGroupUtils = (config2) => {
  const classMap = createClassMap(config2);
  const {
    conflictingClassGroups,
    conflictingClassGroupModifiers
  } = config2;
  const getClassGroupId = (className) => {
    const classParts = className.split(CLASS_PART_SEPARATOR);
    if (classParts[0] === "" && classParts.length !== 1) {
      classParts.shift();
    }
    return getGroupRecursive(classParts, classMap) || getGroupIdForArbitraryProperty(className);
  };
  const getConflictingClassGroupIds = (classGroupId, hasPostfixModifier) => {
    const conflicts = conflictingClassGroups[classGroupId] || [];
    if (hasPostfixModifier && conflictingClassGroupModifiers[classGroupId]) {
      return [...conflicts, ...conflictingClassGroupModifiers[classGroupId]];
    }
    return conflicts;
  };
  return {
    getClassGroupId,
    getConflictingClassGroupIds
  };
};
const getGroupRecursive = (classParts, classPartObject) => {
  if (classParts.length === 0) {
    return classPartObject.classGroupId;
  }
  const currentClassPart = classParts[0];
  const nextClassPartObject = classPartObject.nextPart.get(currentClassPart);
  const classGroupFromNextClassPart = nextClassPartObject ? getGroupRecursive(classParts.slice(1), nextClassPartObject) : void 0;
  if (classGroupFromNextClassPart) {
    return classGroupFromNextClassPart;
  }
  if (classPartObject.validators.length === 0) {
    return void 0;
  }
  const classRest = classParts.join(CLASS_PART_SEPARATOR);
  return classPartObject.validators.find(({
    validator
  }) => validator(classRest))?.classGroupId;
};
const arbitraryPropertyRegex = /^\[(.+)\]$/;
const getGroupIdForArbitraryProperty = (className) => {
  if (arbitraryPropertyRegex.test(className)) {
    const arbitraryPropertyClassName = arbitraryPropertyRegex.exec(className)[1];
    const property = arbitraryPropertyClassName?.substring(0, arbitraryPropertyClassName.indexOf(":"));
    if (property) {
      return "arbitrary.." + property;
    }
  }
};
const createClassMap = (config2) => {
  const {
    theme,
    prefix
  } = config2;
  const classMap = {
    nextPart: /* @__PURE__ */ new Map(),
    validators: []
  };
  const prefixedClassGroupEntries = getPrefixedClassGroupEntries(Object.entries(config2.classGroups), prefix);
  prefixedClassGroupEntries.forEach(([classGroupId, classGroup]) => {
    processClassesRecursively(classGroup, classMap, classGroupId, theme);
  });
  return classMap;
};
const processClassesRecursively = (classGroup, classPartObject, classGroupId, theme) => {
  classGroup.forEach((classDefinition) => {
    if (typeof classDefinition === "string") {
      const classPartObjectToEdit = classDefinition === "" ? classPartObject : getPart(classPartObject, classDefinition);
      classPartObjectToEdit.classGroupId = classGroupId;
      return;
    }
    if (typeof classDefinition === "function") {
      if (isThemeGetter(classDefinition)) {
        processClassesRecursively(classDefinition(theme), classPartObject, classGroupId, theme);
        return;
      }
      classPartObject.validators.push({
        validator: classDefinition,
        classGroupId
      });
      return;
    }
    Object.entries(classDefinition).forEach(([key, classGroup2]) => {
      processClassesRecursively(classGroup2, getPart(classPartObject, key), classGroupId, theme);
    });
  });
};
const getPart = (classPartObject, path) => {
  let currentClassPartObject = classPartObject;
  path.split(CLASS_PART_SEPARATOR).forEach((pathPart) => {
    if (!currentClassPartObject.nextPart.has(pathPart)) {
      currentClassPartObject.nextPart.set(pathPart, {
        nextPart: /* @__PURE__ */ new Map(),
        validators: []
      });
    }
    currentClassPartObject = currentClassPartObject.nextPart.get(pathPart);
  });
  return currentClassPartObject;
};
const isThemeGetter = (func) => func.isThemeGetter;
const getPrefixedClassGroupEntries = (classGroupEntries, prefix) => {
  if (!prefix) {
    return classGroupEntries;
  }
  return classGroupEntries.map(([classGroupId, classGroup]) => {
    const prefixedClassGroup = classGroup.map((classDefinition) => {
      if (typeof classDefinition === "string") {
        return prefix + classDefinition;
      }
      if (typeof classDefinition === "object") {
        return Object.fromEntries(Object.entries(classDefinition).map(([key, value]) => [prefix + key, value]));
      }
      return classDefinition;
    });
    return [classGroupId, prefixedClassGroup];
  });
};
const createLruCache = (maxCacheSize) => {
  if (maxCacheSize < 1) {
    return {
      get: () => void 0,
      set: () => {
      }
    };
  }
  let cacheSize = 0;
  let cache2 = /* @__PURE__ */ new Map();
  let previousCache = /* @__PURE__ */ new Map();
  const update = (key, value) => {
    cache2.set(key, value);
    cacheSize++;
    if (cacheSize > maxCacheSize) {
      cacheSize = 0;
      previousCache = cache2;
      cache2 = /* @__PURE__ */ new Map();
    }
  };
  return {
    get(key) {
      let value = cache2.get(key);
      if (value !== void 0) {
        return value;
      }
      if ((value = previousCache.get(key)) !== void 0) {
        update(key, value);
        return value;
      }
    },
    set(key, value) {
      if (cache2.has(key)) {
        cache2.set(key, value);
      } else {
        update(key, value);
      }
    }
  };
};
const IMPORTANT_MODIFIER = "!";
const createParseClassName = (config2) => {
  const {
    separator,
    experimentalParseClassName
  } = config2;
  const isSeparatorSingleCharacter = separator.length === 1;
  const firstSeparatorCharacter = separator[0];
  const separatorLength = separator.length;
  const parseClassName = (className) => {
    const modifiers = [];
    let bracketDepth = 0;
    let modifierStart = 0;
    let postfixModifierPosition;
    for (let index2 = 0; index2 < className.length; index2++) {
      let currentCharacter = className[index2];
      if (bracketDepth === 0) {
        if (currentCharacter === firstSeparatorCharacter && (isSeparatorSingleCharacter || className.slice(index2, index2 + separatorLength) === separator)) {
          modifiers.push(className.slice(modifierStart, index2));
          modifierStart = index2 + separatorLength;
          continue;
        }
        if (currentCharacter === "/") {
          postfixModifierPosition = index2;
          continue;
        }
      }
      if (currentCharacter === "[") {
        bracketDepth++;
      } else if (currentCharacter === "]") {
        bracketDepth--;
      }
    }
    const baseClassNameWithImportantModifier = modifiers.length === 0 ? className : className.substring(modifierStart);
    const hasImportantModifier = baseClassNameWithImportantModifier.startsWith(IMPORTANT_MODIFIER);
    const baseClassName = hasImportantModifier ? baseClassNameWithImportantModifier.substring(1) : baseClassNameWithImportantModifier;
    const maybePostfixModifierPosition = postfixModifierPosition && postfixModifierPosition > modifierStart ? postfixModifierPosition - modifierStart : void 0;
    return {
      modifiers,
      hasImportantModifier,
      baseClassName,
      maybePostfixModifierPosition
    };
  };
  if (experimentalParseClassName) {
    return (className) => experimentalParseClassName({
      className,
      parseClassName
    });
  }
  return parseClassName;
};
const sortModifiers = (modifiers) => {
  if (modifiers.length <= 1) {
    return modifiers;
  }
  const sortedModifiers = [];
  let unsortedModifiers = [];
  modifiers.forEach((modifier) => {
    const isArbitraryVariant = modifier[0] === "[";
    if (isArbitraryVariant) {
      sortedModifiers.push(...unsortedModifiers.sort(), modifier);
      unsortedModifiers = [];
    } else {
      unsortedModifiers.push(modifier);
    }
  });
  sortedModifiers.push(...unsortedModifiers.sort());
  return sortedModifiers;
};
const createConfigUtils = (config2) => ({
  cache: createLruCache(config2.cacheSize),
  parseClassName: createParseClassName(config2),
  ...createClassGroupUtils(config2)
});
const SPLIT_CLASSES_REGEX = /\s+/;
const mergeClassList = (classList, configUtils) => {
  const {
    parseClassName,
    getClassGroupId,
    getConflictingClassGroupIds
  } = configUtils;
  const classGroupsInConflict = [];
  const classNames = classList.trim().split(SPLIT_CLASSES_REGEX);
  let result = "";
  for (let index2 = classNames.length - 1; index2 >= 0; index2 -= 1) {
    const originalClassName = classNames[index2];
    const {
      modifiers,
      hasImportantModifier,
      baseClassName,
      maybePostfixModifierPosition
    } = parseClassName(originalClassName);
    let hasPostfixModifier = Boolean(maybePostfixModifierPosition);
    let classGroupId = getClassGroupId(hasPostfixModifier ? baseClassName.substring(0, maybePostfixModifierPosition) : baseClassName);
    if (!classGroupId) {
      if (!hasPostfixModifier) {
        result = originalClassName + (result.length > 0 ? " " + result : result);
        continue;
      }
      classGroupId = getClassGroupId(baseClassName);
      if (!classGroupId) {
        result = originalClassName + (result.length > 0 ? " " + result : result);
        continue;
      }
      hasPostfixModifier = false;
    }
    const variantModifier = sortModifiers(modifiers).join(":");
    const modifierId = hasImportantModifier ? variantModifier + IMPORTANT_MODIFIER : variantModifier;
    const classId = modifierId + classGroupId;
    if (classGroupsInConflict.includes(classId)) {
      continue;
    }
    classGroupsInConflict.push(classId);
    const conflictGroups = getConflictingClassGroupIds(classGroupId, hasPostfixModifier);
    for (let i2 = 0; i2 < conflictGroups.length; ++i2) {
      const group = conflictGroups[i2];
      classGroupsInConflict.push(modifierId + group);
    }
    result = originalClassName + (result.length > 0 ? " " + result : result);
  }
  return result;
};
function twJoin() {
  let index2 = 0;
  let argument;
  let resolvedValue;
  let string2 = "";
  while (index2 < arguments.length) {
    if (argument = arguments[index2++]) {
      if (resolvedValue = toValue(argument)) {
        string2 && (string2 += " ");
        string2 += resolvedValue;
      }
    }
  }
  return string2;
}
const toValue = (mix) => {
  if (typeof mix === "string") {
    return mix;
  }
  let resolvedValue;
  let string2 = "";
  for (let k2 = 0; k2 < mix.length; k2++) {
    if (mix[k2]) {
      if (resolvedValue = toValue(mix[k2])) {
        string2 && (string2 += " ");
        string2 += resolvedValue;
      }
    }
  }
  return string2;
};
function createTailwindMerge(createConfigFirst, ...createConfigRest) {
  let configUtils;
  let cacheGet;
  let cacheSet;
  let functionToCall = initTailwindMerge;
  function initTailwindMerge(classList) {
    const config2 = createConfigRest.reduce((previousConfig, createConfigCurrent) => createConfigCurrent(previousConfig), createConfigFirst());
    configUtils = createConfigUtils(config2);
    cacheGet = configUtils.cache.get;
    cacheSet = configUtils.cache.set;
    functionToCall = tailwindMerge;
    return tailwindMerge(classList);
  }
  function tailwindMerge(classList) {
    const cachedResult = cacheGet(classList);
    if (cachedResult) {
      return cachedResult;
    }
    const result = mergeClassList(classList, configUtils);
    cacheSet(classList, result);
    return result;
  }
  return function callTailwindMerge() {
    return functionToCall(twJoin.apply(null, arguments));
  };
}
const fromTheme = (key) => {
  const themeGetter = (theme) => theme[key] || [];
  themeGetter.isThemeGetter = true;
  return themeGetter;
};
const arbitraryValueRegex = /^\[(?:([a-z-]+):)?(.+)\]$/i;
const fractionRegex = /^\d+\/\d+$/;
const stringLengths = /* @__PURE__ */ new Set(["px", "full", "screen"]);
const tshirtUnitRegex = /^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/;
const lengthUnitRegex = /\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/;
const colorFunctionRegex = /^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/;
const shadowRegex = /^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/;
const imageRegex = /^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;
const isLength = (value) => isNumber(value) || stringLengths.has(value) || fractionRegex.test(value);
const isArbitraryLength = (value) => getIsArbitraryValue(value, "length", isLengthOnly);
const isNumber = (value) => Boolean(value) && !Number.isNaN(Number(value));
const isArbitraryNumber = (value) => getIsArbitraryValue(value, "number", isNumber);
const isInteger = (value) => Boolean(value) && Number.isInteger(Number(value));
const isPercent = (value) => value.endsWith("%") && isNumber(value.slice(0, -1));
const isArbitraryValue = (value) => arbitraryValueRegex.test(value);
const isTshirtSize = (value) => tshirtUnitRegex.test(value);
const sizeLabels = /* @__PURE__ */ new Set(["length", "size", "percentage"]);
const isArbitrarySize = (value) => getIsArbitraryValue(value, sizeLabels, isNever);
const isArbitraryPosition = (value) => getIsArbitraryValue(value, "position", isNever);
const imageLabels = /* @__PURE__ */ new Set(["image", "url"]);
const isArbitraryImage = (value) => getIsArbitraryValue(value, imageLabels, isImage);
const isArbitraryShadow = (value) => getIsArbitraryValue(value, "", isShadow);
const isAny = () => true;
const getIsArbitraryValue = (value, label, testValue) => {
  const result = arbitraryValueRegex.exec(value);
  if (result) {
    if (result[1]) {
      return typeof label === "string" ? result[1] === label : label.has(result[1]);
    }
    return testValue(result[2]);
  }
  return false;
};
const isLengthOnly = (value) => (
  // `colorFunctionRegex` check is necessary because color functions can have percentages in them which which would be incorrectly classified as lengths.
  // For example, `hsl(0 0% 0%)` would be classified as a length without this check.
  // I could also use lookbehind assertion in `lengthUnitRegex` but that isn't supported widely enough.
  lengthUnitRegex.test(value) && !colorFunctionRegex.test(value)
);
const isNever = () => false;
const isShadow = (value) => shadowRegex.test(value);
const isImage = (value) => imageRegex.test(value);
const getDefaultConfig = () => {
  const colors = fromTheme("colors");
  const spacing = fromTheme("spacing");
  const blur = fromTheme("blur");
  const brightness = fromTheme("brightness");
  const borderColor = fromTheme("borderColor");
  const borderRadius = fromTheme("borderRadius");
  const borderSpacing = fromTheme("borderSpacing");
  const borderWidth = fromTheme("borderWidth");
  const contrast = fromTheme("contrast");
  const grayscale = fromTheme("grayscale");
  const hueRotate = fromTheme("hueRotate");
  const invert = fromTheme("invert");
  const gap = fromTheme("gap");
  const gradientColorStops = fromTheme("gradientColorStops");
  const gradientColorStopPositions = fromTheme("gradientColorStopPositions");
  const inset = fromTheme("inset");
  const margin = fromTheme("margin");
  const opacity = fromTheme("opacity");
  const padding = fromTheme("padding");
  const saturate = fromTheme("saturate");
  const scale = fromTheme("scale");
  const sepia = fromTheme("sepia");
  const skew = fromTheme("skew");
  const space = fromTheme("space");
  const translate = fromTheme("translate");
  const getOverscroll = () => ["auto", "contain", "none"];
  const getOverflow = () => ["auto", "hidden", "clip", "visible", "scroll"];
  const getSpacingWithAutoAndArbitrary = () => ["auto", isArbitraryValue, spacing];
  const getSpacingWithArbitrary = () => [isArbitraryValue, spacing];
  const getLengthWithEmptyAndArbitrary = () => ["", isLength, isArbitraryLength];
  const getNumberWithAutoAndArbitrary = () => ["auto", isNumber, isArbitraryValue];
  const getPositions = () => ["bottom", "center", "left", "left-bottom", "left-top", "right", "right-bottom", "right-top", "top"];
  const getLineStyles = () => ["solid", "dashed", "dotted", "double", "none"];
  const getBlendModes = () => ["normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"];
  const getAlign = () => ["start", "end", "center", "between", "around", "evenly", "stretch"];
  const getZeroAndEmpty = () => ["", "0", isArbitraryValue];
  const getBreaks = () => ["auto", "avoid", "all", "avoid-page", "page", "left", "right", "column"];
  const getNumberAndArbitrary = () => [isNumber, isArbitraryValue];
  return {
    cacheSize: 500,
    separator: ":",
    theme: {
      colors: [isAny],
      spacing: [isLength, isArbitraryLength],
      blur: ["none", "", isTshirtSize, isArbitraryValue],
      brightness: getNumberAndArbitrary(),
      borderColor: [colors],
      borderRadius: ["none", "", "full", isTshirtSize, isArbitraryValue],
      borderSpacing: getSpacingWithArbitrary(),
      borderWidth: getLengthWithEmptyAndArbitrary(),
      contrast: getNumberAndArbitrary(),
      grayscale: getZeroAndEmpty(),
      hueRotate: getNumberAndArbitrary(),
      invert: getZeroAndEmpty(),
      gap: getSpacingWithArbitrary(),
      gradientColorStops: [colors],
      gradientColorStopPositions: [isPercent, isArbitraryLength],
      inset: getSpacingWithAutoAndArbitrary(),
      margin: getSpacingWithAutoAndArbitrary(),
      opacity: getNumberAndArbitrary(),
      padding: getSpacingWithArbitrary(),
      saturate: getNumberAndArbitrary(),
      scale: getNumberAndArbitrary(),
      sepia: getZeroAndEmpty(),
      skew: getNumberAndArbitrary(),
      space: getSpacingWithArbitrary(),
      translate: getSpacingWithArbitrary()
    },
    classGroups: {
      // Layout
      /**
       * Aspect Ratio
       * @see https://tailwindcss.com/docs/aspect-ratio
       */
      aspect: [{
        aspect: ["auto", "square", "video", isArbitraryValue]
      }],
      /**
       * Container
       * @see https://tailwindcss.com/docs/container
       */
      container: ["container"],
      /**
       * Columns
       * @see https://tailwindcss.com/docs/columns
       */
      columns: [{
        columns: [isTshirtSize]
      }],
      /**
       * Break After
       * @see https://tailwindcss.com/docs/break-after
       */
      "break-after": [{
        "break-after": getBreaks()
      }],
      /**
       * Break Before
       * @see https://tailwindcss.com/docs/break-before
       */
      "break-before": [{
        "break-before": getBreaks()
      }],
      /**
       * Break Inside
       * @see https://tailwindcss.com/docs/break-inside
       */
      "break-inside": [{
        "break-inside": ["auto", "avoid", "avoid-page", "avoid-column"]
      }],
      /**
       * Box Decoration Break
       * @see https://tailwindcss.com/docs/box-decoration-break
       */
      "box-decoration": [{
        "box-decoration": ["slice", "clone"]
      }],
      /**
       * Box Sizing
       * @see https://tailwindcss.com/docs/box-sizing
       */
      box: [{
        box: ["border", "content"]
      }],
      /**
       * Display
       * @see https://tailwindcss.com/docs/display
       */
      display: ["block", "inline-block", "inline", "flex", "inline-flex", "table", "inline-table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row-group", "table-row", "flow-root", "grid", "inline-grid", "contents", "list-item", "hidden"],
      /**
       * Floats
       * @see https://tailwindcss.com/docs/float
       */
      float: [{
        float: ["right", "left", "none", "start", "end"]
      }],
      /**
       * Clear
       * @see https://tailwindcss.com/docs/clear
       */
      clear: [{
        clear: ["left", "right", "both", "none", "start", "end"]
      }],
      /**
       * Isolation
       * @see https://tailwindcss.com/docs/isolation
       */
      isolation: ["isolate", "isolation-auto"],
      /**
       * Object Fit
       * @see https://tailwindcss.com/docs/object-fit
       */
      "object-fit": [{
        object: ["contain", "cover", "fill", "none", "scale-down"]
      }],
      /**
       * Object Position
       * @see https://tailwindcss.com/docs/object-position
       */
      "object-position": [{
        object: [...getPositions(), isArbitraryValue]
      }],
      /**
       * Overflow
       * @see https://tailwindcss.com/docs/overflow
       */
      overflow: [{
        overflow: getOverflow()
      }],
      /**
       * Overflow X
       * @see https://tailwindcss.com/docs/overflow
       */
      "overflow-x": [{
        "overflow-x": getOverflow()
      }],
      /**
       * Overflow Y
       * @see https://tailwindcss.com/docs/overflow
       */
      "overflow-y": [{
        "overflow-y": getOverflow()
      }],
      /**
       * Overscroll Behavior
       * @see https://tailwindcss.com/docs/overscroll-behavior
       */
      overscroll: [{
        overscroll: getOverscroll()
      }],
      /**
       * Overscroll Behavior X
       * @see https://tailwindcss.com/docs/overscroll-behavior
       */
      "overscroll-x": [{
        "overscroll-x": getOverscroll()
      }],
      /**
       * Overscroll Behavior Y
       * @see https://tailwindcss.com/docs/overscroll-behavior
       */
      "overscroll-y": [{
        "overscroll-y": getOverscroll()
      }],
      /**
       * Position
       * @see https://tailwindcss.com/docs/position
       */
      position: ["static", "fixed", "absolute", "relative", "sticky"],
      /**
       * Top / Right / Bottom / Left
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      inset: [{
        inset: [inset]
      }],
      /**
       * Right / Left
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      "inset-x": [{
        "inset-x": [inset]
      }],
      /**
       * Top / Bottom
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      "inset-y": [{
        "inset-y": [inset]
      }],
      /**
       * Start
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      start: [{
        start: [inset]
      }],
      /**
       * End
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      end: [{
        end: [inset]
      }],
      /**
       * Top
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      top: [{
        top: [inset]
      }],
      /**
       * Right
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      right: [{
        right: [inset]
      }],
      /**
       * Bottom
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      bottom: [{
        bottom: [inset]
      }],
      /**
       * Left
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      left: [{
        left: [inset]
      }],
      /**
       * Visibility
       * @see https://tailwindcss.com/docs/visibility
       */
      visibility: ["visible", "invisible", "collapse"],
      /**
       * Z-Index
       * @see https://tailwindcss.com/docs/z-index
       */
      z: [{
        z: ["auto", isInteger, isArbitraryValue]
      }],
      // Flexbox and Grid
      /**
       * Flex Basis
       * @see https://tailwindcss.com/docs/flex-basis
       */
      basis: [{
        basis: getSpacingWithAutoAndArbitrary()
      }],
      /**
       * Flex Direction
       * @see https://tailwindcss.com/docs/flex-direction
       */
      "flex-direction": [{
        flex: ["row", "row-reverse", "col", "col-reverse"]
      }],
      /**
       * Flex Wrap
       * @see https://tailwindcss.com/docs/flex-wrap
       */
      "flex-wrap": [{
        flex: ["wrap", "wrap-reverse", "nowrap"]
      }],
      /**
       * Flex
       * @see https://tailwindcss.com/docs/flex
       */
      flex: [{
        flex: ["1", "auto", "initial", "none", isArbitraryValue]
      }],
      /**
       * Flex Grow
       * @see https://tailwindcss.com/docs/flex-grow
       */
      grow: [{
        grow: getZeroAndEmpty()
      }],
      /**
       * Flex Shrink
       * @see https://tailwindcss.com/docs/flex-shrink
       */
      shrink: [{
        shrink: getZeroAndEmpty()
      }],
      /**
       * Order
       * @see https://tailwindcss.com/docs/order
       */
      order: [{
        order: ["first", "last", "none", isInteger, isArbitraryValue]
      }],
      /**
       * Grid Template Columns
       * @see https://tailwindcss.com/docs/grid-template-columns
       */
      "grid-cols": [{
        "grid-cols": [isAny]
      }],
      /**
       * Grid Column Start / End
       * @see https://tailwindcss.com/docs/grid-column
       */
      "col-start-end": [{
        col: ["auto", {
          span: ["full", isInteger, isArbitraryValue]
        }, isArbitraryValue]
      }],
      /**
       * Grid Column Start
       * @see https://tailwindcss.com/docs/grid-column
       */
      "col-start": [{
        "col-start": getNumberWithAutoAndArbitrary()
      }],
      /**
       * Grid Column End
       * @see https://tailwindcss.com/docs/grid-column
       */
      "col-end": [{
        "col-end": getNumberWithAutoAndArbitrary()
      }],
      /**
       * Grid Template Rows
       * @see https://tailwindcss.com/docs/grid-template-rows
       */
      "grid-rows": [{
        "grid-rows": [isAny]
      }],
      /**
       * Grid Row Start / End
       * @see https://tailwindcss.com/docs/grid-row
       */
      "row-start-end": [{
        row: ["auto", {
          span: [isInteger, isArbitraryValue]
        }, isArbitraryValue]
      }],
      /**
       * Grid Row Start
       * @see https://tailwindcss.com/docs/grid-row
       */
      "row-start": [{
        "row-start": getNumberWithAutoAndArbitrary()
      }],
      /**
       * Grid Row End
       * @see https://tailwindcss.com/docs/grid-row
       */
      "row-end": [{
        "row-end": getNumberWithAutoAndArbitrary()
      }],
      /**
       * Grid Auto Flow
       * @see https://tailwindcss.com/docs/grid-auto-flow
       */
      "grid-flow": [{
        "grid-flow": ["row", "col", "dense", "row-dense", "col-dense"]
      }],
      /**
       * Grid Auto Columns
       * @see https://tailwindcss.com/docs/grid-auto-columns
       */
      "auto-cols": [{
        "auto-cols": ["auto", "min", "max", "fr", isArbitraryValue]
      }],
      /**
       * Grid Auto Rows
       * @see https://tailwindcss.com/docs/grid-auto-rows
       */
      "auto-rows": [{
        "auto-rows": ["auto", "min", "max", "fr", isArbitraryValue]
      }],
      /**
       * Gap
       * @see https://tailwindcss.com/docs/gap
       */
      gap: [{
        gap: [gap]
      }],
      /**
       * Gap X
       * @see https://tailwindcss.com/docs/gap
       */
      "gap-x": [{
        "gap-x": [gap]
      }],
      /**
       * Gap Y
       * @see https://tailwindcss.com/docs/gap
       */
      "gap-y": [{
        "gap-y": [gap]
      }],
      /**
       * Justify Content
       * @see https://tailwindcss.com/docs/justify-content
       */
      "justify-content": [{
        justify: ["normal", ...getAlign()]
      }],
      /**
       * Justify Items
       * @see https://tailwindcss.com/docs/justify-items
       */
      "justify-items": [{
        "justify-items": ["start", "end", "center", "stretch"]
      }],
      /**
       * Justify Self
       * @see https://tailwindcss.com/docs/justify-self
       */
      "justify-self": [{
        "justify-self": ["auto", "start", "end", "center", "stretch"]
      }],
      /**
       * Align Content
       * @see https://tailwindcss.com/docs/align-content
       */
      "align-content": [{
        content: ["normal", ...getAlign(), "baseline"]
      }],
      /**
       * Align Items
       * @see https://tailwindcss.com/docs/align-items
       */
      "align-items": [{
        items: ["start", "end", "center", "baseline", "stretch"]
      }],
      /**
       * Align Self
       * @see https://tailwindcss.com/docs/align-self
       */
      "align-self": [{
        self: ["auto", "start", "end", "center", "stretch", "baseline"]
      }],
      /**
       * Place Content
       * @see https://tailwindcss.com/docs/place-content
       */
      "place-content": [{
        "place-content": [...getAlign(), "baseline"]
      }],
      /**
       * Place Items
       * @see https://tailwindcss.com/docs/place-items
       */
      "place-items": [{
        "place-items": ["start", "end", "center", "baseline", "stretch"]
      }],
      /**
       * Place Self
       * @see https://tailwindcss.com/docs/place-self
       */
      "place-self": [{
        "place-self": ["auto", "start", "end", "center", "stretch"]
      }],
      // Spacing
      /**
       * Padding
       * @see https://tailwindcss.com/docs/padding
       */
      p: [{
        p: [padding]
      }],
      /**
       * Padding X
       * @see https://tailwindcss.com/docs/padding
       */
      px: [{
        px: [padding]
      }],
      /**
       * Padding Y
       * @see https://tailwindcss.com/docs/padding
       */
      py: [{
        py: [padding]
      }],
      /**
       * Padding Start
       * @see https://tailwindcss.com/docs/padding
       */
      ps: [{
        ps: [padding]
      }],
      /**
       * Padding End
       * @see https://tailwindcss.com/docs/padding
       */
      pe: [{
        pe: [padding]
      }],
      /**
       * Padding Top
       * @see https://tailwindcss.com/docs/padding
       */
      pt: [{
        pt: [padding]
      }],
      /**
       * Padding Right
       * @see https://tailwindcss.com/docs/padding
       */
      pr: [{
        pr: [padding]
      }],
      /**
       * Padding Bottom
       * @see https://tailwindcss.com/docs/padding
       */
      pb: [{
        pb: [padding]
      }],
      /**
       * Padding Left
       * @see https://tailwindcss.com/docs/padding
       */
      pl: [{
        pl: [padding]
      }],
      /**
       * Margin
       * @see https://tailwindcss.com/docs/margin
       */
      m: [{
        m: [margin]
      }],
      /**
       * Margin X
       * @see https://tailwindcss.com/docs/margin
       */
      mx: [{
        mx: [margin]
      }],
      /**
       * Margin Y
       * @see https://tailwindcss.com/docs/margin
       */
      my: [{
        my: [margin]
      }],
      /**
       * Margin Start
       * @see https://tailwindcss.com/docs/margin
       */
      ms: [{
        ms: [margin]
      }],
      /**
       * Margin End
       * @see https://tailwindcss.com/docs/margin
       */
      me: [{
        me: [margin]
      }],
      /**
       * Margin Top
       * @see https://tailwindcss.com/docs/margin
       */
      mt: [{
        mt: [margin]
      }],
      /**
       * Margin Right
       * @see https://tailwindcss.com/docs/margin
       */
      mr: [{
        mr: [margin]
      }],
      /**
       * Margin Bottom
       * @see https://tailwindcss.com/docs/margin
       */
      mb: [{
        mb: [margin]
      }],
      /**
       * Margin Left
       * @see https://tailwindcss.com/docs/margin
       */
      ml: [{
        ml: [margin]
      }],
      /**
       * Space Between X
       * @see https://tailwindcss.com/docs/space
       */
      "space-x": [{
        "space-x": [space]
      }],
      /**
       * Space Between X Reverse
       * @see https://tailwindcss.com/docs/space
       */
      "space-x-reverse": ["space-x-reverse"],
      /**
       * Space Between Y
       * @see https://tailwindcss.com/docs/space
       */
      "space-y": [{
        "space-y": [space]
      }],
      /**
       * Space Between Y Reverse
       * @see https://tailwindcss.com/docs/space
       */
      "space-y-reverse": ["space-y-reverse"],
      // Sizing
      /**
       * Width
       * @see https://tailwindcss.com/docs/width
       */
      w: [{
        w: ["auto", "min", "max", "fit", "svw", "lvw", "dvw", isArbitraryValue, spacing]
      }],
      /**
       * Min-Width
       * @see https://tailwindcss.com/docs/min-width
       */
      "min-w": [{
        "min-w": [isArbitraryValue, spacing, "min", "max", "fit"]
      }],
      /**
       * Max-Width
       * @see https://tailwindcss.com/docs/max-width
       */
      "max-w": [{
        "max-w": [isArbitraryValue, spacing, "none", "full", "min", "max", "fit", "prose", {
          screen: [isTshirtSize]
        }, isTshirtSize]
      }],
      /**
       * Height
       * @see https://tailwindcss.com/docs/height
       */
      h: [{
        h: [isArbitraryValue, spacing, "auto", "min", "max", "fit", "svh", "lvh", "dvh"]
      }],
      /**
       * Min-Height
       * @see https://tailwindcss.com/docs/min-height
       */
      "min-h": [{
        "min-h": [isArbitraryValue, spacing, "min", "max", "fit", "svh", "lvh", "dvh"]
      }],
      /**
       * Max-Height
       * @see https://tailwindcss.com/docs/max-height
       */
      "max-h": [{
        "max-h": [isArbitraryValue, spacing, "min", "max", "fit", "svh", "lvh", "dvh"]
      }],
      /**
       * Size
       * @see https://tailwindcss.com/docs/size
       */
      size: [{
        size: [isArbitraryValue, spacing, "auto", "min", "max", "fit"]
      }],
      // Typography
      /**
       * Font Size
       * @see https://tailwindcss.com/docs/font-size
       */
      "font-size": [{
        text: ["base", isTshirtSize, isArbitraryLength]
      }],
      /**
       * Font Smoothing
       * @see https://tailwindcss.com/docs/font-smoothing
       */
      "font-smoothing": ["antialiased", "subpixel-antialiased"],
      /**
       * Font Style
       * @see https://tailwindcss.com/docs/font-style
       */
      "font-style": ["italic", "not-italic"],
      /**
       * Font Weight
       * @see https://tailwindcss.com/docs/font-weight
       */
      "font-weight": [{
        font: ["thin", "extralight", "light", "normal", "medium", "semibold", "bold", "extrabold", "black", isArbitraryNumber]
      }],
      /**
       * Font Family
       * @see https://tailwindcss.com/docs/font-family
       */
      "font-family": [{
        font: [isAny]
      }],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-normal": ["normal-nums"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-ordinal": ["ordinal"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-slashed-zero": ["slashed-zero"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-figure": ["lining-nums", "oldstyle-nums"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-spacing": ["proportional-nums", "tabular-nums"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-fraction": ["diagonal-fractions", "stacked-fractions"],
      /**
       * Letter Spacing
       * @see https://tailwindcss.com/docs/letter-spacing
       */
      tracking: [{
        tracking: ["tighter", "tight", "normal", "wide", "wider", "widest", isArbitraryValue]
      }],
      /**
       * Line Clamp
       * @see https://tailwindcss.com/docs/line-clamp
       */
      "line-clamp": [{
        "line-clamp": ["none", isNumber, isArbitraryNumber]
      }],
      /**
       * Line Height
       * @see https://tailwindcss.com/docs/line-height
       */
      leading: [{
        leading: ["none", "tight", "snug", "normal", "relaxed", "loose", isLength, isArbitraryValue]
      }],
      /**
       * List Style Image
       * @see https://tailwindcss.com/docs/list-style-image
       */
      "list-image": [{
        "list-image": ["none", isArbitraryValue]
      }],
      /**
       * List Style Type
       * @see https://tailwindcss.com/docs/list-style-type
       */
      "list-style-type": [{
        list: ["none", "disc", "decimal", isArbitraryValue]
      }],
      /**
       * List Style Position
       * @see https://tailwindcss.com/docs/list-style-position
       */
      "list-style-position": [{
        list: ["inside", "outside"]
      }],
      /**
       * Placeholder Color
       * @deprecated since Tailwind CSS v3.0.0
       * @see https://tailwindcss.com/docs/placeholder-color
       */
      "placeholder-color": [{
        placeholder: [colors]
      }],
      /**
       * Placeholder Opacity
       * @see https://tailwindcss.com/docs/placeholder-opacity
       */
      "placeholder-opacity": [{
        "placeholder-opacity": [opacity]
      }],
      /**
       * Text Alignment
       * @see https://tailwindcss.com/docs/text-align
       */
      "text-alignment": [{
        text: ["left", "center", "right", "justify", "start", "end"]
      }],
      /**
       * Text Color
       * @see https://tailwindcss.com/docs/text-color
       */
      "text-color": [{
        text: [colors]
      }],
      /**
       * Text Opacity
       * @see https://tailwindcss.com/docs/text-opacity
       */
      "text-opacity": [{
        "text-opacity": [opacity]
      }],
      /**
       * Text Decoration
       * @see https://tailwindcss.com/docs/text-decoration
       */
      "text-decoration": ["underline", "overline", "line-through", "no-underline"],
      /**
       * Text Decoration Style
       * @see https://tailwindcss.com/docs/text-decoration-style
       */
      "text-decoration-style": [{
        decoration: [...getLineStyles(), "wavy"]
      }],
      /**
       * Text Decoration Thickness
       * @see https://tailwindcss.com/docs/text-decoration-thickness
       */
      "text-decoration-thickness": [{
        decoration: ["auto", "from-font", isLength, isArbitraryLength]
      }],
      /**
       * Text Underline Offset
       * @see https://tailwindcss.com/docs/text-underline-offset
       */
      "underline-offset": [{
        "underline-offset": ["auto", isLength, isArbitraryValue]
      }],
      /**
       * Text Decoration Color
       * @see https://tailwindcss.com/docs/text-decoration-color
       */
      "text-decoration-color": [{
        decoration: [colors]
      }],
      /**
       * Text Transform
       * @see https://tailwindcss.com/docs/text-transform
       */
      "text-transform": ["uppercase", "lowercase", "capitalize", "normal-case"],
      /**
       * Text Overflow
       * @see https://tailwindcss.com/docs/text-overflow
       */
      "text-overflow": ["truncate", "text-ellipsis", "text-clip"],
      /**
       * Text Wrap
       * @see https://tailwindcss.com/docs/text-wrap
       */
      "text-wrap": [{
        text: ["wrap", "nowrap", "balance", "pretty"]
      }],
      /**
       * Text Indent
       * @see https://tailwindcss.com/docs/text-indent
       */
      indent: [{
        indent: getSpacingWithArbitrary()
      }],
      /**
       * Vertical Alignment
       * @see https://tailwindcss.com/docs/vertical-align
       */
      "vertical-align": [{
        align: ["baseline", "top", "middle", "bottom", "text-top", "text-bottom", "sub", "super", isArbitraryValue]
      }],
      /**
       * Whitespace
       * @see https://tailwindcss.com/docs/whitespace
       */
      whitespace: [{
        whitespace: ["normal", "nowrap", "pre", "pre-line", "pre-wrap", "break-spaces"]
      }],
      /**
       * Word Break
       * @see https://tailwindcss.com/docs/word-break
       */
      break: [{
        break: ["normal", "words", "all", "keep"]
      }],
      /**
       * Hyphens
       * @see https://tailwindcss.com/docs/hyphens
       */
      hyphens: [{
        hyphens: ["none", "manual", "auto"]
      }],
      /**
       * Content
       * @see https://tailwindcss.com/docs/content
       */
      content: [{
        content: ["none", isArbitraryValue]
      }],
      // Backgrounds
      /**
       * Background Attachment
       * @see https://tailwindcss.com/docs/background-attachment
       */
      "bg-attachment": [{
        bg: ["fixed", "local", "scroll"]
      }],
      /**
       * Background Clip
       * @see https://tailwindcss.com/docs/background-clip
       */
      "bg-clip": [{
        "bg-clip": ["border", "padding", "content", "text"]
      }],
      /**
       * Background Opacity
       * @deprecated since Tailwind CSS v3.0.0
       * @see https://tailwindcss.com/docs/background-opacity
       */
      "bg-opacity": [{
        "bg-opacity": [opacity]
      }],
      /**
       * Background Origin
       * @see https://tailwindcss.com/docs/background-origin
       */
      "bg-origin": [{
        "bg-origin": ["border", "padding", "content"]
      }],
      /**
       * Background Position
       * @see https://tailwindcss.com/docs/background-position
       */
      "bg-position": [{
        bg: [...getPositions(), isArbitraryPosition]
      }],
      /**
       * Background Repeat
       * @see https://tailwindcss.com/docs/background-repeat
       */
      "bg-repeat": [{
        bg: ["no-repeat", {
          repeat: ["", "x", "y", "round", "space"]
        }]
      }],
      /**
       * Background Size
       * @see https://tailwindcss.com/docs/background-size
       */
      "bg-size": [{
        bg: ["auto", "cover", "contain", isArbitrarySize]
      }],
      /**
       * Background Image
       * @see https://tailwindcss.com/docs/background-image
       */
      "bg-image": [{
        bg: ["none", {
          "gradient-to": ["t", "tr", "r", "br", "b", "bl", "l", "tl"]
        }, isArbitraryImage]
      }],
      /**
       * Background Color
       * @see https://tailwindcss.com/docs/background-color
       */
      "bg-color": [{
        bg: [colors]
      }],
      /**
       * Gradient Color Stops From Position
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-from-pos": [{
        from: [gradientColorStopPositions]
      }],
      /**
       * Gradient Color Stops Via Position
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-via-pos": [{
        via: [gradientColorStopPositions]
      }],
      /**
       * Gradient Color Stops To Position
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-to-pos": [{
        to: [gradientColorStopPositions]
      }],
      /**
       * Gradient Color Stops From
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-from": [{
        from: [gradientColorStops]
      }],
      /**
       * Gradient Color Stops Via
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-via": [{
        via: [gradientColorStops]
      }],
      /**
       * Gradient Color Stops To
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-to": [{
        to: [gradientColorStops]
      }],
      // Borders
      /**
       * Border Radius
       * @see https://tailwindcss.com/docs/border-radius
       */
      rounded: [{
        rounded: [borderRadius]
      }],
      /**
       * Border Radius Start
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-s": [{
        "rounded-s": [borderRadius]
      }],
      /**
       * Border Radius End
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-e": [{
        "rounded-e": [borderRadius]
      }],
      /**
       * Border Radius Top
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-t": [{
        "rounded-t": [borderRadius]
      }],
      /**
       * Border Radius Right
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-r": [{
        "rounded-r": [borderRadius]
      }],
      /**
       * Border Radius Bottom
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-b": [{
        "rounded-b": [borderRadius]
      }],
      /**
       * Border Radius Left
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-l": [{
        "rounded-l": [borderRadius]
      }],
      /**
       * Border Radius Start Start
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-ss": [{
        "rounded-ss": [borderRadius]
      }],
      /**
       * Border Radius Start End
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-se": [{
        "rounded-se": [borderRadius]
      }],
      /**
       * Border Radius End End
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-ee": [{
        "rounded-ee": [borderRadius]
      }],
      /**
       * Border Radius End Start
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-es": [{
        "rounded-es": [borderRadius]
      }],
      /**
       * Border Radius Top Left
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-tl": [{
        "rounded-tl": [borderRadius]
      }],
      /**
       * Border Radius Top Right
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-tr": [{
        "rounded-tr": [borderRadius]
      }],
      /**
       * Border Radius Bottom Right
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-br": [{
        "rounded-br": [borderRadius]
      }],
      /**
       * Border Radius Bottom Left
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-bl": [{
        "rounded-bl": [borderRadius]
      }],
      /**
       * Border Width
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w": [{
        border: [borderWidth]
      }],
      /**
       * Border Width X
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-x": [{
        "border-x": [borderWidth]
      }],
      /**
       * Border Width Y
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-y": [{
        "border-y": [borderWidth]
      }],
      /**
       * Border Width Start
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-s": [{
        "border-s": [borderWidth]
      }],
      /**
       * Border Width End
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-e": [{
        "border-e": [borderWidth]
      }],
      /**
       * Border Width Top
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-t": [{
        "border-t": [borderWidth]
      }],
      /**
       * Border Width Right
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-r": [{
        "border-r": [borderWidth]
      }],
      /**
       * Border Width Bottom
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-b": [{
        "border-b": [borderWidth]
      }],
      /**
       * Border Width Left
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-l": [{
        "border-l": [borderWidth]
      }],
      /**
       * Border Opacity
       * @see https://tailwindcss.com/docs/border-opacity
       */
      "border-opacity": [{
        "border-opacity": [opacity]
      }],
      /**
       * Border Style
       * @see https://tailwindcss.com/docs/border-style
       */
      "border-style": [{
        border: [...getLineStyles(), "hidden"]
      }],
      /**
       * Divide Width X
       * @see https://tailwindcss.com/docs/divide-width
       */
      "divide-x": [{
        "divide-x": [borderWidth]
      }],
      /**
       * Divide Width X Reverse
       * @see https://tailwindcss.com/docs/divide-width
       */
      "divide-x-reverse": ["divide-x-reverse"],
      /**
       * Divide Width Y
       * @see https://tailwindcss.com/docs/divide-width
       */
      "divide-y": [{
        "divide-y": [borderWidth]
      }],
      /**
       * Divide Width Y Reverse
       * @see https://tailwindcss.com/docs/divide-width
       */
      "divide-y-reverse": ["divide-y-reverse"],
      /**
       * Divide Opacity
       * @see https://tailwindcss.com/docs/divide-opacity
       */
      "divide-opacity": [{
        "divide-opacity": [opacity]
      }],
      /**
       * Divide Style
       * @see https://tailwindcss.com/docs/divide-style
       */
      "divide-style": [{
        divide: getLineStyles()
      }],
      /**
       * Border Color
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color": [{
        border: [borderColor]
      }],
      /**
       * Border Color X
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-x": [{
        "border-x": [borderColor]
      }],
      /**
       * Border Color Y
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-y": [{
        "border-y": [borderColor]
      }],
      /**
       * Border Color S
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-s": [{
        "border-s": [borderColor]
      }],
      /**
       * Border Color E
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-e": [{
        "border-e": [borderColor]
      }],
      /**
       * Border Color Top
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-t": [{
        "border-t": [borderColor]
      }],
      /**
       * Border Color Right
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-r": [{
        "border-r": [borderColor]
      }],
      /**
       * Border Color Bottom
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-b": [{
        "border-b": [borderColor]
      }],
      /**
       * Border Color Left
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-l": [{
        "border-l": [borderColor]
      }],
      /**
       * Divide Color
       * @see https://tailwindcss.com/docs/divide-color
       */
      "divide-color": [{
        divide: [borderColor]
      }],
      /**
       * Outline Style
       * @see https://tailwindcss.com/docs/outline-style
       */
      "outline-style": [{
        outline: ["", ...getLineStyles()]
      }],
      /**
       * Outline Offset
       * @see https://tailwindcss.com/docs/outline-offset
       */
      "outline-offset": [{
        "outline-offset": [isLength, isArbitraryValue]
      }],
      /**
       * Outline Width
       * @see https://tailwindcss.com/docs/outline-width
       */
      "outline-w": [{
        outline: [isLength, isArbitraryLength]
      }],
      /**
       * Outline Color
       * @see https://tailwindcss.com/docs/outline-color
       */
      "outline-color": [{
        outline: [colors]
      }],
      /**
       * Ring Width
       * @see https://tailwindcss.com/docs/ring-width
       */
      "ring-w": [{
        ring: getLengthWithEmptyAndArbitrary()
      }],
      /**
       * Ring Width Inset
       * @see https://tailwindcss.com/docs/ring-width
       */
      "ring-w-inset": ["ring-inset"],
      /**
       * Ring Color
       * @see https://tailwindcss.com/docs/ring-color
       */
      "ring-color": [{
        ring: [colors]
      }],
      /**
       * Ring Opacity
       * @see https://tailwindcss.com/docs/ring-opacity
       */
      "ring-opacity": [{
        "ring-opacity": [opacity]
      }],
      /**
       * Ring Offset Width
       * @see https://tailwindcss.com/docs/ring-offset-width
       */
      "ring-offset-w": [{
        "ring-offset": [isLength, isArbitraryLength]
      }],
      /**
       * Ring Offset Color
       * @see https://tailwindcss.com/docs/ring-offset-color
       */
      "ring-offset-color": [{
        "ring-offset": [colors]
      }],
      // Effects
      /**
       * Box Shadow
       * @see https://tailwindcss.com/docs/box-shadow
       */
      shadow: [{
        shadow: ["", "inner", "none", isTshirtSize, isArbitraryShadow]
      }],
      /**
       * Box Shadow Color
       * @see https://tailwindcss.com/docs/box-shadow-color
       */
      "shadow-color": [{
        shadow: [isAny]
      }],
      /**
       * Opacity
       * @see https://tailwindcss.com/docs/opacity
       */
      opacity: [{
        opacity: [opacity]
      }],
      /**
       * Mix Blend Mode
       * @see https://tailwindcss.com/docs/mix-blend-mode
       */
      "mix-blend": [{
        "mix-blend": [...getBlendModes(), "plus-lighter", "plus-darker"]
      }],
      /**
       * Background Blend Mode
       * @see https://tailwindcss.com/docs/background-blend-mode
       */
      "bg-blend": [{
        "bg-blend": getBlendModes()
      }],
      // Filters
      /**
       * Filter
       * @deprecated since Tailwind CSS v3.0.0
       * @see https://tailwindcss.com/docs/filter
       */
      filter: [{
        filter: ["", "none"]
      }],
      /**
       * Blur
       * @see https://tailwindcss.com/docs/blur
       */
      blur: [{
        blur: [blur]
      }],
      /**
       * Brightness
       * @see https://tailwindcss.com/docs/brightness
       */
      brightness: [{
        brightness: [brightness]
      }],
      /**
       * Contrast
       * @see https://tailwindcss.com/docs/contrast
       */
      contrast: [{
        contrast: [contrast]
      }],
      /**
       * Drop Shadow
       * @see https://tailwindcss.com/docs/drop-shadow
       */
      "drop-shadow": [{
        "drop-shadow": ["", "none", isTshirtSize, isArbitraryValue]
      }],
      /**
       * Grayscale
       * @see https://tailwindcss.com/docs/grayscale
       */
      grayscale: [{
        grayscale: [grayscale]
      }],
      /**
       * Hue Rotate
       * @see https://tailwindcss.com/docs/hue-rotate
       */
      "hue-rotate": [{
        "hue-rotate": [hueRotate]
      }],
      /**
       * Invert
       * @see https://tailwindcss.com/docs/invert
       */
      invert: [{
        invert: [invert]
      }],
      /**
       * Saturate
       * @see https://tailwindcss.com/docs/saturate
       */
      saturate: [{
        saturate: [saturate]
      }],
      /**
       * Sepia
       * @see https://tailwindcss.com/docs/sepia
       */
      sepia: [{
        sepia: [sepia]
      }],
      /**
       * Backdrop Filter
       * @deprecated since Tailwind CSS v3.0.0
       * @see https://tailwindcss.com/docs/backdrop-filter
       */
      "backdrop-filter": [{
        "backdrop-filter": ["", "none"]
      }],
      /**
       * Backdrop Blur
       * @see https://tailwindcss.com/docs/backdrop-blur
       */
      "backdrop-blur": [{
        "backdrop-blur": [blur]
      }],
      /**
       * Backdrop Brightness
       * @see https://tailwindcss.com/docs/backdrop-brightness
       */
      "backdrop-brightness": [{
        "backdrop-brightness": [brightness]
      }],
      /**
       * Backdrop Contrast
       * @see https://tailwindcss.com/docs/backdrop-contrast
       */
      "backdrop-contrast": [{
        "backdrop-contrast": [contrast]
      }],
      /**
       * Backdrop Grayscale
       * @see https://tailwindcss.com/docs/backdrop-grayscale
       */
      "backdrop-grayscale": [{
        "backdrop-grayscale": [grayscale]
      }],
      /**
       * Backdrop Hue Rotate
       * @see https://tailwindcss.com/docs/backdrop-hue-rotate
       */
      "backdrop-hue-rotate": [{
        "backdrop-hue-rotate": [hueRotate]
      }],
      /**
       * Backdrop Invert
       * @see https://tailwindcss.com/docs/backdrop-invert
       */
      "backdrop-invert": [{
        "backdrop-invert": [invert]
      }],
      /**
       * Backdrop Opacity
       * @see https://tailwindcss.com/docs/backdrop-opacity
       */
      "backdrop-opacity": [{
        "backdrop-opacity": [opacity]
      }],
      /**
       * Backdrop Saturate
       * @see https://tailwindcss.com/docs/backdrop-saturate
       */
      "backdrop-saturate": [{
        "backdrop-saturate": [saturate]
      }],
      /**
       * Backdrop Sepia
       * @see https://tailwindcss.com/docs/backdrop-sepia
       */
      "backdrop-sepia": [{
        "backdrop-sepia": [sepia]
      }],
      // Tables
      /**
       * Border Collapse
       * @see https://tailwindcss.com/docs/border-collapse
       */
      "border-collapse": [{
        border: ["collapse", "separate"]
      }],
      /**
       * Border Spacing
       * @see https://tailwindcss.com/docs/border-spacing
       */
      "border-spacing": [{
        "border-spacing": [borderSpacing]
      }],
      /**
       * Border Spacing X
       * @see https://tailwindcss.com/docs/border-spacing
       */
      "border-spacing-x": [{
        "border-spacing-x": [borderSpacing]
      }],
      /**
       * Border Spacing Y
       * @see https://tailwindcss.com/docs/border-spacing
       */
      "border-spacing-y": [{
        "border-spacing-y": [borderSpacing]
      }],
      /**
       * Table Layout
       * @see https://tailwindcss.com/docs/table-layout
       */
      "table-layout": [{
        table: ["auto", "fixed"]
      }],
      /**
       * Caption Side
       * @see https://tailwindcss.com/docs/caption-side
       */
      caption: [{
        caption: ["top", "bottom"]
      }],
      // Transitions and Animation
      /**
       * Tranisition Property
       * @see https://tailwindcss.com/docs/transition-property
       */
      transition: [{
        transition: ["none", "all", "", "colors", "opacity", "shadow", "transform", isArbitraryValue]
      }],
      /**
       * Transition Duration
       * @see https://tailwindcss.com/docs/transition-duration
       */
      duration: [{
        duration: getNumberAndArbitrary()
      }],
      /**
       * Transition Timing Function
       * @see https://tailwindcss.com/docs/transition-timing-function
       */
      ease: [{
        ease: ["linear", "in", "out", "in-out", isArbitraryValue]
      }],
      /**
       * Transition Delay
       * @see https://tailwindcss.com/docs/transition-delay
       */
      delay: [{
        delay: getNumberAndArbitrary()
      }],
      /**
       * Animation
       * @see https://tailwindcss.com/docs/animation
       */
      animate: [{
        animate: ["none", "spin", "ping", "pulse", "bounce", isArbitraryValue]
      }],
      // Transforms
      /**
       * Transform
       * @see https://tailwindcss.com/docs/transform
       */
      transform: [{
        transform: ["", "gpu", "none"]
      }],
      /**
       * Scale
       * @see https://tailwindcss.com/docs/scale
       */
      scale: [{
        scale: [scale]
      }],
      /**
       * Scale X
       * @see https://tailwindcss.com/docs/scale
       */
      "scale-x": [{
        "scale-x": [scale]
      }],
      /**
       * Scale Y
       * @see https://tailwindcss.com/docs/scale
       */
      "scale-y": [{
        "scale-y": [scale]
      }],
      /**
       * Rotate
       * @see https://tailwindcss.com/docs/rotate
       */
      rotate: [{
        rotate: [isInteger, isArbitraryValue]
      }],
      /**
       * Translate X
       * @see https://tailwindcss.com/docs/translate
       */
      "translate-x": [{
        "translate-x": [translate]
      }],
      /**
       * Translate Y
       * @see https://tailwindcss.com/docs/translate
       */
      "translate-y": [{
        "translate-y": [translate]
      }],
      /**
       * Skew X
       * @see https://tailwindcss.com/docs/skew
       */
      "skew-x": [{
        "skew-x": [skew]
      }],
      /**
       * Skew Y
       * @see https://tailwindcss.com/docs/skew
       */
      "skew-y": [{
        "skew-y": [skew]
      }],
      /**
       * Transform Origin
       * @see https://tailwindcss.com/docs/transform-origin
       */
      "transform-origin": [{
        origin: ["center", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", "left", "top-left", isArbitraryValue]
      }],
      // Interactivity
      /**
       * Accent Color
       * @see https://tailwindcss.com/docs/accent-color
       */
      accent: [{
        accent: ["auto", colors]
      }],
      /**
       * Appearance
       * @see https://tailwindcss.com/docs/appearance
       */
      appearance: [{
        appearance: ["none", "auto"]
      }],
      /**
       * Cursor
       * @see https://tailwindcss.com/docs/cursor
       */
      cursor: [{
        cursor: ["auto", "default", "pointer", "wait", "text", "move", "help", "not-allowed", "none", "context-menu", "progress", "cell", "crosshair", "vertical-text", "alias", "copy", "no-drop", "grab", "grabbing", "all-scroll", "col-resize", "row-resize", "n-resize", "e-resize", "s-resize", "w-resize", "ne-resize", "nw-resize", "se-resize", "sw-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize", "zoom-in", "zoom-out", isArbitraryValue]
      }],
      /**
       * Caret Color
       * @see https://tailwindcss.com/docs/just-in-time-mode#caret-color-utilities
       */
      "caret-color": [{
        caret: [colors]
      }],
      /**
       * Pointer Events
       * @see https://tailwindcss.com/docs/pointer-events
       */
      "pointer-events": [{
        "pointer-events": ["none", "auto"]
      }],
      /**
       * Resize
       * @see https://tailwindcss.com/docs/resize
       */
      resize: [{
        resize: ["none", "y", "x", ""]
      }],
      /**
       * Scroll Behavior
       * @see https://tailwindcss.com/docs/scroll-behavior
       */
      "scroll-behavior": [{
        scroll: ["auto", "smooth"]
      }],
      /**
       * Scroll Margin
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-m": [{
        "scroll-m": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin X
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-mx": [{
        "scroll-mx": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Y
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-my": [{
        "scroll-my": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Start
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-ms": [{
        "scroll-ms": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin End
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-me": [{
        "scroll-me": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Top
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-mt": [{
        "scroll-mt": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Right
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-mr": [{
        "scroll-mr": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Bottom
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-mb": [{
        "scroll-mb": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Left
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-ml": [{
        "scroll-ml": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-p": [{
        "scroll-p": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding X
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-px": [{
        "scroll-px": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Y
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-py": [{
        "scroll-py": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Start
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-ps": [{
        "scroll-ps": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding End
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pe": [{
        "scroll-pe": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Top
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pt": [{
        "scroll-pt": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Right
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pr": [{
        "scroll-pr": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Bottom
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pb": [{
        "scroll-pb": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Left
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pl": [{
        "scroll-pl": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Snap Align
       * @see https://tailwindcss.com/docs/scroll-snap-align
       */
      "snap-align": [{
        snap: ["start", "end", "center", "align-none"]
      }],
      /**
       * Scroll Snap Stop
       * @see https://tailwindcss.com/docs/scroll-snap-stop
       */
      "snap-stop": [{
        snap: ["normal", "always"]
      }],
      /**
       * Scroll Snap Type
       * @see https://tailwindcss.com/docs/scroll-snap-type
       */
      "snap-type": [{
        snap: ["none", "x", "y", "both"]
      }],
      /**
       * Scroll Snap Type Strictness
       * @see https://tailwindcss.com/docs/scroll-snap-type
       */
      "snap-strictness": [{
        snap: ["mandatory", "proximity"]
      }],
      /**
       * Touch Action
       * @see https://tailwindcss.com/docs/touch-action
       */
      touch: [{
        touch: ["auto", "none", "manipulation"]
      }],
      /**
       * Touch Action X
       * @see https://tailwindcss.com/docs/touch-action
       */
      "touch-x": [{
        "touch-pan": ["x", "left", "right"]
      }],
      /**
       * Touch Action Y
       * @see https://tailwindcss.com/docs/touch-action
       */
      "touch-y": [{
        "touch-pan": ["y", "up", "down"]
      }],
      /**
       * Touch Action Pinch Zoom
       * @see https://tailwindcss.com/docs/touch-action
       */
      "touch-pz": ["touch-pinch-zoom"],
      /**
       * User Select
       * @see https://tailwindcss.com/docs/user-select
       */
      select: [{
        select: ["none", "text", "all", "auto"]
      }],
      /**
       * Will Change
       * @see https://tailwindcss.com/docs/will-change
       */
      "will-change": [{
        "will-change": ["auto", "scroll", "contents", "transform", isArbitraryValue]
      }],
      // SVG
      /**
       * Fill
       * @see https://tailwindcss.com/docs/fill
       */
      fill: [{
        fill: [colors, "none"]
      }],
      /**
       * Stroke Width
       * @see https://tailwindcss.com/docs/stroke-width
       */
      "stroke-w": [{
        stroke: [isLength, isArbitraryLength, isArbitraryNumber]
      }],
      /**
       * Stroke
       * @see https://tailwindcss.com/docs/stroke
       */
      stroke: [{
        stroke: [colors, "none"]
      }],
      // Accessibility
      /**
       * Screen Readers
       * @see https://tailwindcss.com/docs/screen-readers
       */
      sr: ["sr-only", "not-sr-only"],
      /**
       * Forced Color Adjust
       * @see https://tailwindcss.com/docs/forced-color-adjust
       */
      "forced-color-adjust": [{
        "forced-color-adjust": ["auto", "none"]
      }]
    },
    conflictingClassGroups: {
      overflow: ["overflow-x", "overflow-y"],
      overscroll: ["overscroll-x", "overscroll-y"],
      inset: ["inset-x", "inset-y", "start", "end", "top", "right", "bottom", "left"],
      "inset-x": ["right", "left"],
      "inset-y": ["top", "bottom"],
      flex: ["basis", "grow", "shrink"],
      gap: ["gap-x", "gap-y"],
      p: ["px", "py", "ps", "pe", "pt", "pr", "pb", "pl"],
      px: ["pr", "pl"],
      py: ["pt", "pb"],
      m: ["mx", "my", "ms", "me", "mt", "mr", "mb", "ml"],
      mx: ["mr", "ml"],
      my: ["mt", "mb"],
      size: ["w", "h"],
      "font-size": ["leading"],
      "fvn-normal": ["fvn-ordinal", "fvn-slashed-zero", "fvn-figure", "fvn-spacing", "fvn-fraction"],
      "fvn-ordinal": ["fvn-normal"],
      "fvn-slashed-zero": ["fvn-normal"],
      "fvn-figure": ["fvn-normal"],
      "fvn-spacing": ["fvn-normal"],
      "fvn-fraction": ["fvn-normal"],
      "line-clamp": ["display", "overflow"],
      rounded: ["rounded-s", "rounded-e", "rounded-t", "rounded-r", "rounded-b", "rounded-l", "rounded-ss", "rounded-se", "rounded-ee", "rounded-es", "rounded-tl", "rounded-tr", "rounded-br", "rounded-bl"],
      "rounded-s": ["rounded-ss", "rounded-es"],
      "rounded-e": ["rounded-se", "rounded-ee"],
      "rounded-t": ["rounded-tl", "rounded-tr"],
      "rounded-r": ["rounded-tr", "rounded-br"],
      "rounded-b": ["rounded-br", "rounded-bl"],
      "rounded-l": ["rounded-tl", "rounded-bl"],
      "border-spacing": ["border-spacing-x", "border-spacing-y"],
      "border-w": ["border-w-s", "border-w-e", "border-w-t", "border-w-r", "border-w-b", "border-w-l"],
      "border-w-x": ["border-w-r", "border-w-l"],
      "border-w-y": ["border-w-t", "border-w-b"],
      "border-color": ["border-color-s", "border-color-e", "border-color-t", "border-color-r", "border-color-b", "border-color-l"],
      "border-color-x": ["border-color-r", "border-color-l"],
      "border-color-y": ["border-color-t", "border-color-b"],
      "scroll-m": ["scroll-mx", "scroll-my", "scroll-ms", "scroll-me", "scroll-mt", "scroll-mr", "scroll-mb", "scroll-ml"],
      "scroll-mx": ["scroll-mr", "scroll-ml"],
      "scroll-my": ["scroll-mt", "scroll-mb"],
      "scroll-p": ["scroll-px", "scroll-py", "scroll-ps", "scroll-pe", "scroll-pt", "scroll-pr", "scroll-pb", "scroll-pl"],
      "scroll-px": ["scroll-pr", "scroll-pl"],
      "scroll-py": ["scroll-pt", "scroll-pb"],
      touch: ["touch-x", "touch-y", "touch-pz"],
      "touch-x": ["touch"],
      "touch-y": ["touch"],
      "touch-pz": ["touch"]
    },
    conflictingClassGroupModifiers: {
      "font-size": ["leading"]
    }
  };
};
const twMerge = /* @__PURE__ */ createTailwindMerge(getDefaultConfig);
function cn$1(...inputs) {
  return twMerge(clsx(inputs));
}
function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null) return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i2;
  for (i2 = 0; i2 < sourceKeys.length; i2++) {
    key = sourceKeys[i2];
    if (excluded.indexOf(key) >= 0) continue;
    target[key] = source[key];
  }
  return target;
}
var _excluded$Q = ["color"];
var CaretSortIcon = /* @__PURE__ */ reactExports.forwardRef(function(_ref, forwardedRef) {
  var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$Q);
  return reactExports.createElement("svg", Object.assign({
    width: "15",
    height: "15",
    viewBox: "0 0 15 15",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg"
  }, props, {
    ref: forwardedRef
  }), reactExports.createElement("path", {
    d: "M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",
    fill: color,
    fillRule: "evenodd",
    clipRule: "evenodd"
  }));
});
var _excluded$T = ["color"];
var CheckIcon = /* @__PURE__ */ reactExports.forwardRef(function(_ref, forwardedRef) {
  var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$T);
  return reactExports.createElement("svg", Object.assign({
    width: "15",
    height: "15",
    viewBox: "0 0 15 15",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg"
  }, props, {
    ref: forwardedRef
  }), reactExports.createElement("path", {
    d: "M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",
    fill: color,
    fillRule: "evenodd",
    clipRule: "evenodd"
  }));
});
var _excluded$W = ["color"];
var ChevronDownIcon = /* @__PURE__ */ reactExports.forwardRef(function(_ref, forwardedRef) {
  var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$W);
  return reactExports.createElement("svg", Object.assign({
    width: "15",
    height: "15",
    viewBox: "0 0 15 15",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg"
  }, props, {
    ref: forwardedRef
  }), reactExports.createElement("path", {
    d: "M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",
    fill: color,
    fillRule: "evenodd",
    clipRule: "evenodd"
  }));
});
var _excluded$Z = ["color"];
var ChevronUpIcon = /* @__PURE__ */ reactExports.forwardRef(function(_ref, forwardedRef) {
  var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$Z);
  return reactExports.createElement("svg", Object.assign({
    width: "15",
    height: "15",
    viewBox: "0 0 15 15",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg"
  }, props, {
    ref: forwardedRef
  }), reactExports.createElement("path", {
    d: "M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",
    fill: color,
    fillRule: "evenodd",
    clipRule: "evenodd"
  }));
});
var _excluded$1r = ["color"];
var Cross2Icon = /* @__PURE__ */ reactExports.forwardRef(function(_ref, forwardedRef) {
  var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$1r);
  return reactExports.createElement("svg", Object.assign({
    width: "15",
    height: "15",
    viewBox: "0 0 15 15",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg"
  }, props, {
    ref: forwardedRef
  }), reactExports.createElement("path", {
    d: "M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",
    fill: color,
    fillRule: "evenodd",
    clipRule: "evenodd"
  }));
});
var _excluded$33 = ["color"];
var MagnifyingGlassIcon = /* @__PURE__ */ reactExports.forwardRef(function(_ref, forwardedRef) {
  var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$33);
  return reactExports.createElement("svg", Object.assign({
    width: "15",
    height: "15",
    viewBox: "0 0 15 15",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg"
  }, props, {
    ref: forwardedRef
  }), reactExports.createElement("path", {
    d: "M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",
    fill: color,
    fillRule: "evenodd",
    clipRule: "evenodd"
  }));
});
const ToastProvider = Provider$1;
const ToastViewport = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Viewport$1,
  {
    ref: ref2,
    className: cn$1(
      "fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
      className
    ),
    ...props
  }
));
ToastViewport.displayName = Viewport$1.displayName;
const toastVariants = cva(
  "group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
  {
    variants: {
      variant: {
        default: "border bg-background text-foreground",
        destructive: "destructive group border-destructive bg-destructive text-destructive-foreground"
      }
    },
    defaultVariants: {
      variant: "default"
    }
  }
);
const Toast = reactExports.forwardRef(({ className, variant, ...props }, ref2) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    Root2$4,
    {
      ref: ref2,
      className: cn$1(toastVariants({ variant }), className),
      ...props
    }
  );
});
Toast.displayName = Root2$4.displayName;
const ToastAction = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Action,
  {
    ref: ref2,
    className: cn$1(
      "inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
      className
    ),
    ...props
  }
));
ToastAction.displayName = Action.displayName;
const ToastClose = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Close$1,
  {
    ref: ref2,
    className: cn$1(
      "absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
      className
    ),
    "toast-close": "",
    ...props,
    children: /* @__PURE__ */ jsxRuntimeExports.jsx(Cross2Icon, { className: "h-4 w-4" })
  }
));
ToastClose.displayName = Close$1.displayName;
const ToastTitle = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Title$1,
  {
    ref: ref2,
    className: cn$1("text-sm font-semibold [&+div]:text-xs", className),
    ...props
  }
));
ToastTitle.displayName = Title$1.displayName;
const ToastDescription = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Description$1,
  {
    ref: ref2,
    className: cn$1("text-sm opacity-90", className),
    ...props
  }
));
ToastDescription.displayName = Description$1.displayName;
function Toaster() {
  const { toasts } = useToast();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(ToastProvider, { children: [
    toasts.map(function({ id: id2, title: title2, description: description2, action, ...props }) {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(Toast, { ...props, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1", children: [
          title2 && /* @__PURE__ */ jsxRuntimeExports.jsx(ToastTitle, { children: title2 }),
          description2 && /* @__PURE__ */ jsxRuntimeExports.jsx(ToastDescription, { children: description2 })
        ] }),
        action,
        /* @__PURE__ */ jsxRuntimeExports.jsx(ToastClose, {})
      ] }, id2);
    }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ToastViewport, {})
  ] });
}
const scriptRel = "modulepreload";
const assetsURL = function(dep) {
  return "/" + dep;
};
const seen = {};
const __vitePreload = function preload(baseModule, deps, importerUrl) {
  let promise = Promise.resolve();
  if (deps && deps.length > 0) {
    let allSettled = function(promises$2) {
      return Promise.all(promises$2.map((p2) => Promise.resolve(p2).then((value$1) => ({
        status: "fulfilled",
        value: value$1
      }), (reason) => ({
        status: "rejected",
        reason
      }))));
    };
    document.getElementsByTagName("link");
    const cspNonceMeta = document.querySelector("meta[property=csp-nonce]");
    const cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce");
    promise = allSettled(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(/* @__PURE__ */ new Error(`Unable to preload CSS for ${dep}`)));
      });
    }));
  }
  function handlePreloadError(err$2) {
    const e$1 = new Event("vite:preloadError", { cancelable: true });
    e$1.payload = err$2;
    window.dispatchEvent(e$1);
    if (!e$1.defaultPrevented) throw err$2;
  }
  return promise.then((res) => {
    for (const item of res || []) {
      if (item.status !== "rejected") continue;
      handlePreloadError(item.reason);
    }
    return baseModule().catch(handlePreloadError);
  });
};
const NEVER = Object.freeze({
  status: "aborted"
});
function $constructor(name2, initializer2, params) {
  function init(inst, def) {
    var _a2;
    Object.defineProperty(inst, "_zod", {
      value: inst._zod ?? {},
      enumerable: false
    });
    (_a2 = inst._zod).traits ?? (_a2.traits = /* @__PURE__ */ new Set());
    inst._zod.traits.add(name2);
    initializer2(inst, def);
    for (const k2 in _2.prototype) {
      if (!(k2 in inst))
        Object.defineProperty(inst, k2, { value: _2.prototype[k2].bind(inst) });
    }
    inst._zod.constr = _2;
    inst._zod.def = def;
  }
  const Parent = params?.Parent ?? Object;
  class Definition extends Parent {
  }
  Object.defineProperty(Definition, "name", { value: name2 });
  function _2(def) {
    var _a2;
    const inst = params?.Parent ? new Definition() : this;
    init(inst, def);
    (_a2 = inst._zod).deferred ?? (_a2.deferred = []);
    for (const fn2 of inst._zod.deferred) {
      fn2();
    }
    return inst;
  }
  Object.defineProperty(_2, "init", { value: init });
  Object.defineProperty(_2, Symbol.hasInstance, {
    value: (inst) => {
      if (params?.Parent && inst instanceof params.Parent)
        return true;
      return inst?._zod?.traits?.has(name2);
    }
  });
  Object.defineProperty(_2, "name", { value: name2 });
  return _2;
}
class $ZodAsyncError extends Error {
  constructor() {
    super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
  }
}
const globalConfig = {};
function config(newConfig) {
  return globalConfig;
}
function getEnumValues(entries) {
  const numericValues = Object.values(entries).filter((v2) => typeof v2 === "number");
  const values = Object.entries(entries).filter(([k2, _2]) => numericValues.indexOf(+k2) === -1).map(([_2, v2]) => v2);
  return values;
}
function jsonStringifyReplacer(_2, value) {
  if (typeof value === "bigint")
    return value.toString();
  return value;
}
function cached(getter) {
  return {
    get value() {
      {
        const value = getter();
        Object.defineProperty(this, "value", { value });
        return value;
      }
    }
  };
}
function nullish(input) {
  return input === null || input === void 0;
}
function cleanRegex(source) {
  const start = source.startsWith("^") ? 1 : 0;
  const end = source.endsWith("$") ? source.length - 1 : source.length;
  return source.slice(start, end);
}
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;
}
function defineLazy(object2, key, getter) {
  Object.defineProperty(object2, key, {
    get() {
      {
        const value = getter();
        object2[key] = value;
        return value;
      }
    },
    set(v2) {
      Object.defineProperty(object2, key, {
        value: v2
        // configurable: true,
      });
    },
    configurable: true
  });
}
function assignProp(target, prop, value) {
  Object.defineProperty(target, prop, {
    value,
    writable: true,
    enumerable: true,
    configurable: true
  });
}
function esc(str) {
  return JSON.stringify(str);
}
const captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => {
};
function isObject(data2) {
  return typeof data2 === "object" && data2 !== null && !Array.isArray(data2);
}
const allowsEval = cached(() => {
  if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
    return false;
  }
  try {
    const F2 = Function;
    new F2("");
    return true;
  } catch (_2) {
    return false;
  }
});
function isPlainObject$2(o2) {
  if (isObject(o2) === false)
    return false;
  const ctor = o2.constructor;
  if (ctor === void 0)
    return true;
  const prot = ctor.prototype;
  if (isObject(prot) === false)
    return false;
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
    return false;
  }
  return true;
}
const propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone(inst, def, params) {
  const cl2 = new inst._zod.constr(def ?? inst._zod.def);
  if (!def || params?.parent)
    cl2._zod.parent = inst;
  return cl2;
}
function normalizeParams(_params) {
  const params = _params;
  if (!params)
    return {};
  if (typeof params === "string")
    return { error: () => params };
  if (params?.message !== void 0) {
    if (params?.error !== void 0)
      throw new Error("Cannot specify both `message` and `error` params");
    params.error = params.message;
  }
  delete params.message;
  if (typeof params.error === "string")
    return { ...params, error: () => params.error };
  return params;
}
function optionalKeys(shape) {
  return Object.keys(shape).filter((k2) => {
    return shape[k2]._zod.optin === "optional" && shape[k2]._zod.optout === "optional";
  });
}
const NUMBER_FORMAT_RANGES = {
  safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
  int32: [-2147483648, 2147483647],
  uint32: [0, 4294967295],
  float32: [-34028234663852886e22, 34028234663852886e22],
  float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
};
function pick(schema, mask) {
  const newShape = {};
  const currDef = schema._zod.def;
  for (const key in mask) {
    if (!(key in currDef.shape)) {
      throw new Error(`Unrecognized key: "${key}"`);
    }
    if (!mask[key])
      continue;
    newShape[key] = currDef.shape[key];
  }
  return clone(schema, {
    ...schema._zod.def,
    shape: newShape,
    checks: []
  });
}
function omit(schema, mask) {
  const newShape = { ...schema._zod.def.shape };
  const currDef = schema._zod.def;
  for (const key in mask) {
    if (!(key in currDef.shape)) {
      throw new Error(`Unrecognized key: "${key}"`);
    }
    if (!mask[key])
      continue;
    delete newShape[key];
  }
  return clone(schema, {
    ...schema._zod.def,
    shape: newShape,
    checks: []
  });
}
function extend(schema, shape) {
  if (!isPlainObject$2(shape)) {
    throw new Error("Invalid input to extend: expected a plain object");
  }
  const def = {
    ...schema._zod.def,
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape };
      assignProp(this, "shape", _shape);
      return _shape;
    },
    checks: []
    // delete existing checks
  };
  return clone(schema, def);
}
function merge(a2, b2) {
  return clone(a2, {
    ...a2._zod.def,
    get shape() {
      const _shape = { ...a2._zod.def.shape, ...b2._zod.def.shape };
      assignProp(this, "shape", _shape);
      return _shape;
    },
    catchall: b2._zod.def.catchall,
    checks: []
    // delete existing checks
  });
}
function partial(Class, schema, mask) {
  const oldShape = schema._zod.def.shape;
  const shape = { ...oldShape };
  if (mask) {
    for (const key in mask) {
      if (!(key in oldShape)) {
        throw new Error(`Unrecognized key: "${key}"`);
      }
      if (!mask[key])
        continue;
      shape[key] = Class ? new Class({
        type: "optional",
        innerType: oldShape[key]
      }) : oldShape[key];
    }
  } else {
    for (const key in oldShape) {
      shape[key] = Class ? new Class({
        type: "optional",
        innerType: oldShape[key]
      }) : oldShape[key];
    }
  }
  return clone(schema, {
    ...schema._zod.def,
    shape,
    checks: []
  });
}
function required$6(Class, schema, mask) {
  const oldShape = schema._zod.def.shape;
  const shape = { ...oldShape };
  if (mask) {
    for (const key in mask) {
      if (!(key in shape)) {
        throw new Error(`Unrecognized key: "${key}"`);
      }
      if (!mask[key])
        continue;
      shape[key] = new Class({
        type: "nonoptional",
        innerType: oldShape[key]
      });
    }
  } else {
    for (const key in oldShape) {
      shape[key] = new Class({
        type: "nonoptional",
        innerType: oldShape[key]
      });
    }
  }
  return clone(schema, {
    ...schema._zod.def,
    shape,
    // optional: [],
    checks: []
  });
}
function aborted(x2, startIndex = 0) {
  for (let i2 = startIndex; i2 < x2.issues.length; i2++) {
    if (x2.issues[i2]?.continue !== true)
      return true;
  }
  return false;
}
function prefixIssues(path, issues) {
  return issues.map((iss) => {
    var _a2;
    (_a2 = iss).path ?? (_a2.path = []);
    iss.path.unshift(path);
    return iss;
  });
}
function unwrapMessage(message) {
  return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config2) {
  const full = { ...iss, path: iss.path ?? [] };
  if (!iss.message) {
    const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
    full.message = message;
  }
  delete full.inst;
  delete full.continue;
  if (!ctx?.reportInput) {
    delete full.input;
  }
  return full;
}
function getLengthableOrigin(input) {
  if (Array.isArray(input))
    return "array";
  if (typeof input === "string")
    return "string";
  return "unknown";
}
function issue(...args) {
  const [iss, input, inst] = args;
  if (typeof iss === "string") {
    return {
      message: iss,
      code: "custom",
      input,
      inst
    };
  }
  return { ...iss };
}
const initializer$1 = (inst, def) => {
  inst.name = "$ZodError";
  Object.defineProperty(inst, "_zod", {
    value: inst._zod,
    enumerable: false
  });
  Object.defineProperty(inst, "issues", {
    value: def,
    enumerable: false
  });
  Object.defineProperty(inst, "message", {
    get() {
      return JSON.stringify(def, jsonStringifyReplacer, 2);
    },
    enumerable: true
    // configurable: false,
  });
  Object.defineProperty(inst, "toString", {
    value: () => inst.message,
    enumerable: false
  });
};
const $ZodError = $constructor("$ZodError", initializer$1);
const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
function flattenError$1(error, mapper = (issue2) => issue2.message) {
  const fieldErrors = {};
  const formErrors = [];
  for (const sub of error.issues) {
    if (sub.path.length > 0) {
      fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
      fieldErrors[sub.path[0]].push(mapper(sub));
    } else {
      formErrors.push(mapper(sub));
    }
  }
  return { formErrors, fieldErrors };
}
function formatError(error, _mapper) {
  const mapper = _mapper || function(issue2) {
    return issue2.message;
  };
  const fieldErrors = { _errors: [] };
  const processError = (error2) => {
    for (const issue2 of error2.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues });
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues });
      } else if (issue2.path.length === 0) {
        fieldErrors._errors.push(mapper(issue2));
      } else {
        let curr = fieldErrors;
        let i2 = 0;
        while (i2 < issue2.path.length) {
          const el2 = issue2.path[i2];
          const terminal = i2 === issue2.path.length - 1;
          if (!terminal) {
            curr[el2] = curr[el2] || { _errors: [] };
          } else {
            curr[el2] = curr[el2] || { _errors: [] };
            curr[el2]._errors.push(mapper(issue2));
          }
          curr = curr[el2];
          i2++;
        }
      }
    }
  };
  processError(error);
  return fieldErrors;
}
const _parse = (_Err) => (schema, value, _ctx, _params) => {
  const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
  const result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise) {
    throw new $ZodAsyncError();
  }
  if (result.issues.length) {
    const e2 = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e2, _params?.callee);
    throw e2;
  }
  return result.value;
};
const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
  const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
  let result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise)
    result = await result;
  if (result.issues.length) {
    const e2 = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e2, params?.callee);
    throw e2;
  }
  return result.value;
};
const _safeParse = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
  const result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise) {
    throw new $ZodAsyncError();
  }
  return result.issues.length ? {
    success: false,
    error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  } : { success: true, data: result.value };
};
const safeParse$2 = /* @__PURE__ */ _safeParse($ZodRealError);
const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
  let result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise)
    result = await result;
  return result.issues.length ? {
    success: false,
    error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  } : { success: true, data: result.value };
};
const safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync($ZodRealError);
const cuid = /^[cC][^\s-]{8,}$/;
const cuid2 = /^[0-9a-z]+$/;
const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
const xid = /^[0-9a-vA-V]{20}$/;
const ksuid = /^[A-Za-z0-9]{27}$/;
const nanoid = /^[a-zA-Z0-9_-]{21}$/;
const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
const uuid = (version2) => {
  if (!version2)
    return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;
  return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
function emoji() {
  return new RegExp(_emoji$1, "u");
}
const ipv4 = /^(?:(?: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 ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;
const cidrv4 = /^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/;
const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
const base64url = /^[A-Za-z0-9_-]*$/;
const hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
const e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
const dateSource = `(?:(?:\\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 date$1 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
function timeSource(args) {
  const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
  const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
  return regex;
}
function time$1(args) {
  return new RegExp(`^${timeSource(args)}$`);
}
function datetime$1(args) {
  const time2 = timeSource({ precision: args.precision });
  const opts = ["Z"];
  if (args.local)
    opts.push("");
  if (args.offset)
    opts.push(`([+-]\\d{2}:\\d{2})`);
  const timeRegex2 = `${time2}(?:${opts.join("|")})`;
  return new RegExp(`^${dateSource}T(?:${timeRegex2})$`);
}
const string$1 = (params) => {
  const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
  return new RegExp(`^${regex}$`);
};
const integer = /^\d+$/;
const number$2 = /^-?\d+(?:\.\d+)?/i;
const boolean$1 = /true|false/i;
const _null$2 = /null/i;
const _undefined$2 = /undefined/i;
const lowercase = /^[^A-Z]*$/;
const uppercase = /^[^a-z]*$/;
const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
  var _a2;
  inst._zod ?? (inst._zod = {});
  inst._zod.def = def;
  (_a2 = inst._zod).onattach ?? (_a2.onattach = []);
});
const numericOriginMap = {
  number: "number",
  bigint: "bigint",
  object: "date"
};
const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
  $ZodCheck.init(inst, def);
  const origin = numericOriginMap[typeof def.value];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
    if (def.value < curr) {
      if (def.inclusive)
        bag.maximum = def.value;
      else
        bag.exclusiveMaximum = def.value;
    }
  });
  inst._zod.check = (payload) => {
    if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
      return;
    }
    payload.issues.push({
      origin,
      code: "too_big",
      maximum: def.value,
      input: payload.value,
      inclusive: def.inclusive,
      inst,
      continue: !def.abort
    });
  };
});
const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
  $ZodCheck.init(inst, def);
  const origin = numericOriginMap[typeof def.value];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
    if (def.value > curr) {
      if (def.inclusive)
        bag.minimum = def.value;
      else
        bag.exclusiveMinimum = def.value;
    }
  });
  inst._zod.check = (payload) => {
    if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
      return;
    }
    payload.issues.push({
      origin,
      code: "too_small",
      minimum: def.value,
      input: payload.value,
      inclusive: def.inclusive,
      inst,
      continue: !def.abort
    });
  };
});
const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    var _a2;
    (_a2 = inst2._zod.bag).multipleOf ?? (_a2.multipleOf = def.value);
  });
  inst._zod.check = (payload) => {
    if (typeof payload.value !== typeof def.value)
      throw new Error("Cannot mix number and bigint in multiple_of check.");
    const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder$1(payload.value, def.value) === 0;
    if (isMultiple)
      return;
    payload.issues.push({
      origin: typeof payload.value,
      code: "not_multiple_of",
      divisor: def.value,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
  $ZodCheck.init(inst, def);
  def.format = def.format || "float64";
  const isInt = def.format?.includes("int");
  const origin = isInt ? "int" : "number";
  const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    bag.minimum = minimum;
    bag.maximum = maximum;
    if (isInt)
      bag.pattern = integer;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    if (isInt) {
      if (!Number.isInteger(input)) {
        payload.issues.push({
          expected: origin,
          format: def.format,
          code: "invalid_type",
          input,
          inst
        });
        return;
      }
      if (!Number.isSafeInteger(input)) {
        if (input > 0) {
          payload.issues.push({
            input,
            code: "too_big",
            maximum: Number.MAX_SAFE_INTEGER,
            note: "Integers must be within the safe integer range.",
            inst,
            origin,
            continue: !def.abort
          });
        } else {
          payload.issues.push({
            input,
            code: "too_small",
            minimum: Number.MIN_SAFE_INTEGER,
            note: "Integers must be within the safe integer range.",
            inst,
            origin,
            continue: !def.abort
          });
        }
        return;
      }
    }
    if (input < minimum) {
      payload.issues.push({
        origin: "number",
        input,
        code: "too_small",
        minimum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
    if (input > maximum) {
      payload.issues.push({
        origin: "number",
        input,
        code: "too_big",
        maximum,
        inst
      });
    }
  };
});
const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
  var _a2;
  $ZodCheck.init(inst, def);
  (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
    if (def.maximum < curr)
      inst2._zod.bag.maximum = def.maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length = input.length;
    if (length <= def.maximum)
      return;
    const origin = getLengthableOrigin(input);
    payload.issues.push({
      origin,
      code: "too_big",
      maximum: def.maximum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
const $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
  var _a2;
  $ZodCheck.init(inst, def);
  (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
    if (def.minimum > curr)
      inst2._zod.bag.minimum = def.minimum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length = input.length;
    if (length >= def.minimum)
      return;
    const origin = getLengthableOrigin(input);
    payload.issues.push({
      origin,
      code: "too_small",
      minimum: def.minimum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
const $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
  var _a2;
  $ZodCheck.init(inst, def);
  (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.minimum = def.length;
    bag.maximum = def.length;
    bag.length = def.length;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length = input.length;
    if (length === def.length)
      return;
    const origin = getLengthableOrigin(input);
    const tooBig = length > def.length;
    payload.issues.push({
      origin,
      ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length },
      inclusive: true,
      exact: true,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
const $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
  var _a2, _b;
  $ZodCheck.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    if (def.pattern) {
      bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
      bag.patterns.add(def.pattern);
    }
  });
  if (def.pattern)
    (_a2 = inst._zod).check ?? (_a2.check = (payload) => {
      def.pattern.lastIndex = 0;
      if (def.pattern.test(payload.value))
        return;
      payload.issues.push({
        origin: "string",
        code: "invalid_format",
        format: def.format,
        input: payload.value,
        ...def.pattern ? { pattern: def.pattern.toString() } : {},
        inst,
        continue: !def.abort
      });
    });
  else
    (_b = inst._zod).check ?? (_b.check = () => {
    });
});
const $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
  $ZodCheckStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    def.pattern.lastIndex = 0;
    if (def.pattern.test(payload.value))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "regex",
      input: payload.value,
      pattern: def.pattern.toString(),
      inst,
      continue: !def.abort
    });
  };
});
const $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
  def.pattern ?? (def.pattern = lowercase);
  $ZodCheckStringFormat.init(inst, def);
});
const $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
  def.pattern ?? (def.pattern = uppercase);
  $ZodCheckStringFormat.init(inst, def);
});
const $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
  $ZodCheck.init(inst, def);
  const escapedRegex = escapeRegex(def.includes);
  const pattern2 = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
  def.pattern = pattern2;
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
    bag.patterns.add(pattern2);
  });
  inst._zod.check = (payload) => {
    if (payload.value.includes(def.includes, def.position))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "includes",
      includes: def.includes,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
const $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
  $ZodCheck.init(inst, def);
  const pattern2 = new RegExp(`^${escapeRegex(def.prefix)}.*`);
  def.pattern ?? (def.pattern = pattern2);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
    bag.patterns.add(pattern2);
  });
  inst._zod.check = (payload) => {
    if (payload.value.startsWith(def.prefix))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "starts_with",
      prefix: def.prefix,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
const $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
  $ZodCheck.init(inst, def);
  const pattern2 = new RegExp(`.*${escapeRegex(def.suffix)}$`);
  def.pattern ?? (def.pattern = pattern2);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
    bag.patterns.add(pattern2);
  });
  inst._zod.check = (payload) => {
    if (payload.value.endsWith(def.suffix))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "ends_with",
      suffix: def.suffix,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.check = (payload) => {
    payload.value = def.tx(payload.value);
  };
});
class Doc {
  constructor(args = []) {
    this.content = [];
    this.indent = 0;
    if (this)
      this.args = args;
  }
  indented(fn2) {
    this.indent += 1;
    fn2(this);
    this.indent -= 1;
  }
  write(arg) {
    if (typeof arg === "function") {
      arg(this, { execution: "sync" });
      arg(this, { execution: "async" });
      return;
    }
    const content = arg;
    const lines = content.split("\n").filter((x2) => x2);
    const minIndent = Math.min(...lines.map((x2) => x2.length - x2.trimStart().length));
    const dedented = lines.map((x2) => x2.slice(minIndent)).map((x2) => " ".repeat(this.indent * 2) + x2);
    for (const line of dedented) {
      this.content.push(line);
    }
  }
  compile() {
    const F2 = Function;
    const args = this?.args;
    const content = this?.content ?? [``];
    const lines = [...content.map((x2) => `  ${x2}`)];
    return new F2(...args, lines.join("\n"));
  }
}
const version$2 = {
  major: 4,
  minor: 0,
  patch: 0
};
const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
  var _a2;
  inst ?? (inst = {});
  inst._zod.def = def;
  inst._zod.bag = inst._zod.bag || {};
  inst._zod.version = version$2;
  const checks = [...inst._zod.def.checks ?? []];
  if (inst._zod.traits.has("$ZodCheck")) {
    checks.unshift(inst);
  }
  for (const ch of checks) {
    for (const fn2 of ch._zod.onattach) {
      fn2(inst);
    }
  }
  if (checks.length === 0) {
    (_a2 = inst._zod).deferred ?? (_a2.deferred = []);
    inst._zod.deferred?.push(() => {
      inst._zod.run = inst._zod.parse;
    });
  } else {
    const runChecks = (payload, checks2, ctx) => {
      let isAborted2 = aborted(payload);
      let asyncResult;
      for (const ch of checks2) {
        if (ch._zod.def.when) {
          const shouldRun = ch._zod.def.when(payload);
          if (!shouldRun)
            continue;
        } else if (isAborted2) {
          continue;
        }
        const currLen = payload.issues.length;
        const _2 = ch._zod.check(payload);
        if (_2 instanceof Promise && ctx?.async === false) {
          throw new $ZodAsyncError();
        }
        if (asyncResult || _2 instanceof Promise) {
          asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
            await _2;
            const nextLen = payload.issues.length;
            if (nextLen === currLen)
              return;
            if (!isAborted2)
              isAborted2 = aborted(payload, currLen);
          });
        } else {
          const nextLen = payload.issues.length;
          if (nextLen === currLen)
            continue;
          if (!isAborted2)
            isAborted2 = aborted(payload, currLen);
        }
      }
      if (asyncResult) {
        return asyncResult.then(() => {
          return payload;
        });
      }
      return payload;
    };
    inst._zod.run = (payload, ctx) => {
      const result = inst._zod.parse(payload, ctx);
      if (result instanceof Promise) {
        if (ctx.async === false)
          throw new $ZodAsyncError();
        return result.then((result2) => runChecks(result2, checks, ctx));
      }
      return runChecks(result, checks, ctx);
    };
  }
  inst["~standard"] = {
    validate: (value) => {
      try {
        const r2 = safeParse$2(inst, value);
        return r2.success ? { value: r2.data } : { issues: r2.error?.issues };
      } catch (_2) {
        return safeParseAsync$1(inst, value).then((r2) => r2.success ? { value: r2.data } : { issues: r2.error?.issues });
      }
    },
    vendor: "zod",
    version: 1
  };
});
const $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag);
  inst._zod.parse = (payload, _2) => {
    if (def.coerce)
      try {
        payload.value = String(payload.value);
      } catch (_3) {
      }
    if (typeof payload.value === "string")
      return payload;
    payload.issues.push({
      expected: "string",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
const $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
  $ZodCheckStringFormat.init(inst, def);
  $ZodString.init(inst, def);
});
const $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
  def.pattern ?? (def.pattern = guid);
  $ZodStringFormat.init(inst, def);
});
const $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
  if (def.version) {
    const versionMap = {
      v1: 1,
      v2: 2,
      v3: 3,
      v4: 4,
      v5: 5,
      v6: 6,
      v7: 7,
      v8: 8
    };
    const v2 = versionMap[def.version];
    if (v2 === void 0)
      throw new Error(`Invalid UUID version: "${def.version}"`);
    def.pattern ?? (def.pattern = uuid(v2));
  } else
    def.pattern ?? (def.pattern = uuid());
  $ZodStringFormat.init(inst, def);
});
const $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
  def.pattern ?? (def.pattern = email);
  $ZodStringFormat.init(inst, def);
});
const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    try {
      const orig = payload.value;
      const url2 = new URL(orig);
      const href = url2.href;
      if (def.hostname) {
        def.hostname.lastIndex = 0;
        if (!def.hostname.test(url2.hostname)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid hostname",
            pattern: hostname.source,
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      }
      if (def.protocol) {
        def.protocol.lastIndex = 0;
        if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid protocol",
            pattern: def.protocol.source,
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      }
      if (!orig.endsWith("/") && href.endsWith("/")) {
        payload.value = href.slice(0, -1);
      } else {
        payload.value = href;
      }
      return;
    } catch (_2) {
      payload.issues.push({
        code: "invalid_format",
        format: "url",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
const $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
  def.pattern ?? (def.pattern = emoji());
  $ZodStringFormat.init(inst, def);
});
const $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
  def.pattern ?? (def.pattern = nanoid);
  $ZodStringFormat.init(inst, def);
});
const $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
  def.pattern ?? (def.pattern = cuid);
  $ZodStringFormat.init(inst, def);
});
const $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
  def.pattern ?? (def.pattern = cuid2);
  $ZodStringFormat.init(inst, def);
});
const $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
  def.pattern ?? (def.pattern = ulid);
  $ZodStringFormat.init(inst, def);
});
const $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
  def.pattern ?? (def.pattern = xid);
  $ZodStringFormat.init(inst, def);
});
const $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
  def.pattern ?? (def.pattern = ksuid);
  $ZodStringFormat.init(inst, def);
});
const $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
  def.pattern ?? (def.pattern = datetime$1(def));
  $ZodStringFormat.init(inst, def);
});
const $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
  def.pattern ?? (def.pattern = date$1);
  $ZodStringFormat.init(inst, def);
});
const $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
  def.pattern ?? (def.pattern = time$1(def));
  $ZodStringFormat.init(inst, def);
});
const $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
  def.pattern ?? (def.pattern = duration$1);
  $ZodStringFormat.init(inst, def);
});
const $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
  def.pattern ?? (def.pattern = ipv4);
  $ZodStringFormat.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = `ipv4`;
  });
});
const $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
  def.pattern ?? (def.pattern = ipv6);
  $ZodStringFormat.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = `ipv6`;
  });
  inst._zod.check = (payload) => {
    try {
      new URL(`http://[${payload.value}]`);
    } catch {
      payload.issues.push({
        code: "invalid_format",
        format: "ipv6",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
const $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
  def.pattern ?? (def.pattern = cidrv4);
  $ZodStringFormat.init(inst, def);
});
const $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
  def.pattern ?? (def.pattern = cidrv6);
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    const [address, prefix] = payload.value.split("/");
    try {
      if (!prefix)
        throw new Error();
      const prefixNum = Number(prefix);
      if (`${prefixNum}` !== prefix)
        throw new Error();
      if (prefixNum < 0 || prefixNum > 128)
        throw new Error();
      new URL(`http://[${address}]`);
    } catch {
      payload.issues.push({
        code: "invalid_format",
        format: "cidrv6",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
function isValidBase64(data2) {
  if (data2 === "")
    return true;
  if (data2.length % 4 !== 0)
    return false;
  try {
    atob(data2);
    return true;
  } catch {
    return false;
  }
}
const $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
  def.pattern ?? (def.pattern = base64);
  $ZodStringFormat.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    inst2._zod.bag.contentEncoding = "base64";
  });
  inst._zod.check = (payload) => {
    if (isValidBase64(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "base64",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
function isValidBase64URL(data2) {
  if (!base64url.test(data2))
    return false;
  const base642 = data2.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
  const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "=");
  return isValidBase64(padded);
}
const $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
  def.pattern ?? (def.pattern = base64url);
  $ZodStringFormat.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    inst2._zod.bag.contentEncoding = "base64url";
  });
  inst._zod.check = (payload) => {
    if (isValidBase64URL(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "base64url",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
const $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
  def.pattern ?? (def.pattern = e164);
  $ZodStringFormat.init(inst, def);
});
function isValidJWT$1(token, algorithm = null) {
  try {
    const tokensParts = token.split(".");
    if (tokensParts.length !== 3)
      return false;
    const [header] = tokensParts;
    if (!header)
      return false;
    const parsedHeader = JSON.parse(atob(header));
    if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
      return false;
    if (!parsedHeader.alg)
      return false;
    if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
      return false;
    return true;
  } catch {
    return false;
  }
}
const $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    if (isValidJWT$1(payload.value, def.alg))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "jwt",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
const $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = inst._zod.bag.pattern ?? number$2;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = Number(payload.value);
      } catch (_2) {
      }
    const input = payload.value;
    if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
      return payload;
    }
    const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
    payload.issues.push({
      expected: "number",
      code: "invalid_type",
      input,
      inst,
      ...received ? { received } : {}
    });
    return payload;
  };
});
const $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
  $ZodCheckNumberFormat.init(inst, def);
  $ZodNumber.init(inst, def);
});
const $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = boolean$1;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = Boolean(payload.value);
      } catch (_2) {
      }
    const input = payload.value;
    if (typeof input === "boolean")
      return payload;
    payload.issues.push({
      expected: "boolean",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
const $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = _undefined$2;
  inst._zod.values = /* @__PURE__ */ new Set([void 0]);
  inst._zod.optin = "optional";
  inst._zod.optout = "optional";
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "undefined")
      return payload;
    payload.issues.push({
      expected: "undefined",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
const $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = _null$2;
  inst._zod.values = /* @__PURE__ */ new Set([null]);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (input === null)
      return payload;
    payload.issues.push({
      expected: "null",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
const $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload) => payload;
});
const $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload) => payload;
});
const $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    payload.issues.push({
      expected: "never",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
function handleArrayResult(result, final, index2) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index2, result.issues));
  }
  final.value[index2] = result.value;
}
const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!Array.isArray(input)) {
      payload.issues.push({
        expected: "array",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    payload.value = Array(input.length);
    const proms = [];
    for (let i2 = 0; i2 < input.length; i2++) {
      const item = input[i2];
      const result = def.element._zod.run({
        value: item,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result2) => handleArrayResult(result2, payload, i2)));
      } else {
        handleArrayResult(result, payload, i2);
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
function handleObjectResult(result, final, key) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(key, result.issues));
  }
  final.value[key] = result.value;
}
function handleOptionalObjectResult(result, final, key, input) {
  if (result.issues.length) {
    if (input[key] === void 0) {
      if (key in input) {
        final.value[key] = void 0;
      } else {
        final.value[key] = result.value;
      }
    } else {
      final.issues.push(...prefixIssues(key, result.issues));
    }
  } else if (result.value === void 0) {
    if (key in input)
      final.value[key] = void 0;
  } else {
    final.value[key] = result.value;
  }
}
const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
  $ZodType.init(inst, def);
  const _normalized = cached(() => {
    const keys = Object.keys(def.shape);
    for (const k2 of keys) {
      if (!(def.shape[k2] instanceof $ZodType)) {
        throw new Error(`Invalid element at key "${k2}": expected a Zod schema`);
      }
    }
    const okeys = optionalKeys(def.shape);
    return {
      shape: def.shape,
      keys,
      keySet: new Set(keys),
      numKeys: keys.length,
      optionalKeys: new Set(okeys)
    };
  });
  defineLazy(inst._zod, "propValues", () => {
    const shape = def.shape;
    const propValues = {};
    for (const key in shape) {
      const field = shape[key]._zod;
      if (field.values) {
        propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
        for (const v2 of field.values)
          propValues[key].add(v2);
      }
    }
    return propValues;
  });
  const generateFastpass = (shape) => {
    const doc = new Doc(["shape", "payload", "ctx"]);
    const normalized = _normalized.value;
    const parseStr = (key) => {
      const k2 = esc(key);
      return `shape[${k2}]._zod.run({ value: input[${k2}], issues: [] }, ctx)`;
    };
    doc.write(`const input = payload.value;`);
    const ids = /* @__PURE__ */ Object.create(null);
    let counter = 0;
    for (const key of normalized.keys) {
      ids[key] = `key_${counter++}`;
    }
    doc.write(`const newResult = {}`);
    for (const key of normalized.keys) {
      if (normalized.optionalKeys.has(key)) {
        const id2 = ids[key];
        doc.write(`const ${id2} = ${parseStr(key)};`);
        const k2 = esc(key);
        doc.write(`
        if (${id2}.issues.length) {
          if (input[${k2}] === undefined) {
            if (${k2} in input) {
              newResult[${k2}] = undefined;
            }
          } else {
            payload.issues = payload.issues.concat(
              ${id2}.issues.map((iss) => ({
                ...iss,
                path: iss.path ? [${k2}, ...iss.path] : [${k2}],
              }))
            );
          }
        } else if (${id2}.value === undefined) {
          if (${k2} in input) newResult[${k2}] = undefined;
        } else {
          newResult[${k2}] = ${id2}.value;
        }
        `);
      } else {
        const id2 = ids[key];
        doc.write(`const ${id2} = ${parseStr(key)};`);
        doc.write(`
          if (${id2}.issues.length) payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
          })));`);
        doc.write(`newResult[${esc(key)}] = ${id2}.value`);
      }
    }
    doc.write(`payload.value = newResult;`);
    doc.write(`return payload;`);
    const fn2 = doc.compile();
    return (payload, ctx) => fn2(shape, payload, ctx);
  };
  let fastpass;
  const isObject$1 = isObject;
  const jit = !globalConfig.jitless;
  const allowsEval$1 = allowsEval;
  const fastEnabled = jit && allowsEval$1.value;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value ?? (value = _normalized.value);
    const input = payload.value;
    if (!isObject$1(input)) {
      payload.issues.push({
        expected: "object",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    const proms = [];
    if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
      if (!fastpass)
        fastpass = generateFastpass(def.shape);
      payload = fastpass(payload, ctx);
    } else {
      payload.value = {};
      const shape = value.shape;
      for (const key of value.keys) {
        const el2 = shape[key];
        const r2 = el2._zod.run({ value: input[key], issues: [] }, ctx);
        const isOptional = el2._zod.optin === "optional" && el2._zod.optout === "optional";
        if (r2 instanceof Promise) {
          proms.push(r2.then((r3) => isOptional ? handleOptionalObjectResult(r3, payload, key, input) : handleObjectResult(r3, payload, key)));
        } else if (isOptional) {
          handleOptionalObjectResult(r2, payload, key, input);
        } else {
          handleObjectResult(r2, payload, key);
        }
      }
    }
    if (!catchall) {
      return proms.length ? Promise.all(proms).then(() => payload) : payload;
    }
    const unrecognized = [];
    const keySet = value.keySet;
    const _catchall = catchall._zod;
    const t2 = _catchall.def.type;
    for (const key of Object.keys(input)) {
      if (keySet.has(key))
        continue;
      if (t2 === "never") {
        unrecognized.push(key);
        continue;
      }
      const r2 = _catchall.run({ value: input[key], issues: [] }, ctx);
      if (r2 instanceof Promise) {
        proms.push(r2.then((r3) => handleObjectResult(r3, payload, key)));
      } else {
        handleObjectResult(r2, payload, key);
      }
    }
    if (unrecognized.length) {
      payload.issues.push({
        code: "unrecognized_keys",
        keys: unrecognized,
        input,
        inst
      });
    }
    if (!proms.length)
      return payload;
    return Promise.all(proms).then(() => {
      return payload;
    });
  };
});
function handleUnionResults(results, final, inst, ctx) {
  for (const result of results) {
    if (result.issues.length === 0) {
      final.value = result.value;
      return final;
    }
  }
  final.issues.push({
    code: "invalid_union",
    input: final.value,
    inst,
    errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  });
  return final;
}
const $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "optin", () => def.options.some((o2) => o2._zod.optin === "optional") ? "optional" : void 0);
  defineLazy(inst._zod, "optout", () => def.options.some((o2) => o2._zod.optout === "optional") ? "optional" : void 0);
  defineLazy(inst._zod, "values", () => {
    if (def.options.every((o2) => o2._zod.values)) {
      return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
    }
    return void 0;
  });
  defineLazy(inst._zod, "pattern", () => {
    if (def.options.every((o2) => o2._zod.pattern)) {
      const patterns = def.options.map((o2) => o2._zod.pattern);
      return new RegExp(`^(${patterns.map((p2) => cleanRegex(p2.source)).join("|")})$`);
    }
    return void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    let async2 = false;
    const results = [];
    for (const option of def.options) {
      const result = option._zod.run({
        value: payload.value,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        results.push(result);
        async2 = true;
      } else {
        if (result.issues.length === 0)
          return result;
        results.push(result);
      }
    }
    if (!async2)
      return handleUnionResults(results, payload, inst, ctx);
    return Promise.all(results).then((results2) => {
      return handleUnionResults(results2, payload, inst, ctx);
    });
  };
});
const $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
  $ZodUnion.init(inst, def);
  const _super = inst._zod.parse;
  defineLazy(inst._zod, "propValues", () => {
    const propValues = {};
    for (const option of def.options) {
      const pv2 = option._zod.propValues;
      if (!pv2 || Object.keys(pv2).length === 0)
        throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
      for (const [k2, v2] of Object.entries(pv2)) {
        if (!propValues[k2])
          propValues[k2] = /* @__PURE__ */ new Set();
        for (const val of v2) {
          propValues[k2].add(val);
        }
      }
    }
    return propValues;
  });
  const disc = cached(() => {
    const opts = def.options;
    const map = /* @__PURE__ */ new Map();
    for (const o2 of opts) {
      const values = o2._zod.propValues[def.discriminator];
      if (!values || values.size === 0)
        throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o2)}"`);
      for (const v2 of values) {
        if (map.has(v2)) {
          throw new Error(`Duplicate discriminator value "${String(v2)}"`);
        }
        map.set(v2, o2);
      }
    }
    return map;
  });
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!isObject(input)) {
      payload.issues.push({
        code: "invalid_type",
        expected: "object",
        input,
        inst
      });
      return payload;
    }
    const opt = disc.value.get(input?.[def.discriminator]);
    if (opt) {
      return opt._zod.run(payload, ctx);
    }
    if (def.unionFallback) {
      return _super(payload, ctx);
    }
    payload.issues.push({
      code: "invalid_union",
      errors: [],
      note: "No matching discriminator",
      input,
      path: [def.discriminator],
      inst
    });
    return payload;
  };
});
const $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    const left = def.left._zod.run({ value: input, issues: [] }, ctx);
    const right = def.right._zod.run({ value: input, issues: [] }, ctx);
    const async2 = left instanceof Promise || right instanceof Promise;
    if (async2) {
      return Promise.all([left, right]).then(([left2, right2]) => {
        return handleIntersectionResults(payload, left2, right2);
      });
    }
    return handleIntersectionResults(payload, left, right);
  };
});
function mergeValues$1(a2, b2) {
  if (a2 === b2) {
    return { valid: true, data: a2 };
  }
  if (a2 instanceof Date && b2 instanceof Date && +a2 === +b2) {
    return { valid: true, data: a2 };
  }
  if (isPlainObject$2(a2) && isPlainObject$2(b2)) {
    const bKeys = Object.keys(b2);
    const sharedKeys = Object.keys(a2).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a2, ...b2 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues$1(a2[key], b2[key]);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
        };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  }
  if (Array.isArray(a2) && Array.isArray(b2)) {
    if (a2.length !== b2.length) {
      return { valid: false, mergeErrorPath: [] };
    }
    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,
          mergeErrorPath: [index2, ...sharedValue.mergeErrorPath]
        };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  }
  return { valid: false, mergeErrorPath: [] };
}
function handleIntersectionResults(result, left, right) {
  if (left.issues.length) {
    result.issues.push(...left.issues);
  }
  if (right.issues.length) {
    result.issues.push(...right.issues);
  }
  if (aborted(result))
    return result;
  const merged = mergeValues$1(left.value, right.value);
  if (!merged.valid) {
    throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
  }
  result.value = merged.data;
  return result;
}
const $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!isPlainObject$2(input)) {
      payload.issues.push({
        expected: "record",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    const proms = [];
    if (def.keyType._zod.values) {
      const values = def.keyType._zod.values;
      payload.value = {};
      for (const key of values) {
        if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
          const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
          if (result instanceof Promise) {
            proms.push(result.then((result2) => {
              if (result2.issues.length) {
                payload.issues.push(...prefixIssues(key, result2.issues));
              }
              payload.value[key] = result2.value;
            }));
          } else {
            if (result.issues.length) {
              payload.issues.push(...prefixIssues(key, result.issues));
            }
            payload.value[key] = result.value;
          }
        }
      }
      let unrecognized;
      for (const key in input) {
        if (!values.has(key)) {
          unrecognized = unrecognized ?? [];
          unrecognized.push(key);
        }
      }
      if (unrecognized && unrecognized.length > 0) {
        payload.issues.push({
          code: "unrecognized_keys",
          input,
          inst,
          keys: unrecognized
        });
      }
    } else {
      payload.value = {};
      for (const key of Reflect.ownKeys(input)) {
        if (key === "__proto__")
          continue;
        const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
        if (keyResult instanceof Promise) {
          throw new Error("Async schemas not supported in object keys currently");
        }
        if (keyResult.issues.length) {
          payload.issues.push({
            origin: "record",
            code: "invalid_key",
            issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
            input: key,
            path: [key],
            inst
          });
          payload.value[keyResult.value] = keyResult.value;
          continue;
        }
        const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
        if (result instanceof Promise) {
          proms.push(result.then((result2) => {
            if (result2.issues.length) {
              payload.issues.push(...prefixIssues(key, result2.issues));
            }
            payload.value[keyResult.value] = result2.value;
          }));
        } else {
          if (result.issues.length) {
            payload.issues.push(...prefixIssues(key, result.issues));
          }
          payload.value[keyResult.value] = result.value;
        }
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
  $ZodType.init(inst, def);
  const values = getEnumValues(def.entries);
  inst._zod.values = new Set(values);
  inst._zod.pattern = new RegExp(`^(${values.filter((k2) => propertyKeyTypes.has(typeof k2)).map((o2) => typeof o2 === "string" ? escapeRegex(o2) : o2.toString()).join("|")})$`);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (inst._zod.values.has(input)) {
      return payload;
    }
    payload.issues.push({
      code: "invalid_value",
      values,
      input,
      inst
    });
    return payload;
  };
});
const $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.values = new Set(def.values);
  inst._zod.pattern = new RegExp(`^(${def.values.map((o2) => typeof o2 === "string" ? escapeRegex(o2) : o2 ? o2.toString() : String(o2)).join("|")})$`);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (inst._zod.values.has(input)) {
      return payload;
    }
    payload.issues.push({
      code: "invalid_value",
      values: def.values,
      input,
      inst
    });
    return payload;
  };
});
const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const _out = def.transform(payload.value, payload);
    if (_ctx.async) {
      const output = _out instanceof Promise ? _out : Promise.resolve(_out);
      return output.then((output2) => {
        payload.value = output2;
        return payload;
      });
    }
    if (_out instanceof Promise) {
      throw new $ZodAsyncError();
    }
    payload.value = _out;
    return payload;
  };
});
const $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  inst._zod.optout = "optional";
  defineLazy(inst._zod, "values", () => {
    return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
  });
  defineLazy(inst._zod, "pattern", () => {
    const pattern2 = def.innerType._zod.pattern;
    return pattern2 ? new RegExp(`^(${cleanRegex(pattern2.source)})?$`) : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    if (def.innerType._zod.optin === "optional") {
      return def.innerType._zod.run(payload, ctx);
    }
    if (payload.value === void 0) {
      return payload;
    }
    return def.innerType._zod.run(payload, ctx);
  };
});
const $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  defineLazy(inst._zod, "pattern", () => {
    const pattern2 = def.innerType._zod.pattern;
    return pattern2 ? new RegExp(`^(${cleanRegex(pattern2.source)}|null)$`) : void 0;
  });
  defineLazy(inst._zod, "values", () => {
    return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    if (payload.value === null)
      return payload;
    return def.innerType._zod.run(payload, ctx);
  };
});
const $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (payload.value === void 0) {
      payload.value = def.defaultValue;
      return payload;
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => handleDefaultResult(result2, def));
    }
    return handleDefaultResult(result, def);
  };
});
function handleDefaultResult(payload, def) {
  if (payload.value === void 0) {
    payload.value = def.defaultValue;
  }
  return payload;
}
const $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (payload.value === void 0) {
      payload.value = def.defaultValue;
    }
    return def.innerType._zod.run(payload, ctx);
  };
});
const $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => {
    const v2 = def.innerType._zod.values;
    return v2 ? new Set([...v2].filter((x2) => x2 !== void 0)) : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => handleNonOptionalResult(result2, inst));
    }
    return handleNonOptionalResult(result, inst);
  };
});
function handleNonOptionalResult(payload, inst) {
  if (!payload.issues.length && payload.value === void 0) {
    payload.issues.push({
      code: "invalid_type",
      expected: "nonoptional",
      input: payload.value,
      inst
    });
  }
  return payload;
}
const $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => {
        payload.value = result2.value;
        if (result2.issues.length) {
          payload.value = def.catchValue({
            ...payload,
            error: {
              issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
            },
            input: payload.value
          });
          payload.issues = [];
        }
        return payload;
      });
    }
    payload.value = result.value;
    if (result.issues.length) {
      payload.value = def.catchValue({
        ...payload,
        error: {
          issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
        },
        input: payload.value
      });
      payload.issues = [];
    }
    return payload;
  };
});
const $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => def.in._zod.values);
  defineLazy(inst._zod, "optin", () => def.in._zod.optin);
  defineLazy(inst._zod, "optout", () => def.out._zod.optout);
  inst._zod.parse = (payload, ctx) => {
    const left = def.in._zod.run(payload, ctx);
    if (left instanceof Promise) {
      return left.then((left2) => handlePipeResult(left2, def, ctx));
    }
    return handlePipeResult(left, def, ctx);
  };
});
function handlePipeResult(left, def, ctx) {
  if (aborted(left)) {
    return left;
  }
  return def.out._zod.run({ value: left.value, issues: left.issues }, ctx);
}
const $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  inst._zod.parse = (payload, ctx) => {
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then(handleReadonlyResult);
    }
    return handleReadonlyResult(result);
  };
});
function handleReadonlyResult(payload) {
  payload.value = Object.freeze(payload.value);
  return payload;
}
const $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
  $ZodCheck.init(inst, def);
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _2) => {
    return payload;
  };
  inst._zod.check = (payload) => {
    const input = payload.value;
    const r2 = def.fn(input);
    if (r2 instanceof Promise) {
      return r2.then((r3) => handleRefineResult(r3, payload, input, inst));
    }
    handleRefineResult(r2, payload, input, inst);
    return;
  };
});
function handleRefineResult(result, payload, input, inst) {
  if (!result) {
    const _iss = {
      code: "custom",
      input,
      inst,
      // incorporates params.error into issue reporting
      path: [...inst._zod.def.path ?? []],
      // incorporates params.error into issue reporting
      continue: !inst._zod.def.abort
      // params: inst._zod.def.params,
    };
    if (inst._zod.def.params)
      _iss.params = inst._zod.def.params;
    payload.issues.push(issue(_iss));
  }
}
class $ZodRegistry {
  constructor() {
    this._map = /* @__PURE__ */ new Map();
    this._idmap = /* @__PURE__ */ new Map();
  }
  add(schema, ..._meta) {
    const meta = _meta[0];
    this._map.set(schema, meta);
    if (meta && typeof meta === "object" && "id" in meta) {
      if (this._idmap.has(meta.id)) {
        throw new Error(`ID ${meta.id} already exists in the registry`);
      }
      this._idmap.set(meta.id, schema);
    }
    return this;
  }
  clear() {
    this._map = /* @__PURE__ */ new Map();
    this._idmap = /* @__PURE__ */ new Map();
    return this;
  }
  remove(schema) {
    const meta = this._map.get(schema);
    if (meta && typeof meta === "object" && "id" in meta) {
      this._idmap.delete(meta.id);
    }
    this._map.delete(schema);
    return this;
  }
  get(schema) {
    const p2 = schema._zod.parent;
    if (p2) {
      const pm2 = { ...this.get(p2) ?? {} };
      delete pm2.id;
      return { ...pm2, ...this._map.get(schema) };
    }
    return this._map.get(schema);
  }
  has(schema) {
    return this._map.has(schema);
  }
}
function registry() {
  return new $ZodRegistry();
}
const globalRegistry = /* @__PURE__ */ registry();
function _string(Class, params) {
  return new Class({
    type: "string",
    ...normalizeParams(params)
  });
}
function _email(Class, params) {
  return new Class({
    type: "string",
    format: "email",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _guid(Class, params) {
  return new Class({
    type: "string",
    format: "guid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _uuid(Class, params) {
  return new Class({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _uuidv4(Class, params) {
  return new Class({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v4",
    ...normalizeParams(params)
  });
}
function _uuidv6(Class, params) {
  return new Class({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v6",
    ...normalizeParams(params)
  });
}
function _uuidv7(Class, params) {
  return new Class({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v7",
    ...normalizeParams(params)
  });
}
function _url$1(Class, params) {
  return new Class({
    type: "string",
    format: "url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _emoji(Class, params) {
  return new Class({
    type: "string",
    format: "emoji",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _nanoid(Class, params) {
  return new Class({
    type: "string",
    format: "nanoid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _cuid(Class, params) {
  return new Class({
    type: "string",
    format: "cuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _cuid2(Class, params) {
  return new Class({
    type: "string",
    format: "cuid2",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _ulid(Class, params) {
  return new Class({
    type: "string",
    format: "ulid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _xid(Class, params) {
  return new Class({
    type: "string",
    format: "xid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _ksuid(Class, params) {
  return new Class({
    type: "string",
    format: "ksuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _ipv4(Class, params) {
  return new Class({
    type: "string",
    format: "ipv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _ipv6(Class, params) {
  return new Class({
    type: "string",
    format: "ipv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _cidrv4(Class, params) {
  return new Class({
    type: "string",
    format: "cidrv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _cidrv6(Class, params) {
  return new Class({
    type: "string",
    format: "cidrv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _base64(Class, params) {
  return new Class({
    type: "string",
    format: "base64",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _base64url(Class, params) {
  return new Class({
    type: "string",
    format: "base64url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _e164(Class, params) {
  return new Class({
    type: "string",
    format: "e164",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _jwt(Class, params) {
  return new Class({
    type: "string",
    format: "jwt",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _isoDateTime(Class, params) {
  return new Class({
    type: "string",
    format: "datetime",
    check: "string_format",
    offset: false,
    local: false,
    precision: null,
    ...normalizeParams(params)
  });
}
function _isoDate(Class, params) {
  return new Class({
    type: "string",
    format: "date",
    check: "string_format",
    ...normalizeParams(params)
  });
}
function _isoTime(Class, params) {
  return new Class({
    type: "string",
    format: "time",
    check: "string_format",
    precision: null,
    ...normalizeParams(params)
  });
}
function _isoDuration(Class, params) {
  return new Class({
    type: "string",
    format: "duration",
    check: "string_format",
    ...normalizeParams(params)
  });
}
function _number(Class, params) {
  return new Class({
    type: "number",
    checks: [],
    ...normalizeParams(params)
  });
}
function _coercedNumber(Class, params) {
  return new Class({
    type: "number",
    coerce: true,
    checks: [],
    ...normalizeParams(params)
  });
}
function _int(Class, params) {
  return new Class({
    type: "number",
    check: "number_format",
    abort: false,
    format: "safeint",
    ...normalizeParams(params)
  });
}
function _boolean(Class, params) {
  return new Class({
    type: "boolean",
    ...normalizeParams(params)
  });
}
function _undefined$1(Class, params) {
  return new Class({
    type: "undefined",
    ...normalizeParams(params)
  });
}
function _null$1(Class, params) {
  return new Class({
    type: "null",
    ...normalizeParams(params)
  });
}
function _any(Class) {
  return new Class({
    type: "any"
  });
}
function _unknown(Class) {
  return new Class({
    type: "unknown"
  });
}
function _never(Class, params) {
  return new Class({
    type: "never",
    ...normalizeParams(params)
  });
}
function _lt(value, params) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params),
    value,
    inclusive: false
  });
}
function _lte(value, params) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params),
    value,
    inclusive: true
  });
}
function _gt(value, params) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params),
    value,
    inclusive: false
  });
}
function _gte(value, params) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params),
    value,
    inclusive: true
  });
}
function _multipleOf(value, params) {
  return new $ZodCheckMultipleOf({
    check: "multiple_of",
    ...normalizeParams(params),
    value
  });
}
function _maxLength(maximum, params) {
  const ch = new $ZodCheckMaxLength({
    check: "max_length",
    ...normalizeParams(params),
    maximum
  });
  return ch;
}
function _minLength(minimum, params) {
  return new $ZodCheckMinLength({
    check: "min_length",
    ...normalizeParams(params),
    minimum
  });
}
function _length(length, params) {
  return new $ZodCheckLengthEquals({
    check: "length_equals",
    ...normalizeParams(params),
    length
  });
}
function _regex(pattern2, params) {
  return new $ZodCheckRegex({
    check: "string_format",
    format: "regex",
    ...normalizeParams(params),
    pattern: pattern2
  });
}
function _lowercase(params) {
  return new $ZodCheckLowerCase({
    check: "string_format",
    format: "lowercase",
    ...normalizeParams(params)
  });
}
function _uppercase(params) {
  return new $ZodCheckUpperCase({
    check: "string_format",
    format: "uppercase",
    ...normalizeParams(params)
  });
}
function _includes(includes, params) {
  return new $ZodCheckIncludes({
    check: "string_format",
    format: "includes",
    ...normalizeParams(params),
    includes
  });
}
function _startsWith(prefix, params) {
  return new $ZodCheckStartsWith({
    check: "string_format",
    format: "starts_with",
    ...normalizeParams(params),
    prefix
  });
}
function _endsWith(suffix, params) {
  return new $ZodCheckEndsWith({
    check: "string_format",
    format: "ends_with",
    ...normalizeParams(params),
    suffix
  });
}
function _overwrite(tx) {
  return new $ZodCheckOverwrite({
    check: "overwrite",
    tx
  });
}
function _normalize(form) {
  return _overwrite((input) => input.normalize(form));
}
function _trim() {
  return _overwrite((input) => input.trim());
}
function _toLowerCase() {
  return _overwrite((input) => input.toLowerCase());
}
function _toUpperCase() {
  return _overwrite((input) => input.toUpperCase());
}
function _array(Class, element, params) {
  return new Class({
    type: "array",
    element,
    // get element() {
    //   return element;
    // },
    ...normalizeParams(params)
  });
}
function _custom(Class, fn2, _params) {
  const norm = normalizeParams(_params);
  norm.abort ?? (norm.abort = true);
  const schema = new Class({
    type: "custom",
    check: "custom",
    fn: fn2,
    ...norm
  });
  return schema;
}
function _refine(Class, fn2, _params) {
  const schema = new Class({
    type: "custom",
    check: "custom",
    fn: fn2,
    ...normalizeParams(_params)
  });
  return schema;
}
const ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
  $ZodISODateTime.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function datetime(params) {
  return _isoDateTime(ZodISODateTime, params);
}
const ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
  $ZodISODate.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function date(params) {
  return _isoDate(ZodISODate, params);
}
const ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
  $ZodISOTime.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function time(params) {
  return _isoTime(ZodISOTime, params);
}
const ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
  $ZodISODuration.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function duration(params) {
  return _isoDuration(ZodISODuration, params);
}
const initializer = (inst, issues) => {
  $ZodError.init(inst, issues);
  inst.name = "ZodError";
  Object.defineProperties(inst, {
    format: {
      value: (mapper) => formatError(inst, mapper)
      // enumerable: false,
    },
    flatten: {
      value: (mapper) => flattenError$1(inst, mapper)
      // enumerable: false,
    },
    addIssue: {
      value: (issue2) => inst.issues.push(issue2)
      // enumerable: false,
    },
    addIssues: {
      value: (issues2) => inst.issues.push(...issues2)
      // enumerable: false,
    },
    isEmpty: {
      get() {
        return inst.issues.length === 0;
      }
      // enumerable: false,
    }
  });
};
const ZodRealError = $constructor("ZodError", initializer, {
  Parent: Error
});
const parse$1 = /* @__PURE__ */ _parse(ZodRealError);
const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
const safeParse$1 = /* @__PURE__ */ _safeParse(ZodRealError);
const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
const ZodType$1 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
  $ZodType.init(inst, def);
  inst.def = def;
  Object.defineProperty(inst, "_def", { value: def });
  inst.check = (...checks) => {
    return inst.clone(
      {
        ...def,
        checks: [
          ...def.checks ?? [],
          ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
        ]
      }
      // { parent: true }
    );
  };
  inst.clone = (def2, params) => clone(inst, def2, params);
  inst.brand = () => inst;
  inst.register = ((reg, meta) => {
    reg.add(inst, meta);
    return inst;
  });
  inst.parse = (data2, params) => parse$1(inst, data2, params, { callee: inst.parse });
  inst.safeParse = (data2, params) => safeParse$1(inst, data2, params);
  inst.parseAsync = async (data2, params) => parseAsync(inst, data2, params, { callee: inst.parseAsync });
  inst.safeParseAsync = async (data2, params) => safeParseAsync(inst, data2, params);
  inst.spa = inst.safeParseAsync;
  inst.refine = (check2, params) => inst.check(refine(check2, params));
  inst.superRefine = (refinement) => inst.check(superRefine(refinement));
  inst.overwrite = (fn2) => inst.check(_overwrite(fn2));
  inst.optional = () => optional(inst);
  inst.nullable = () => nullable(inst);
  inst.nullish = () => optional(nullable(inst));
  inst.nonoptional = (params) => nonoptional(inst, params);
  inst.array = () => array(inst);
  inst.or = (arg) => union([inst, arg]);
  inst.and = (arg) => intersection(inst, arg);
  inst.transform = (tx) => pipe(inst, transform(tx));
  inst.default = (def2) => _default(inst, def2);
  inst.prefault = (def2) => prefault(inst, def2);
  inst.catch = (params) => _catch(inst, params);
  inst.pipe = (target) => pipe(inst, target);
  inst.readonly = () => readonly(inst);
  inst.describe = (description2) => {
    const cl2 = inst.clone();
    globalRegistry.add(cl2, { description: description2 });
    return cl2;
  };
  Object.defineProperty(inst, "description", {
    get() {
      return globalRegistry.get(inst)?.description;
    },
    configurable: true
  });
  inst.meta = (...args) => {
    if (args.length === 0) {
      return globalRegistry.get(inst);
    }
    const cl2 = inst.clone();
    globalRegistry.add(cl2, args[0]);
    return cl2;
  };
  inst.isOptional = () => inst.safeParse(void 0).success;
  inst.isNullable = () => inst.safeParse(null).success;
  return inst;
});
const _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
  $ZodString.init(inst, def);
  ZodType$1.init(inst, def);
  const bag = inst._zod.bag;
  inst.format = bag.format ?? null;
  inst.minLength = bag.minimum ?? null;
  inst.maxLength = bag.maximum ?? null;
  inst.regex = (...args) => inst.check(_regex(...args));
  inst.includes = (...args) => inst.check(_includes(...args));
  inst.startsWith = (...args) => inst.check(_startsWith(...args));
  inst.endsWith = (...args) => inst.check(_endsWith(...args));
  inst.min = (...args) => inst.check(_minLength(...args));
  inst.max = (...args) => inst.check(_maxLength(...args));
  inst.length = (...args) => inst.check(_length(...args));
  inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
  inst.lowercase = (params) => inst.check(_lowercase(params));
  inst.uppercase = (params) => inst.check(_uppercase(params));
  inst.trim = () => inst.check(_trim());
  inst.normalize = (...args) => inst.check(_normalize(...args));
  inst.toLowerCase = () => inst.check(_toLowerCase());
  inst.toUpperCase = () => inst.check(_toUpperCase());
});
const ZodString$1 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
  $ZodString.init(inst, def);
  _ZodString.init(inst, def);
  inst.email = (params) => inst.check(_email(ZodEmail, params));
  inst.url = (params) => inst.check(_url$1(ZodURL, params));
  inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
  inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
  inst.guid = (params) => inst.check(_guid(ZodGUID, params));
  inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
  inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
  inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
  inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
  inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
  inst.guid = (params) => inst.check(_guid(ZodGUID, params));
  inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
  inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
  inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
  inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
  inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
  inst.xid = (params) => inst.check(_xid(ZodXID, params));
  inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
  inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
  inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
  inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
  inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
  inst.e164 = (params) => inst.check(_e164(ZodE164, params));
  inst.datetime = (params) => inst.check(datetime(params));
  inst.date = (params) => inst.check(date(params));
  inst.time = (params) => inst.check(time(params));
  inst.duration = (params) => inst.check(duration(params));
});
function string(params) {
  return _string(ZodString$1, params);
}
const ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  _ZodString.init(inst, def);
});
const ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
  $ZodEmail.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
  $ZodGUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
  $ZodUUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
  $ZodURL.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function url(params) {
  return _url$1(ZodURL, params);
}
const ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
  $ZodEmoji.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
  $ZodNanoID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
  $ZodCUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
  $ZodCUID2.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
  $ZodULID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
  $ZodXID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
  $ZodKSUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
  $ZodIPv4.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
  $ZodIPv6.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
  $ZodCIDRv4.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
  $ZodCIDRv6.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
  $ZodBase64.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
  $ZodBase64URL.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
  $ZodE164.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
  $ZodJWT.init(inst, def);
  ZodStringFormat.init(inst, def);
});
const ZodNumber$1 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
  $ZodNumber.init(inst, def);
  ZodType$1.init(inst, def);
  inst.gt = (value, params) => inst.check(_gt(value, params));
  inst.gte = (value, params) => inst.check(_gte(value, params));
  inst.min = (value, params) => inst.check(_gte(value, params));
  inst.lt = (value, params) => inst.check(_lt(value, params));
  inst.lte = (value, params) => inst.check(_lte(value, params));
  inst.max = (value, params) => inst.check(_lte(value, params));
  inst.int = (params) => inst.check(int(params));
  inst.safe = (params) => inst.check(int(params));
  inst.positive = (params) => inst.check(_gt(0, params));
  inst.nonnegative = (params) => inst.check(_gte(0, params));
  inst.negative = (params) => inst.check(_lt(0, params));
  inst.nonpositive = (params) => inst.check(_lte(0, params));
  inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
  inst.step = (value, params) => inst.check(_multipleOf(value, params));
  inst.finite = () => inst;
  const bag = inst._zod.bag;
  inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
  inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
  inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
  inst.isFinite = true;
  inst.format = bag.format ?? null;
});
function number$1(params) {
  return _number(ZodNumber$1, params);
}
const ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
  $ZodNumberFormat.init(inst, def);
  ZodNumber$1.init(inst, def);
});
function int(params) {
  return _int(ZodNumberFormat, params);
}
const ZodBoolean$1 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
  $ZodBoolean.init(inst, def);
  ZodType$1.init(inst, def);
});
function boolean(params) {
  return _boolean(ZodBoolean$1, params);
}
const ZodUndefined$1 = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => {
  $ZodUndefined.init(inst, def);
  ZodType$1.init(inst, def);
});
function _undefined(params) {
  return _undefined$1(ZodUndefined$1, params);
}
const ZodNull$1 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
  $ZodNull.init(inst, def);
  ZodType$1.init(inst, def);
});
function _null(params) {
  return _null$1(ZodNull$1, params);
}
const ZodAny$1 = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => {
  $ZodAny.init(inst, def);
  ZodType$1.init(inst, def);
});
function any() {
  return _any(ZodAny$1);
}
const ZodUnknown$1 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
  $ZodUnknown.init(inst, def);
  ZodType$1.init(inst, def);
});
function unknown() {
  return _unknown(ZodUnknown$1);
}
const ZodNever$1 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
  $ZodNever.init(inst, def);
  ZodType$1.init(inst, def);
});
function never(params) {
  return _never(ZodNever$1, params);
}
const ZodArray$1 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
  $ZodArray.init(inst, def);
  ZodType$1.init(inst, def);
  inst.element = def.element;
  inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
  inst.nonempty = (params) => inst.check(_minLength(1, params));
  inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
  inst.length = (len, params) => inst.check(_length(len, params));
  inst.unwrap = () => inst.element;
});
function array(element, params) {
  return _array(ZodArray$1, element, params);
}
const ZodObject$1 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
  $ZodObject.init(inst, def);
  ZodType$1.init(inst, def);
  defineLazy(inst, "shape", () => def.shape);
  inst.keyof = () => _enum$3(Object.keys(inst._zod.def.shape));
  inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall });
  inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
  inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
  inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
  inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 });
  inst.extend = (incoming) => {
    return extend(inst, incoming);
  };
  inst.merge = (other) => merge(inst, other);
  inst.pick = (mask) => pick(inst, mask);
  inst.omit = (mask) => omit(inst, mask);
  inst.partial = (...args) => partial(ZodOptional$1, inst, args[0]);
  inst.required = (...args) => required$6(ZodNonOptional, inst, args[0]);
});
function object(shape, params) {
  const def = {
    type: "object",
    get shape() {
      assignProp(this, "shape", { ...shape });
      return this.shape;
    },
    ...normalizeParams(params)
  };
  return new ZodObject$1(def);
}
function looseObject(shape, params) {
  return new ZodObject$1({
    type: "object",
    get shape() {
      assignProp(this, "shape", { ...shape });
      return this.shape;
    },
    catchall: unknown(),
    ...normalizeParams(params)
  });
}
const ZodUnion$1 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
  $ZodUnion.init(inst, def);
  ZodType$1.init(inst, def);
  inst.options = def.options;
});
function union(options, params) {
  return new ZodUnion$1({
    type: "union",
    options,
    ...normalizeParams(params)
  });
}
const ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
  ZodUnion$1.init(inst, def);
  $ZodDiscriminatedUnion.init(inst, def);
});
function discriminatedUnion(discriminator2, options, params) {
  return new ZodDiscriminatedUnion({
    type: "union",
    options,
    discriminator: discriminator2,
    ...normalizeParams(params)
  });
}
const ZodIntersection$1 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
  $ZodIntersection.init(inst, def);
  ZodType$1.init(inst, def);
});
function intersection(left, right) {
  return new ZodIntersection$1({
    type: "intersection",
    left,
    right
  });
}
const ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
  $ZodRecord.init(inst, def);
  ZodType$1.init(inst, def);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
});
function record(keyType, valueType, params) {
  return new ZodRecord({
    type: "record",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
const ZodEnum$1 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
  $ZodEnum.init(inst, def);
  ZodType$1.init(inst, def);
  inst.enum = def.entries;
  inst.options = Object.values(def.entries);
  const keys = new Set(Object.keys(def.entries));
  inst.extract = (values, params) => {
    const newEntries = {};
    for (const value of values) {
      if (keys.has(value)) {
        newEntries[value] = def.entries[value];
      } else
        throw new Error(`Key ${value} not found in enum`);
    }
    return new ZodEnum$1({
      ...def,
      checks: [],
      ...normalizeParams(params),
      entries: newEntries
    });
  };
  inst.exclude = (values, params) => {
    const newEntries = { ...def.entries };
    for (const value of values) {
      if (keys.has(value)) {
        delete newEntries[value];
      } else
        throw new Error(`Key ${value} not found in enum`);
    }
    return new ZodEnum$1({
      ...def,
      checks: [],
      ...normalizeParams(params),
      entries: newEntries
    });
  };
});
function _enum$3(values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v2) => [v2, v2])) : values;
  return new ZodEnum$1({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
const ZodLiteral$1 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
  $ZodLiteral.init(inst, def);
  ZodType$1.init(inst, def);
  inst.values = new Set(def.values);
  Object.defineProperty(inst, "value", {
    get() {
      if (def.values.length > 1) {
        throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
      }
      return def.values[0];
    }
  });
});
function literal(value, params) {
  return new ZodLiteral$1({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...normalizeParams(params)
  });
}
const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
  $ZodTransform.init(inst, def);
  ZodType$1.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    payload.addIssue = (issue$1) => {
      if (typeof issue$1 === "string") {
        payload.issues.push(issue(issue$1, payload.value, def));
      } else {
        const _issue = issue$1;
        if (_issue.fatal)
          _issue.continue = false;
        _issue.code ?? (_issue.code = "custom");
        _issue.input ?? (_issue.input = payload.value);
        _issue.inst ?? (_issue.inst = inst);
        _issue.continue ?? (_issue.continue = true);
        payload.issues.push(issue(_issue));
      }
    };
    const output = def.transform(payload.value, payload);
    if (output instanceof Promise) {
      return output.then((output2) => {
        payload.value = output2;
        return payload;
      });
    }
    payload.value = output;
    return payload;
  };
});
function transform(fn2) {
  return new ZodTransform({
    type: "transform",
    transform: fn2
  });
}
const ZodOptional$1 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
  $ZodOptional.init(inst, def);
  ZodType$1.init(inst, def);
  inst.unwrap = () => inst._zod.def.innerType;
});
function optional(innerType) {
  return new ZodOptional$1({
    type: "optional",
    innerType
  });
}
const ZodNullable$1 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
  $ZodNullable.init(inst, def);
  ZodType$1.init(inst, def);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nullable(innerType) {
  return new ZodNullable$1({
    type: "nullable",
    innerType
  });
}
const ZodDefault$1 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
  $ZodDefault.init(inst, def);
  ZodType$1.init(inst, def);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeDefault = inst.unwrap;
});
function _default(innerType, defaultValue) {
  return new ZodDefault$1({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : defaultValue;
    }
  });
}
const ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
  $ZodPrefault.init(inst, def);
  ZodType$1.init(inst, def);
  inst.unwrap = () => inst._zod.def.innerType;
});
function prefault(innerType, defaultValue) {
  return new ZodPrefault({
    type: "prefault",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : defaultValue;
    }
  });
}
const ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
  $ZodNonOptional.init(inst, def);
  ZodType$1.init(inst, def);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nonoptional(innerType, params) {
  return new ZodNonOptional({
    type: "nonoptional",
    innerType,
    ...normalizeParams(params)
  });
}
const ZodCatch$1 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
  $ZodCatch.init(inst, def);
  ZodType$1.init(inst, def);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeCatch = inst.unwrap;
});
function _catch(innerType, catchValue) {
  return new ZodCatch$1({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
const ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
  $ZodPipe.init(inst, def);
  ZodType$1.init(inst, def);
  inst.in = def.in;
  inst.out = def.out;
});
function pipe(in_, out) {
  return new ZodPipe({
    type: "pipe",
    in: in_,
    out
    // ...util.normalizeParams(params),
  });
}
const ZodReadonly$1 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
  $ZodReadonly.init(inst, def);
  ZodType$1.init(inst, def);
});
function readonly(innerType) {
  return new ZodReadonly$1({
    type: "readonly",
    innerType
  });
}
const ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
  $ZodCustom.init(inst, def);
  ZodType$1.init(inst, def);
});
function check(fn2) {
  const ch = new $ZodCheck({
    check: "custom"
    // ...util.normalizeParams(params),
  });
  ch._zod.check = fn2;
  return ch;
}
function custom$1(fn2, _params) {
  return _custom(ZodCustom, fn2 ?? (() => true), _params);
}
function refine(fn2, _params = {}) {
  return _refine(ZodCustom, fn2, _params);
}
function superRefine(fn2) {
  const ch = check((payload) => {
    payload.addIssue = (issue$1) => {
      if (typeof issue$1 === "string") {
        payload.issues.push(issue(issue$1, payload.value, ch._zod.def));
      } else {
        const _issue = issue$1;
        if (_issue.fatal)
          _issue.continue = false;
        _issue.code ?? (_issue.code = "custom");
        _issue.input ?? (_issue.input = payload.value);
        _issue.inst ?? (_issue.inst = ch);
        _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
        payload.issues.push(issue(_issue));
      }
    };
    return fn2(payload.value, payload);
  });
  return ch;
}
function preprocess(fn2, schema) {
  return pipe(transform(fn2), schema);
}
const ZodIssueCode$1 = {
  custom: "custom"
};
function number(params) {
  return _coercedNumber(ZodNumber$1, params);
}
const LATEST_PROTOCOL_VERSION = "2025-11-25";
const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
const JSONRPC_VERSION = "2.0";
const AssertObjectSchema = custom$1((v2) => v2 !== null && (typeof v2 === "object" || typeof v2 === "function"));
const ProgressTokenSchema = union([string(), number$1().int()]);
const CursorSchema = string();
looseObject({
  /**
   * Requested duration in milliseconds to retain task from creation.
   */
  ttl: number$1().optional(),
  /**
   * Time in milliseconds to wait between task status requests.
   */
  pollInterval: number$1().optional()
});
const TaskMetadataSchema = object({
  ttl: number$1().optional()
});
const RelatedTaskMetadataSchema = object({
  taskId: string()
});
const RequestMetaSchema = looseObject({
  /**
   * 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: ProgressTokenSchema.optional(),
  /**
   * If specified, this request is related to the provided task.
   */
  [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
});
const BaseRequestParamsSchema = object({
  /**
   * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
   */
  _meta: RequestMetaSchema.optional()
});
const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
  /**
   * If specified, the caller is requesting task-augmented execution for this request.
   * The request will return a CreateTaskResult immediately, and the actual result can be
   * retrieved later via tasks/result.
   *
   * Task augmentation is subject to capability negotiation - receivers MUST declare support
   * for task augmentation of specific request types in their capabilities.
   */
  task: TaskMetadataSchema.optional()
});
const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
const RequestSchema = object({
  method: string(),
  params: BaseRequestParamsSchema.loose().optional()
});
const NotificationsParamsSchema = object({
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: RequestMetaSchema.optional()
});
const NotificationSchema = object({
  method: string(),
  params: NotificationsParamsSchema.loose().optional()
});
const ResultSchema = looseObject({
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: RequestMetaSchema.optional()
});
const RequestIdSchema = union([string(), number$1().int()]);
const JSONRPCRequestSchema = object({
  jsonrpc: literal(JSONRPC_VERSION),
  id: RequestIdSchema,
  ...RequestSchema.shape
}).strict();
const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
const JSONRPCNotificationSchema = object({
  jsonrpc: literal(JSONRPC_VERSION),
  ...NotificationSchema.shape
}).strict();
const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
const JSONRPCResultResponseSchema = object({
  jsonrpc: literal(JSONRPC_VERSION),
  id: RequestIdSchema,
  result: ResultSchema
}).strict();
const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.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";
  ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
})(ErrorCode || (ErrorCode = {}));
const JSONRPCErrorResponseSchema = object({
  jsonrpc: literal(JSONRPC_VERSION),
  id: RequestIdSchema.optional(),
  error: object({
    /**
     * The error type that occurred.
     */
    code: number$1().int(),
    /**
     * A short description of the error. The message SHOULD be limited to a concise single sentence.
     */
    message: string(),
    /**
     * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
     */
    data: unknown().optional()
  })
}).strict();
const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
const JSONRPCMessageSchema = union([
  JSONRPCRequestSchema,
  JSONRPCNotificationSchema,
  JSONRPCResultResponseSchema,
  JSONRPCErrorResponseSchema
]);
union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
const EmptyResultSchema = ResultSchema.strict();
const CancelledNotificationParamsSchema = NotificationsParamsSchema.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.optional(),
  /**
   * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
   */
  reason: string().optional()
});
const CancelledNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/cancelled"),
  params: CancelledNotificationParamsSchema
});
const IconSchema = object({
  /**
   * URL or data URI for the icon.
   */
  src: string(),
  /**
   * Optional MIME type for the icon.
   */
  mimeType: string().optional(),
  /**
   * Optional array of strings that specify sizes at which the icon can be used.
   * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
   *
   * If not provided, the client should assume that the icon can be used at any size.
   */
  sizes: array(string()).optional(),
  /**
   * Optional specifier for the theme this icon is designed for. `light` indicates
   * the icon is designed to be used with a light background, and `dark` indicates
   * the icon is designed to be used with a dark background.
   *
   * If not provided, the client should assume the icon can be used with any theme.
   */
  theme: _enum$3(["light", "dark"]).optional()
});
const IconsSchema = object({
  /**
   * Optional set of sized icons that the client can display in a user interface.
   *
   * Clients that support rendering icons MUST support at least the following MIME types:
   * - `image/png` - PNG images (safe, universal compatibility)
   * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
   *
   * Clients that support rendering icons SHOULD also support:
   * - `image/svg+xml` - SVG images (scalable but requires security precautions)
   * - `image/webp` - WebP images (modern, efficient format)
   */
  icons: array(IconSchema).optional()
});
const BaseMetadataSchema = object({
  /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
  name: string(),
  /**
   * 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: string().optional()
});
const ImplementationSchema = BaseMetadataSchema.extend({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  version: string(),
  /**
   * An optional URL of the website for this implementation.
   */
  websiteUrl: string().optional(),
  /**
   * An optional human-readable description of what this implementation does.
   *
   * This can be used by clients or servers to provide context about their purpose
   * and capabilities. For example, a server might describe the types of resources
   * or tools it provides, while a client might describe its intended use case.
   */
  description: string().optional()
});
const FormElicitationCapabilitySchema = intersection(object({
  applyDefaults: boolean().optional()
}), record(string(), unknown()));
const ElicitationCapabilitySchema = preprocess((value) => {
  if (value && typeof value === "object" && !Array.isArray(value)) {
    if (Object.keys(value).length === 0) {
      return { form: {} };
    }
  }
  return value;
}, intersection(object({
  form: FormElicitationCapabilitySchema.optional(),
  url: AssertObjectSchema.optional()
}), record(string(), unknown()).optional()));
const ClientTasksCapabilitySchema = looseObject({
  /**
   * Present if the client supports listing tasks.
   */
  list: AssertObjectSchema.optional(),
  /**
   * Present if the client supports cancelling tasks.
   */
  cancel: AssertObjectSchema.optional(),
  /**
   * Capabilities for task creation on specific request types.
   */
  requests: looseObject({
    /**
     * Task support for sampling requests.
     */
    sampling: looseObject({
      createMessage: AssertObjectSchema.optional()
    }).optional(),
    /**
     * Task support for elicitation requests.
     */
    elicitation: looseObject({
      create: AssertObjectSchema.optional()
    }).optional()
  }).optional()
});
const ServerTasksCapabilitySchema = looseObject({
  /**
   * Present if the server supports listing tasks.
   */
  list: AssertObjectSchema.optional(),
  /**
   * Present if the server supports cancelling tasks.
   */
  cancel: AssertObjectSchema.optional(),
  /**
   * Capabilities for task creation on specific request types.
   */
  requests: looseObject({
    /**
     * Task support for tool requests.
     */
    tools: looseObject({
      call: AssertObjectSchema.optional()
    }).optional()
  }).optional()
});
const ClientCapabilitiesSchema = object({
  /**
   * Experimental, non-standard capabilities that the client supports.
   */
  experimental: record(string(), AssertObjectSchema).optional(),
  /**
   * Present if the client supports sampling from an LLM.
   */
  sampling: object({
    /**
     * Present if the client supports context inclusion via includeContext parameter.
     * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
     */
    context: AssertObjectSchema.optional(),
    /**
     * Present if the client supports tool use via tools and toolChoice parameters.
     */
    tools: AssertObjectSchema.optional()
  }).optional(),
  /**
   * Present if the client supports eliciting user input.
   */
  elicitation: ElicitationCapabilitySchema.optional(),
  /**
   * Present if the client supports listing roots.
   */
  roots: object({
    /**
     * Whether the client supports issuing notifications for changes to the roots list.
     */
    listChanged: boolean().optional()
  }).optional(),
  /**
   * Present if the client supports task creation.
   */
  tasks: ClientTasksCapabilitySchema.optional(),
  /**
   * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).
   */
  extensions: record(string(), AssertObjectSchema).optional()
});
const InitializeRequestParamsSchema = 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: string(),
  capabilities: ClientCapabilitiesSchema,
  clientInfo: ImplementationSchema
});
const InitializeRequestSchema = RequestSchema.extend({
  method: literal("initialize"),
  params: InitializeRequestParamsSchema
});
const ServerCapabilitiesSchema = object({
  /**
   * Experimental, non-standard capabilities that the server supports.
   */
  experimental: record(string(), AssertObjectSchema).optional(),
  /**
   * Present if the server supports sending log messages to the client.
   */
  logging: AssertObjectSchema.optional(),
  /**
   * Present if the server supports sending completions to the client.
   */
  completions: AssertObjectSchema.optional(),
  /**
   * Present if the server offers any prompt templates.
   */
  prompts: object({
    /**
     * Whether this server supports issuing notifications for changes to the prompt list.
     */
    listChanged: boolean().optional()
  }).optional(),
  /**
   * Present if the server offers any resources to read.
   */
  resources: object({
    /**
     * Whether this server supports clients subscribing to resource updates.
     */
    subscribe: boolean().optional(),
    /**
     * Whether this server supports issuing notifications for changes to the resource list.
     */
    listChanged: boolean().optional()
  }).optional(),
  /**
   * Present if the server offers any tools to call.
   */
  tools: object({
    /**
     * Whether this server supports issuing notifications for changes to the tool list.
     */
    listChanged: boolean().optional()
  }).optional(),
  /**
   * Present if the server supports task creation.
   */
  tasks: ServerTasksCapabilitySchema.optional(),
  /**
   * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).
   */
  extensions: record(string(), AssertObjectSchema).optional()
});
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: string(),
  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: string().optional()
});
const InitializedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/initialized"),
  params: NotificationsParamsSchema.optional()
});
const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;
const PingRequestSchema = RequestSchema.extend({
  method: literal("ping"),
  params: BaseRequestParamsSchema.optional()
});
const ProgressSchema = object({
  /**
   * The progress thus far. This should increase every time progress is made, even if the total is unknown.
   */
  progress: number$1(),
  /**
   * Total number of items to process (or total progress required), if known.
   */
  total: optional(number$1()),
  /**
   * An optional message describing the current progress.
   */
  message: optional(string())
});
const ProgressNotificationParamsSchema = object({
  ...NotificationsParamsSchema.shape,
  ...ProgressSchema.shape,
  /**
   * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
   */
  progressToken: ProgressTokenSchema
});
const ProgressNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/progress"),
  params: ProgressNotificationParamsSchema
});
const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
  /**
   * An opaque token representing the current pagination position.
   * If provided, the server should return results starting after this cursor.
   */
  cursor: CursorSchema.optional()
});
const PaginatedRequestSchema = RequestSchema.extend({
  params: PaginatedRequestParamsSchema.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: CursorSchema.optional()
});
const TaskStatusSchema = _enum$3(["working", "input_required", "completed", "failed", "cancelled"]);
const TaskSchema = object({
  taskId: string(),
  status: TaskStatusSchema,
  /**
   * Time in milliseconds to keep task results available after completion.
   * If null, the task has unlimited lifetime until manually cleaned up.
   */
  ttl: union([number$1(), _null()]),
  /**
   * ISO 8601 timestamp when the task was created.
   */
  createdAt: string(),
  /**
   * ISO 8601 timestamp when the task was last updated.
   */
  lastUpdatedAt: string(),
  pollInterval: optional(number$1()),
  /**
   * Optional diagnostic message for failed tasks or other status information.
   */
  statusMessage: optional(string())
});
const CreateTaskResultSchema = ResultSchema.extend({
  task: TaskSchema
});
const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
const TaskStatusNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/tasks/status"),
  params: TaskStatusNotificationParamsSchema
});
const GetTaskRequestSchema = RequestSchema.extend({
  method: literal("tasks/get"),
  params: BaseRequestParamsSchema.extend({
    taskId: string()
  })
});
const GetTaskResultSchema = ResultSchema.merge(TaskSchema);
const GetTaskPayloadRequestSchema = RequestSchema.extend({
  method: literal("tasks/result"),
  params: BaseRequestParamsSchema.extend({
    taskId: string()
  })
});
ResultSchema.loose();
const ListTasksRequestSchema = PaginatedRequestSchema.extend({
  method: literal("tasks/list")
});
const ListTasksResultSchema = PaginatedResultSchema.extend({
  tasks: array(TaskSchema)
});
const CancelTaskRequestSchema = RequestSchema.extend({
  method: literal("tasks/cancel"),
  params: BaseRequestParamsSchema.extend({
    taskId: string()
  })
});
const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
const ResourceContentsSchema = object({
  /**
   * The URI of this resource.
   */
  uri: string(),
  /**
   * The MIME type of this resource, if known.
   */
  mimeType: optional(string()),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string(), unknown()).optional()
});
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: string()
});
const Base64Schema = string().refine((val) => {
  try {
    atob(val);
    return true;
  } catch {
    return false;
  }
}, { message: "Invalid Base64 string" });
const BlobResourceContentsSchema = ResourceContentsSchema.extend({
  /**
   * A base64-encoded string representing the binary data of the item.
   */
  blob: Base64Schema
});
const RoleSchema = _enum$3(["user", "assistant"]);
const AnnotationsSchema = object({
  /**
   * Intended audience(s) for the resource.
   */
  audience: array(RoleSchema).optional(),
  /**
   * Importance hint for the resource, from 0 (least) to 1 (most).
   */
  priority: number$1().min(0).max(1).optional(),
  /**
   * ISO 8601 timestamp for the most recent modification.
   */
  lastModified: datetime({ offset: true }).optional()
});
const ResourceSchema = object({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  /**
   * The URI of this resource.
   */
  uri: string(),
  /**
   * 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: optional(string()),
  /**
   * The MIME type of this resource, if known.
   */
  mimeType: optional(string()),
  /**
   * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.
   *
   * This can be used by Hosts to display file sizes and estimate context window usage.
   */
  size: optional(number$1()),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optional(looseObject({}))
});
const ResourceTemplateSchema = object({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  /**
   * A URI template (according to RFC 6570) that can be used to construct resource URIs.
   */
  uriTemplate: string(),
  /**
   * 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: optional(string()),
  /**
   * 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: optional(string()),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optional(looseObject({}))
});
const ListResourcesRequestSchema = PaginatedRequestSchema.extend({
  method: literal("resources/list")
});
const ListResourcesResultSchema = PaginatedResultSchema.extend({
  resources: array(ResourceSchema)
});
const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
  method: literal("resources/templates/list")
});
const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
  resourceTemplates: array(ResourceTemplateSchema)
});
const ResourceRequestParamsSchema = 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.
   *
   * @format uri
   */
  uri: string()
});
const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
const ReadResourceRequestSchema = RequestSchema.extend({
  method: literal("resources/read"),
  params: ReadResourceRequestParamsSchema
});
const ReadResourceResultSchema = ResultSchema.extend({
  contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))
});
const ResourceListChangedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/resources/list_changed"),
  params: NotificationsParamsSchema.optional()
});
const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
const SubscribeRequestSchema = RequestSchema.extend({
  method: literal("resources/subscribe"),
  params: SubscribeRequestParamsSchema
});
const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
const UnsubscribeRequestSchema = RequestSchema.extend({
  method: literal("resources/unsubscribe"),
  params: UnsubscribeRequestParamsSchema
});
const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.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: string()
});
const ResourceUpdatedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/resources/updated"),
  params: ResourceUpdatedNotificationParamsSchema
});
const PromptArgumentSchema = object({
  /**
   * The name of the argument.
   */
  name: string(),
  /**
   * A human-readable description of the argument.
   */
  description: optional(string()),
  /**
   * Whether this argument must be provided.
   */
  required: optional(boolean())
});
const PromptSchema = object({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  /**
   * An optional description of what this prompt provides
   */
  description: optional(string()),
  /**
   * A list of arguments to use for templating the prompt.
   */
  arguments: optional(array(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: optional(looseObject({}))
});
const ListPromptsRequestSchema = PaginatedRequestSchema.extend({
  method: literal("prompts/list")
});
const ListPromptsResultSchema = PaginatedResultSchema.extend({
  prompts: array(PromptSchema)
});
const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
  /**
   * The name of the prompt or prompt template.
   */
  name: string(),
  /**
   * Arguments to use for templating the prompt.
   */
  arguments: record(string(), string()).optional()
});
const GetPromptRequestSchema = RequestSchema.extend({
  method: literal("prompts/get"),
  params: GetPromptRequestParamsSchema
});
const TextContentSchema = object({
  type: literal("text"),
  /**
   * The text content of the message.
   */
  text: string(),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string(), unknown()).optional()
});
const ImageContentSchema = object({
  type: literal("image"),
  /**
   * The base64-encoded image data.
   */
  data: Base64Schema,
  /**
   * The MIME type of the image. Different providers may support different image types.
   */
  mimeType: string(),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string(), unknown()).optional()
});
const AudioContentSchema = object({
  type: literal("audio"),
  /**
   * The base64-encoded audio data.
   */
  data: Base64Schema,
  /**
   * The MIME type of the audio. Different providers may support different audio types.
   */
  mimeType: string(),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string(), unknown()).optional()
});
const ToolUseContentSchema = object({
  type: literal("tool_use"),
  /**
   * The name of the tool to invoke.
   * Must match a tool name from the request's tools array.
   */
  name: string(),
  /**
   * Unique identifier for this tool call.
   * Used to correlate with ToolResultContent in subsequent messages.
   */
  id: string(),
  /**
   * Arguments to pass to the tool.
   * Must conform to the tool's inputSchema.
   */
  input: record(string(), unknown()),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string(), unknown()).optional()
});
const EmbeddedResourceSchema = object({
  type: literal("resource"),
  resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string(), unknown()).optional()
});
const ResourceLinkSchema = ResourceSchema.extend({
  type: literal("resource_link")
});
const ContentBlockSchema = union([
  TextContentSchema,
  ImageContentSchema,
  AudioContentSchema,
  ResourceLinkSchema,
  EmbeddedResourceSchema
]);
const PromptMessageSchema = object({
  role: RoleSchema,
  content: ContentBlockSchema
});
const GetPromptResultSchema = ResultSchema.extend({
  /**
   * An optional description for the prompt.
   */
  description: string().optional(),
  messages: array(PromptMessageSchema)
});
const PromptListChangedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/prompts/list_changed"),
  params: NotificationsParamsSchema.optional()
});
const ToolAnnotationsSchema = object({
  /**
   * A human-readable title for the tool.
   */
  title: string().optional(),
  /**
   * If true, the tool does not modify its environment.
   *
   * Default: false
   */
  readOnlyHint: boolean().optional(),
  /**
   * 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: boolean().optional(),
  /**
   * 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: boolean().optional(),
  /**
   * 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: boolean().optional()
});
const ToolExecutionSchema = object({
  /**
   * Indicates the tool's preference for task-augmented execution.
   * - "required": Clients MUST invoke the tool as a task
   * - "optional": Clients MAY invoke the tool as a task or normal request
   * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task
   *
   * If not present, defaults to "forbidden".
   */
  taskSupport: _enum$3(["required", "optional", "forbidden"]).optional()
});
const ToolSchema = object({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  /**
   * A human-readable description of the tool.
   */
  description: string().optional(),
  /**
   * A JSON Schema 2020-12 object defining the expected parameters for the tool.
   * Must have type: 'object' at the root level per MCP spec.
   */
  inputSchema: object({
    type: literal("object"),
    properties: record(string(), AssertObjectSchema).optional(),
    required: array(string()).optional()
  }).catchall(unknown()),
  /**
   * An optional JSON Schema 2020-12 object defining the structure of the tool's output
   * returned in the structuredContent field of a CallToolResult.
   * Must have type: 'object' at the root level per MCP spec.
   */
  outputSchema: object({
    type: literal("object"),
    properties: record(string(), AssertObjectSchema).optional(),
    required: array(string()).optional()
  }).catchall(unknown()).optional(),
  /**
   * Optional additional tool information.
   */
  annotations: ToolAnnotationsSchema.optional(),
  /**
   * Execution-related properties for this tool.
   */
  execution: ToolExecutionSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string(), unknown()).optional()
});
const ListToolsRequestSchema = PaginatedRequestSchema.extend({
  method: literal("tools/list")
});
const ListToolsResultSchema = PaginatedResultSchema.extend({
  tools: array(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: array(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: record(string(), unknown()).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: boolean().optional()
});
const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
  toolResult: unknown()
}));
const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
  /**
   * The name of the tool to call.
   */
  name: string(),
  /**
   * Arguments to pass to the tool.
   */
  arguments: record(string(), unknown()).optional()
});
const CallToolRequestSchema = RequestSchema.extend({
  method: literal("tools/call"),
  params: CallToolRequestParamsSchema
});
const ToolListChangedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/tools/list_changed"),
  params: NotificationsParamsSchema.optional()
});
const ListChangedOptionsBaseSchema = object({
  /**
   * If true, the list will be refreshed automatically when a list changed notification is received.
   * The callback will be called with the updated list.
   *
   * If false, the callback will be called with null items, allowing manual refresh.
   *
   * @default true
   */
  autoRefresh: boolean().default(true),
  /**
   * Debounce time in milliseconds for list changed notification processing.
   *
   * Multiple notifications received within this timeframe will only trigger one refresh.
   * Set to 0 to disable debouncing.
   *
   * @default 300
   */
  debounceMs: number$1().int().nonnegative().default(300)
});
const LoggingLevelSchema = _enum$3(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
const SetLevelRequestParamsSchema = 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 SetLevelRequestSchema = RequestSchema.extend({
  method: literal("logging/setLevel"),
  params: SetLevelRequestParamsSchema
});
const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
  /**
   * The severity of this log message.
   */
  level: LoggingLevelSchema,
  /**
   * An optional name of the logger issuing this message.
   */
  logger: string().optional(),
  /**
   * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
   */
  data: unknown()
});
const LoggingMessageNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/message"),
  params: LoggingMessageNotificationParamsSchema
});
const ModelHintSchema = object({
  /**
   * A hint for a model name.
   */
  name: string().optional()
});
const ModelPreferencesSchema = object({
  /**
   * Optional hints to use for model selection.
   */
  hints: array(ModelHintSchema).optional(),
  /**
   * How much to prioritize cost when selecting a model.
   */
  costPriority: number$1().min(0).max(1).optional(),
  /**
   * How much to prioritize sampling speed (latency) when selecting a model.
   */
  speedPriority: number$1().min(0).max(1).optional(),
  /**
   * How much to prioritize intelligence and capabilities when selecting a model.
   */
  intelligencePriority: number$1().min(0).max(1).optional()
});
const ToolChoiceSchema = object({
  /**
   * Controls when tools are used:
   * - "auto": Model decides whether to use tools (default)
   * - "required": Model MUST use at least one tool before completing
   * - "none": Model MUST NOT use any tools
   */
  mode: _enum$3(["auto", "required", "none"]).optional()
});
const ToolResultContentSchema = object({
  type: literal("tool_result"),
  toolUseId: string().describe("The unique identifier for the corresponding tool call."),
  content: array(ContentBlockSchema).default([]),
  structuredContent: object({}).loose().optional(),
  isError: boolean().optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string(), unknown()).optional()
});
const SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
const SamplingMessageContentBlockSchema = discriminatedUnion("type", [
  TextContentSchema,
  ImageContentSchema,
  AudioContentSchema,
  ToolUseContentSchema,
  ToolResultContentSchema
]);
const SamplingMessageSchema = object({
  role: RoleSchema,
  content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string(), unknown()).optional()
});
const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
  messages: array(SamplingMessageSchema),
  /**
   * The server's preferences for which model to select. The client MAY modify or omit this request.
   */
  modelPreferences: ModelPreferencesSchema.optional(),
  /**
   * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
   */
  systemPrompt: string().optional(),
  /**
   * 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.
   *
   * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client
   * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
   */
  includeContext: _enum$3(["none", "thisServer", "allServers"]).optional(),
  temperature: number$1().optional(),
  /**
   * The requested maximum number of tokens to sample (to prevent runaway completions).
   *
   * The client MAY choose to sample fewer tokens than the requested maximum.
   */
  maxTokens: number$1().int(),
  stopSequences: array(string()).optional(),
  /**
   * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
   */
  metadata: AssertObjectSchema.optional(),
  /**
   * Tools that the model may use during generation.
   * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
   */
  tools: array(ToolSchema).optional(),
  /**
   * Controls how the model uses tools.
   * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
   * Default is `{ mode: "auto" }`.
   */
  toolChoice: ToolChoiceSchema.optional()
});
const CreateMessageRequestSchema = RequestSchema.extend({
  method: literal("sampling/createMessage"),
  params: CreateMessageRequestParamsSchema
});
const CreateMessageResultSchema = ResultSchema.extend({
  /**
   * The name of the model that generated the message.
   */
  model: string(),
  /**
   * The reason why sampling stopped, if known.
   *
   * Standard values:
   * - "endTurn": Natural end of the assistant's turn
   * - "stopSequence": A stop sequence was encountered
   * - "maxTokens": Maximum token limit was reached
   *
   * This field is an open string to allow for provider-specific stop reasons.
   */
  stopReason: optional(_enum$3(["endTurn", "stopSequence", "maxTokens"]).or(string())),
  role: RoleSchema,
  /**
   * Response content. Single content block (text, image, or audio).
   */
  content: SamplingContentSchema
});
const CreateMessageResultWithToolsSchema = ResultSchema.extend({
  /**
   * The name of the model that generated the message.
   */
  model: string(),
  /**
   * The reason why sampling stopped, if known.
   *
   * Standard values:
   * - "endTurn": Natural end of the assistant's turn
   * - "stopSequence": A stop sequence was encountered
   * - "maxTokens": Maximum token limit was reached
   * - "toolUse": The model wants to use one or more tools
   *
   * This field is an open string to allow for provider-specific stop reasons.
   */
  stopReason: optional(_enum$3(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string())),
  role: RoleSchema,
  /**
   * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
   */
  content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
});
const BooleanSchemaSchema = object({
  type: literal("boolean"),
  title: string().optional(),
  description: string().optional(),
  default: boolean().optional()
});
const StringSchemaSchema = object({
  type: literal("string"),
  title: string().optional(),
  description: string().optional(),
  minLength: number$1().optional(),
  maxLength: number$1().optional(),
  format: _enum$3(["email", "uri", "date", "date-time"]).optional(),
  default: string().optional()
});
const NumberSchemaSchema = object({
  type: _enum$3(["number", "integer"]),
  title: string().optional(),
  description: string().optional(),
  minimum: number$1().optional(),
  maximum: number$1().optional(),
  default: number$1().optional()
});
const UntitledSingleSelectEnumSchemaSchema = object({
  type: literal("string"),
  title: string().optional(),
  description: string().optional(),
  enum: array(string()),
  default: string().optional()
});
const TitledSingleSelectEnumSchemaSchema = object({
  type: literal("string"),
  title: string().optional(),
  description: string().optional(),
  oneOf: array(object({
    const: string(),
    title: string()
  })),
  default: string().optional()
});
const LegacyTitledEnumSchemaSchema = object({
  type: literal("string"),
  title: string().optional(),
  description: string().optional(),
  enum: array(string()),
  enumNames: array(string()).optional(),
  default: string().optional()
});
const SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
const UntitledMultiSelectEnumSchemaSchema = object({
  type: literal("array"),
  title: string().optional(),
  description: string().optional(),
  minItems: number$1().optional(),
  maxItems: number$1().optional(),
  items: object({
    type: literal("string"),
    enum: array(string())
  }),
  default: array(string()).optional()
});
const TitledMultiSelectEnumSchemaSchema = object({
  type: literal("array"),
  title: string().optional(),
  description: string().optional(),
  minItems: number$1().optional(),
  maxItems: number$1().optional(),
  items: object({
    anyOf: array(object({
      const: string(),
      title: string()
    }))
  }),
  default: array(string()).optional()
});
const MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
const EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
const PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
  /**
   * The elicitation mode.
   *
   * Optional for backward compatibility. Clients MUST treat missing mode as "form".
   */
  mode: literal("form").optional(),
  /**
   * The message to present to the user describing what information is being requested.
   */
  message: string(),
  /**
   * A restricted subset of JSON Schema.
   * Only top-level properties are allowed, without nesting.
   */
  requestedSchema: object({
    type: literal("object"),
    properties: record(string(), PrimitiveSchemaDefinitionSchema),
    required: array(string()).optional()
  })
});
const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
  /**
   * The elicitation mode.
   */
  mode: literal("url"),
  /**
   * The message to present to the user explaining why the interaction is needed.
   */
  message: string(),
  /**
   * The ID of the elicitation, which must be unique within the context of the server.
   * The client MUST treat this ID as an opaque value.
   */
  elicitationId: string(),
  /**
   * The URL that the user should navigate to.
   */
  url: string().url()
});
const ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
const ElicitRequestSchema = RequestSchema.extend({
  method: literal("elicitation/create"),
  params: ElicitRequestParamsSchema
});
const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
  /**
   * The ID of the elicitation that completed.
   */
  elicitationId: string()
});
const ElicitationCompleteNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/elicitation/complete"),
  params: ElicitationCompleteNotificationParamsSchema
});
const ElicitResultSchema = ResultSchema.extend({
  /**
   * The user action in response to the elicitation.
   * - "accept": User submitted the form/confirmed the action
   * - "decline": User explicitly decline the action
   * - "cancel": User dismissed without making an explicit choice
   */
  action: _enum$3(["accept", "decline", "cancel"]),
  /**
   * The submitted form data, only present when action is "accept".
   * Contains values matching the requested schema.
   * Per MCP spec, content is "typically omitted" for decline/cancel actions.
   * We normalize null to undefined for leniency while maintaining type compatibility.
   */
  content: preprocess((val) => val === null ? void 0 : val, record(string(), union([string(), number$1(), boolean(), array(string())])).optional())
});
const ResourceTemplateReferenceSchema = object({
  type: literal("ref/resource"),
  /**
   * The URI or URI template of the resource.
   */
  uri: string()
});
const PromptReferenceSchema = object({
  type: literal("ref/prompt"),
  /**
   * The name of the prompt or prompt template
   */
  name: string()
});
const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
  ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
  /**
   * The argument's information
   */
  argument: object({
    /**
     * The name of the argument
     */
    name: string(),
    /**
     * The value of the argument to use for completion matching.
     */
    value: string()
  }),
  context: object({
    /**
     * Previously-resolved variables in a URI template or prompt.
     */
    arguments: record(string(), string()).optional()
  }).optional()
});
const CompleteRequestSchema = RequestSchema.extend({
  method: literal("completion/complete"),
  params: CompleteRequestParamsSchema
});
const CompleteResultSchema = ResultSchema.extend({
  completion: looseObject({
    /**
     * An array of completion values. Must not exceed 100 items.
     */
    values: array(string()).max(100),
    /**
     * The total number of completion options available. This can exceed the number of values actually sent in the response.
     */
    total: optional(number$1().int()),
    /**
     * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
     */
    hasMore: optional(boolean())
  })
});
const RootSchema = object({
  /**
   * The URI identifying the root. This *must* start with file:// for now.
   */
  uri: string().startsWith("file://"),
  /**
   * An optional name for the root.
   */
  name: string().optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string(), unknown()).optional()
});
const ListRootsRequestSchema = RequestSchema.extend({
  method: literal("roots/list"),
  params: BaseRequestParamsSchema.optional()
});
const ListRootsResultSchema = ResultSchema.extend({
  roots: array(RootSchema)
});
const RootsListChangedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/roots/list_changed"),
  params: NotificationsParamsSchema.optional()
});
union([
  PingRequestSchema,
  InitializeRequestSchema,
  CompleteRequestSchema,
  SetLevelRequestSchema,
  GetPromptRequestSchema,
  ListPromptsRequestSchema,
  ListResourcesRequestSchema,
  ListResourceTemplatesRequestSchema,
  ReadResourceRequestSchema,
  SubscribeRequestSchema,
  UnsubscribeRequestSchema,
  CallToolRequestSchema,
  ListToolsRequestSchema,
  GetTaskRequestSchema,
  GetTaskPayloadRequestSchema,
  ListTasksRequestSchema,
  CancelTaskRequestSchema
]);
union([
  CancelledNotificationSchema,
  ProgressNotificationSchema,
  InitializedNotificationSchema,
  RootsListChangedNotificationSchema,
  TaskStatusNotificationSchema
]);
union([
  EmptyResultSchema,
  CreateMessageResultSchema,
  CreateMessageResultWithToolsSchema,
  ElicitResultSchema,
  ListRootsResultSchema,
  GetTaskResultSchema,
  ListTasksResultSchema,
  CreateTaskResultSchema
]);
union([
  PingRequestSchema,
  CreateMessageRequestSchema,
  ElicitRequestSchema,
  ListRootsRequestSchema,
  GetTaskRequestSchema,
  GetTaskPayloadRequestSchema,
  ListTasksRequestSchema,
  CancelTaskRequestSchema
]);
union([
  CancelledNotificationSchema,
  ProgressNotificationSchema,
  LoggingMessageNotificationSchema,
  ResourceUpdatedNotificationSchema,
  ResourceListChangedNotificationSchema,
  ToolListChangedNotificationSchema,
  PromptListChangedNotificationSchema,
  TaskStatusNotificationSchema,
  ElicitationCompleteNotificationSchema
]);
union([
  EmptyResultSchema,
  InitializeResultSchema,
  CompleteResultSchema,
  GetPromptResultSchema,
  ListPromptsResultSchema,
  ListResourcesResultSchema,
  ListResourceTemplatesResultSchema,
  ReadResourceResultSchema,
  CallToolResultSchema,
  ListToolsResultSchema,
  GetTaskResultSchema,
  ListTasksResultSchema,
  CreateTaskResultSchema
]);
class McpError extends Error {
  constructor(code2, message, data2) {
    super(`MCP error ${code2}: ${message}`);
    this.code = code2;
    this.data = data2;
    this.name = "McpError";
  }
  /**
   * Factory method to create the appropriate error type based on the error code and data
   */
  static fromError(code2, message, data2) {
    if (code2 === ErrorCode.UrlElicitationRequired && data2) {
      const errorData = data2;
      if (errorData.elicitations) {
        return new UrlElicitationRequiredError(errorData.elicitations, message);
      }
    }
    return new McpError(code2, message, data2);
  }
}
class UrlElicitationRequiredError extends McpError {
  constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
    super(ErrorCode.UrlElicitationRequired, message, {
      elicitations
    });
  }
  get elicitations() {
    return this.data?.elicitations ?? [];
  }
}
const SafeUrlSchema = url().superRefine((val, ctx) => {
  if (!URL.canParse(val)) {
    ctx.addIssue({
      code: ZodIssueCode$1.custom,
      message: "URL must be parseable",
      fatal: true
    });
    return NEVER;
  }
}).refine((url2) => {
  const u2 = new URL(url2);
  return u2.protocol !== "javascript:" && u2.protocol !== "data:" && u2.protocol !== "vbscript:";
}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" });
const OAuthProtectedResourceMetadataSchema = looseObject({
  resource: string().url(),
  authorization_servers: array(SafeUrlSchema).optional(),
  jwks_uri: string().url().optional(),
  scopes_supported: array(string()).optional(),
  bearer_methods_supported: array(string()).optional(),
  resource_signing_alg_values_supported: array(string()).optional(),
  resource_name: string().optional(),
  resource_documentation: string().optional(),
  resource_policy_uri: string().url().optional(),
  resource_tos_uri: string().url().optional(),
  tls_client_certificate_bound_access_tokens: boolean().optional(),
  authorization_details_types_supported: array(string()).optional(),
  dpop_signing_alg_values_supported: array(string()).optional(),
  dpop_bound_access_tokens_required: boolean().optional()
});
const OAuthMetadataSchema = looseObject({
  issuer: string(),
  authorization_endpoint: SafeUrlSchema,
  token_endpoint: SafeUrlSchema,
  registration_endpoint: SafeUrlSchema.optional(),
  scopes_supported: array(string()).optional(),
  response_types_supported: array(string()),
  response_modes_supported: array(string()).optional(),
  grant_types_supported: array(string()).optional(),
  token_endpoint_auth_methods_supported: array(string()).optional(),
  token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
  service_documentation: SafeUrlSchema.optional(),
  revocation_endpoint: SafeUrlSchema.optional(),
  revocation_endpoint_auth_methods_supported: array(string()).optional(),
  revocation_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
  introspection_endpoint: string().optional(),
  introspection_endpoint_auth_methods_supported: array(string()).optional(),
  introspection_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
  code_challenge_methods_supported: array(string()).optional(),
  client_id_metadata_document_supported: boolean().optional()
});
const OpenIdProviderMetadataSchema = looseObject({
  issuer: string(),
  authorization_endpoint: SafeUrlSchema,
  token_endpoint: SafeUrlSchema,
  userinfo_endpoint: SafeUrlSchema.optional(),
  jwks_uri: SafeUrlSchema,
  registration_endpoint: SafeUrlSchema.optional(),
  scopes_supported: array(string()).optional(),
  response_types_supported: array(string()),
  response_modes_supported: array(string()).optional(),
  grant_types_supported: array(string()).optional(),
  acr_values_supported: array(string()).optional(),
  subject_types_supported: array(string()),
  id_token_signing_alg_values_supported: array(string()),
  id_token_encryption_alg_values_supported: array(string()).optional(),
  id_token_encryption_enc_values_supported: array(string()).optional(),
  userinfo_signing_alg_values_supported: array(string()).optional(),
  userinfo_encryption_alg_values_supported: array(string()).optional(),
  userinfo_encryption_enc_values_supported: array(string()).optional(),
  request_object_signing_alg_values_supported: array(string()).optional(),
  request_object_encryption_alg_values_supported: array(string()).optional(),
  request_object_encryption_enc_values_supported: array(string()).optional(),
  token_endpoint_auth_methods_supported: array(string()).optional(),
  token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
  display_values_supported: array(string()).optional(),
  claim_types_supported: array(string()).optional(),
  claims_supported: array(string()).optional(),
  service_documentation: string().optional(),
  claims_locales_supported: array(string()).optional(),
  ui_locales_supported: array(string()).optional(),
  claims_parameter_supported: boolean().optional(),
  request_parameter_supported: boolean().optional(),
  request_uri_parameter_supported: boolean().optional(),
  require_request_uri_registration: boolean().optional(),
  op_policy_uri: SafeUrlSchema.optional(),
  op_tos_uri: SafeUrlSchema.optional(),
  client_id_metadata_document_supported: boolean().optional()
});
const OpenIdProviderDiscoveryMetadataSchema = object({
  ...OpenIdProviderMetadataSchema.shape,
  ...OAuthMetadataSchema.pick({
    code_challenge_methods_supported: true
  }).shape
});
const OAuthTokensSchema = object({
  access_token: string(),
  id_token: string().optional(),
  // Optional for OAuth 2.1, but necessary in OpenID Connect
  token_type: string(),
  expires_in: number().optional(),
  scope: string().optional(),
  refresh_token: string().optional()
}).strip();
const OAuthErrorResponseSchema = object({
  error: string(),
  error_description: string().optional(),
  error_uri: string().optional()
});
const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0));
const OAuthClientMetadataSchema = object({
  redirect_uris: array(SafeUrlSchema),
  token_endpoint_auth_method: string().optional(),
  grant_types: array(string()).optional(),
  response_types: array(string()).optional(),
  client_name: string().optional(),
  client_uri: SafeUrlSchema.optional(),
  logo_uri: OptionalSafeUrlSchema,
  scope: string().optional(),
  contacts: array(string()).optional(),
  tos_uri: OptionalSafeUrlSchema,
  policy_uri: string().optional(),
  jwks_uri: SafeUrlSchema.optional(),
  jwks: any().optional(),
  software_id: string().optional(),
  software_version: string().optional(),
  software_statement: string().optional()
}).strip();
const OAuthClientInformationSchema = object({
  client_id: string(),
  client_secret: string().optional(),
  client_id_issued_at: number$1().optional(),
  client_secret_expires_at: number$1().optional()
}).strip();
const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
object({
  error: string(),
  error_description: string().optional()
}).strip();
object({
  token: string(),
  token_type_hint: string().optional()
}).strip();
const name = "@modelcontextprotocol/inspector-client";
const version$1 = "0.22.0";
const packageJson = {
  name,
  version: version$1
};
const CLIENT_IDENTITY = (() => {
  const [, name2 = packageJson.name] = packageJson.name.split("/");
  const version2 = packageJson.version;
  return { name: name2, version: version2 };
})();
const SESSION_KEYS = {
  CODE_VERIFIER: "mcp_code_verifier",
  SERVER_URL: "mcp_server_url",
  TOKENS: "mcp_tokens",
  CLIENT_INFORMATION: "mcp_client_information",
  PREREGISTERED_CLIENT_INFORMATION: "mcp_preregistered_client_information",
  SERVER_METADATA: "mcp_server_metadata",
  AUTH_DEBUGGER_STATE: "mcp_auth_debugger_state",
  SCOPE: "mcp_scope"
};
const getServerSpecificKey = (baseKey, serverUrl) => {
  if (!serverUrl) return baseKey;
  return `[${serverUrl}] ${baseKey}`;
};
const DEFAULT_MCP_PROXY_LISTEN_PORT = "6277";
const MCP_PROXY_TRANSPORT_ERROR_CODE = -32099;
const DEFAULT_INSPECTOR_CONFIG = {
  MCP_SERVER_REQUEST_TIMEOUT: {
    label: "Request Timeout",
    description: "Client-side timeout (ms) - Inspector will cancel requests after this time",
    value: 3e5,
    // 5 minutes - increased to support elicitation and other long-running tools
    is_session_item: false
  },
  MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS: {
    label: "Reset Timeout on Progress",
    description: "Reset timeout on progress notifications",
    value: true,
    is_session_item: false
  },
  MCP_REQUEST_MAX_TOTAL_TIMEOUT: {
    label: "Maximum Total Timeout",
    description: "Maximum total timeout for requests sent to the MCP server (ms) (Use with progress notifications)",
    value: 6e4,
    is_session_item: false
  },
  MCP_PROXY_FULL_ADDRESS: {
    label: "Inspector Proxy Address",
    description: "Set this if you are running the MCP Inspector Proxy on a non-default address. Example: http://10.1.1.22:5577",
    value: "",
    is_session_item: false
  },
  MCP_PROXY_AUTH_TOKEN: {
    label: "Proxy Session Token",
    description: "Session token for authenticating with the MCP Proxy Server (displayed in proxy console on startup)",
    value: "",
    is_session_item: true
  },
  MCP_TASK_TTL: {
    label: "Task TTL",
    description: "Default Time-to-Live (TTL) in milliseconds for newly created tasks",
    value: 6e4,
    is_session_item: false
  }
};
const META_PREFIX_LABEL_REGEX = /^[a-z](?:[a-z\d-]*[a-z\d])?$/i;
const META_NAME_REGEX = /^[a-z\d](?:[a-z\d._-]*[a-z\d])?$/i;
const RESERVED_NAMESPACE_LABELS = ["modelcontextprotocol", "mcp"];
const RESERVED_NAMESPACE_MESSAGE = 'Keys using the "modelcontextprotocol.*" or "mcp.*" namespaces are reserved by MCP and cannot be used.';
const META_NAME_RULES_MESSAGE = "Names must begin and end with an alphanumeric character and may only contain alphanumerics, hyphens (-), underscores (_), or dots (.) in between.";
const META_PREFIX_RULES_MESSAGE = "Prefixes must be dot-separated labels that start with a letter and end with a letter or digit (e.g. example.domain/).";
const getPrefixSegment = (key) => {
  const trimmedKey = key.trim();
  const slashIndex = trimmedKey.indexOf("/");
  if (slashIndex === -1) {
    return null;
  }
  return trimmedKey.slice(0, slashIndex);
};
const normalizeSegment = (segment) => {
  if (!segment) return null;
  let normalized = segment.trim().toLowerCase();
  if (!normalized) return null;
  const schemeIndex = normalized.indexOf("://");
  if (schemeIndex !== -1) {
    normalized = normalized.slice(schemeIndex + 3);
  }
  const stopChars = ["?", "#", ":"];
  let endIndex = normalized.length;
  stopChars.forEach((char) => {
    const idx = normalized.indexOf(char);
    if (idx !== -1 && idx < endIndex) {
      endIndex = idx;
    }
  });
  return normalized.slice(0, endIndex) || null;
};
const splitLabels = (segment) => {
  const normalized = normalizeSegment(segment);
  if (!normalized) return null;
  const labels = normalized.split(".");
  if (labels.length === 0 || labels.some((label) => !label || !META_PREFIX_LABEL_REGEX.test(label))) {
    return null;
  }
  return labels;
};
const isReservedMetaKey = (key) => {
  const trimmedKey = key.trim();
  if (!trimmedKey) {
    return false;
  }
  const candidateSegment = getPrefixSegment(trimmedKey) ?? trimmedKey;
  const labels = splitLabels(candidateSegment);
  if (!labels || labels.length < 2) {
    return false;
  }
  for (let i2 = 0; i2 < labels.length - 1; i2 += 1) {
    const current = labels[i2];
    const next = labels[i2 + 1];
    if (RESERVED_NAMESPACE_LABELS.includes(current) && META_PREFIX_LABEL_REGEX.test(next)) {
      return true;
    }
  }
  return false;
};
const hasValidMetaPrefix = (key) => {
  const prefixSegment = getPrefixSegment(key);
  if (prefixSegment === null) {
    return true;
  }
  return splitLabels(prefixSegment) !== null;
};
const extractMetaName = (key) => {
  const trimmedKey = key.trim();
  if (!trimmedKey) return "";
  const slashIndex = trimmedKey.lastIndexOf("/");
  if (slashIndex === -1) {
    return trimmedKey;
  }
  return trimmedKey.slice(slashIndex + 1);
};
const hasValidMetaName = (key) => {
  const name2 = extractMetaName(key);
  if (!name2) return false;
  return META_NAME_REGEX.test(name2);
};
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(e2) {
      return obj[e2];
    });
  };
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => {
    const keys = [];
    for (const key in object2) {
      if (Object.prototype.hasOwnProperty.call(object2, key)) {
        keys.push(key);
      }
    }
    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(array2, separator = " | ") {
    return array2.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;
(function(objectUtil2) {
  objectUtil2.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second
      // second overwrites first
    };
  };
})(objectUtil || (objectUtil = {}));
const ZodParsedType = 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 = (data2) => {
  const t2 = typeof data2;
  switch (t2) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return Number.isNaN(data2) ? 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":
      if (Array.isArray(data2)) {
        return ZodParsedType.array;
      }
      if (data2 === null) {
        return ZodParsedType.null;
      }
      if (data2.then && typeof data2.then === "function" && data2.catch && typeof data2.catch === "function") {
        return ZodParsedType.promise;
      }
      if (typeof Map !== "undefined" && data2 instanceof Map) {
        return ZodParsedType.map;
      }
      if (typeof Set !== "undefined" && data2 instanceof Set) {
        return ZodParsedType.set;
      }
      if (typeof Date !== "undefined" && data2 instanceof Date) {
        return ZodParsedType.date;
      }
      return ZodParsedType.object;
    default:
      return ZodParsedType.unknown;
  }
};
const ZodIssueCode = 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"
]);
class ZodError 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(issue2) {
      return issue2.message;
    };
    const fieldErrors = { _errors: [] };
    const processError = (error) => {
      for (const issue2 of error.issues) {
        if (issue2.code === "invalid_union") {
          issue2.unionErrors.map(processError);
        } else if (issue2.code === "invalid_return_type") {
          processError(issue2.returnTypeError);
        } else if (issue2.code === "invalid_arguments") {
          processError(issue2.argumentsError);
        } else if (issue2.path.length === 0) {
          fieldErrors._errors.push(mapper(issue2));
        } else {
          let curr = fieldErrors;
          let i2 = 0;
          while (i2 < issue2.path.length) {
            const el2 = issue2.path[i2];
            const terminal = i2 === issue2.path.length - 1;
            if (!terminal) {
              curr[el2] = curr[el2] || { _errors: [] };
            } else {
              curr[el2] = curr[el2] || { _errors: [] };
              curr[el2]._errors.push(mapper(issue2));
            }
            curr = curr[el2];
            i2++;
          }
        }
      }
    };
    processError(this);
    return fieldErrors;
  }
  static assert(value) {
    if (!(value instanceof ZodError)) {
      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 = (issue2) => issue2.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.create = (issues) => {
  const error = new ZodError(issues);
  return error;
};
const errorMap = (issue2, _ctx) => {
  let message;
  switch (issue2.code) {
    case ZodIssueCode.invalid_type:
      if (issue2.received === ZodParsedType.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue2.expected}, received ${issue2.received}`;
      }
      break;
    case ZodIssueCode.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util$3.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util$3.joinValues(issue2.keys, ", ")}`;
      break;
    case ZodIssueCode.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util$3.joinValues(issue2.options)}`;
      break;
    case ZodIssueCode.invalid_enum_value:
      message = `Invalid enum value. Expected ${util$3.joinValues(issue2.options)}, received '${issue2.received}'`;
      break;
    case ZodIssueCode.invalid_arguments:
      message = `Invalid function arguments`;
      break;
    case ZodIssueCode.invalid_return_type:
      message = `Invalid function return type`;
      break;
    case ZodIssueCode.invalid_date:
      message = `Invalid date`;
      break;
    case ZodIssueCode.invalid_string:
      if (typeof issue2.validation === "object") {
        if ("includes" in issue2.validation) {
          message = `Invalid input: must include "${issue2.validation.includes}"`;
          if (typeof issue2.validation.position === "number") {
            message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`;
          }
        } else if ("startsWith" in issue2.validation) {
          message = `Invalid input: must start with "${issue2.validation.startsWith}"`;
        } else if ("endsWith" in issue2.validation) {
          message = `Invalid input: must end with "${issue2.validation.endsWith}"`;
        } else {
          util$3.assertNever(issue2.validation);
        }
      } else if (issue2.validation !== "regex") {
        message = `Invalid ${issue2.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode.too_small:
      if (issue2.type === "array")
        message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`;
      else if (issue2.type === "string")
        message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`;
      else if (issue2.type === "number")
        message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
      else if (issue2.type === "bigint")
        message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
      else if (issue2.type === "date")
        message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.too_big:
      if (issue2.type === "array")
        message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`;
      else if (issue2.type === "string")
        message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`;
      else if (issue2.type === "number")
        message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
      else if (issue2.type === "bigint")
        message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
      else if (issue2.type === "date")
        message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode.not_multiple_of:
      message = `Number must be a multiple of ${issue2.multipleOf}`;
      break;
    case ZodIssueCode.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util$3.assertNever(issue2);
  }
  return { message };
};
let overrideErrorMap = errorMap;
function getErrorMap() {
  return overrideErrorMap;
}
const makeIssue = (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((m2) => !!m2).slice().reverse();
  for (const map of maps) {
    errorMessage = map(fullIssue, { data: data2, defaultError: errorMessage }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: errorMessage
  };
};
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue2 = makeIssue({
    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 ? void 0 : errorMap
      // then global default map
    ].filter((x2) => !!x2)
  });
  ctx.common.issues.push(issue2);
}
class ParseStatus {
  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;
      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 key = await pair.key;
      const value = await pair.value;
      syncPairs.push({
        key,
        value
      });
    }
    return ParseStatus.mergeObjectSync(status, syncPairs);
  }
  static mergeObjectSync(status, pairs) {
    const finalObject = {};
    for (const pair of pairs) {
      const { key, value } = pair;
      if (key.status === "aborted")
        return INVALID;
      if (value.status === "aborted")
        return INVALID;
      if (key.status === "dirty")
        status.dirty();
      if (value.status === "dirty")
        status.dirty();
      if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key.value] = value.value;
      }
    }
    return { status: status.value, value: finalObject };
  }
}
const INVALID = Object.freeze({
  status: "aborted"
});
const DIRTY = (value) => ({ status: "dirty", value });
const OK = (value) => ({ status: "valid", value });
const isAborted = (x2) => x2.status === "aborted";
const isDirty = (x2) => x2.status === "dirty";
const isValid = (x2) => x2.status === "valid";
const isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise;
var errorUtil;
(function(errorUtil2) {
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));
class ParseInputLazyPath {
  constructor(parent, value, path, key) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path;
    this._key = key;
  }
  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 = (ctx, result) => {
  if (isValid(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(ctx.common.issues);
        this._error = error;
        return this._error;
      }
    };
  }
};
function processCreateParams(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 };
}
class ZodType {
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus(),
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync(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?.async ?? false,
        contextualErrorMap: params?.errorMap
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data: data2,
      parsedType: getParsedType(data2)
    };
    const result = this._parseSync({ data: data2, path: ctx.path, parent: ctx });
    return handleResult(ctx, result);
  }
  "~validate"(data2) {
    const ctx = {
      common: {
        issues: [],
        async: !!this["~standard"].async
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data: data2,
      parsedType: getParsedType(data2)
    };
    if (!this["~standard"].async) {
      try {
        const result = this._parseSync({ data: data2, path: [], parent: ctx });
        return isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        };
      } catch (err) {
        if (err?.message?.toLowerCase()?.includes("encountered")) {
          this["~standard"].async = true;
        }
        ctx.common = {
          issues: [],
          async: true
        };
      }
    }
    return this._parseAsync({ data: data2, path: [], parent: ctx }).then((result) => isValid(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?.errorMap,
        async: true
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data: data2,
      parsedType: getParsedType(data2)
    };
    const maybeAsyncResult = this._parse({ data: data2, path: ctx.path, parent: ctx });
    const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult(ctx, result);
  }
  refine(check2, 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 = check2(val);
      const setError = () => ctx.addIssue({
        code: ZodIssueCode.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(check2, refinementData) {
    return this._refinement((val, ctx) => {
      if (!check2(val)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects({
      schema: this,
      typeName: ZodFirstPartyTypeKind.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.create(this, this._def);
  }
  nullable() {
    return ZodNullable.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray.create(this);
  }
  promise() {
    return ZodPromise.create(this, this._def);
  }
  or(option) {
    return ZodUnion.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection.create(this, incoming, this._def);
  }
  transform(transform2) {
    return new ZodEffects({
      ...processCreateParams(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "transform", transform: transform2 }
    });
  }
  default(def) {
    const defaultValueFunc = typeof def === "function" ? def : () => def;
    return new ZodDefault({
      ...processCreateParams(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodDefault
    });
  }
  brand() {
    return new ZodBranded({
      typeName: ZodFirstPartyTypeKind.ZodBranded,
      type: this,
      ...processCreateParams(this._def)
    });
  }
  catch(def) {
    const catchValueFunc = typeof def === "function" ? def : () => def;
    return new ZodCatch({
      ...processCreateParams(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodCatch
    });
  }
  describe(description2) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description: description2
    });
  }
  pipe(target) {
    return ZodPipeline.create(this, target);
  }
  readonly() {
    return ZodReadonly.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
}
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[0-9a-z]+$/;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
const 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;
const nanoidRegex = /^[a-z0-9_-]{21}$/i;
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
const 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)?)??$/;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
const _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])$/;
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 = /^(([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 = /^([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 = `((\\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 = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(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(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(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(ip2, version2) {
  if ((version2 === "v4" || !version2) && ipv4Regex.test(ip2)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6Regex.test(ip2)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    if (!header)
      return false;
    const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base642));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip2, version2) {
  if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip2)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip2)) {
    return true;
  }
  return false;
}
class ZodString extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.string,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check2 of this._def.checks) {
      if (check2.kind === "min") {
        if (input.data.length < check2.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check2.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "max") {
        if (input.data.length > check2.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check2.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "length") {
        const tooBig = input.data.length > check2.value;
        const tooSmall = input.data.length < check2.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: check2.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check2.message
            });
          } else if (tooSmall) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: check2.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check2.message
            });
          }
          status.dirty();
        }
      } else if (check2.kind === "email") {
        if (!emailRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "email",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "emoji") {
        if (!emojiRegex) {
          emojiRegex = new RegExp(_emojiRegex, "u");
        }
        if (!emojiRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "uuid") {
        if (!uuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "nanoid") {
        if (!nanoidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "nanoid",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "cuid") {
        if (!cuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "cuid2") {
        if (!cuid2Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "ulid") {
        if (!ulidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "url") {
        try {
          new URL(input.data);
        } catch {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "url",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "regex") {
        check2.regex.lastIndex = 0;
        const testResult = check2.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "trim") {
        input.data = input.data.trim();
      } else if (check2.kind === "includes") {
        if (!input.data.includes(check2.value, check2.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { includes: check2.value, position: check2.position },
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check2.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check2.kind === "startsWith") {
        if (!input.data.startsWith(check2.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { startsWith: check2.value },
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "endsWith") {
        if (!input.data.endsWith(check2.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { endsWith: check2.value },
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "datetime") {
        const regex = datetimeRegex(check2);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "datetime",
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "date") {
        const regex = dateRegex;
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "date",
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "time") {
        const regex = timeRegex(check2);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "time",
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "duration") {
        if (!durationRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "duration",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "ip") {
        if (!isValidIP(input.data, check2.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "jwt") {
        if (!isValidJWT(input.data, check2.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "jwt",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "cidr") {
        if (!isValidCidr(input.data, check2.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cidr",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "base64") {
        if (!base64Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "base64url") {
        if (!base64urlRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64url",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else {
        util$3.assertNever(check2);
      }
    }
    return { status: status.value, value: input.data };
  }
  _regex(regex, validation2, message) {
    return this.refinement((data2) => regex.test(data2), {
      validation: validation2,
      code: ZodIssueCode.invalid_string,
      ...errorUtil.errToObj(message)
    });
  }
  _addCheck(check2) {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, check2]
    });
  }
  email(message) {
    return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  }
  url(message) {
    return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  }
  emoji(message) {
    return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  }
  uuid(message) {
    return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  }
  nanoid(message) {
    return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  }
  cuid(message) {
    return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  }
  cuid2(message) {
    return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  }
  ulid(message) {
    return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  }
  base64(message) {
    return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
  }
  base64url(message) {
    return this._addCheck({
      kind: "base64url",
      ...errorUtil.errToObj(message)
    });
  }
  jwt(options) {
    return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
  }
  ip(options) {
    return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  }
  cidr(options) {
    return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
  }
  datetime(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      offset: options?.offset ?? false,
      local: options?.local ?? false,
      ...errorUtil.errToObj(options?.message)
    });
  }
  date(message) {
    return this._addCheck({ kind: "date", message });
  }
  time(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      ...errorUtil.errToObj(options?.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  }
  regex(regex, message) {
    return this._addCheck({
      kind: "regex",
      regex,
      ...errorUtil.errToObj(message)
    });
  }
  includes(value, options) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options?.position,
      ...errorUtil.errToObj(options?.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil.errToObj(message)
    });
  }
  /**
   * Equivalent to `.min(1)`
   */
  nonempty(message) {
    return this.min(1, errorUtil.errToObj(message));
  }
  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((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.create = (params) => {
  return new ZodString({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodString,
    coerce: params?.coerce ?? false,
    ...processCreateParams(params)
  });
};
function floatSafeRemainder(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;
}
class ZodNumber extends ZodType {
  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.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.number,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check2 of this._def.checks) {
      if (check2.kind === "int") {
        if (!util$3.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: "integer",
            received: "float",
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "min") {
        const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check2.value,
            type: "number",
            inclusive: check2.inclusive,
            exact: false,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "max") {
        const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check2.value,
            type: "number",
            inclusive: check2.inclusive,
            exact: false,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "multipleOf") {
        if (floatSafeRemainder(input.data, check2.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check2.value,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_finite,
            message: check2.message
          });
          status.dirty();
        }
      } else {
        util$3.assertNever(check2);
      }
    }
    return { status: status.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodNumber({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check2) {
    return new ZodNumber({
      ...this._def,
      checks: [...this._def.checks, check2]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil.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.create = (params) => {
  return new ZodNumber({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodNumber,
    coerce: params?.coerce || false,
    ...processCreateParams(params)
  });
};
class ZodBigInt extends ZodType {
  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.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check2 of this._def.checks) {
      if (check2.kind === "min") {
        const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            type: "bigint",
            minimum: check2.value,
            inclusive: check2.inclusive,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "max") {
        const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            type: "bigint",
            maximum: check2.value,
            inclusive: check2.inclusive,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "multipleOf") {
        if (input.data % check2.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check2.value,
            message: check2.message
          });
          status.dirty();
        }
      } else {
        util$3.assertNever(check2);
      }
    }
    return { status: status.value, value: input.data };
  }
  _getInvalidInput(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.bigint,
      received: ctx.parsedType
    });
    return INVALID;
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodBigInt({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check2) {
    return new ZodBigInt({
      ...this._def,
      checks: [...this._def.checks, check2]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.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.create = (params) => {
  return new ZodBigInt({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodBigInt,
    coerce: params?.coerce ?? false,
    ...processCreateParams(params)
  });
};
class ZodBoolean extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.boolean,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodBoolean.create = (params) => {
  return new ZodBoolean({
    typeName: ZodFirstPartyTypeKind.ZodBoolean,
    coerce: params?.coerce || false,
    ...processCreateParams(params)
  });
};
class ZodDate extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.date,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    if (Number.isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_date
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check2 of this._def.checks) {
      if (check2.kind === "min") {
        if (input.data.getTime() < check2.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            message: check2.message,
            inclusive: true,
            exact: false,
            minimum: check2.value,
            type: "date"
          });
          status.dirty();
        }
      } else if (check2.kind === "max") {
        if (input.data.getTime() > check2.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            message: check2.message,
            inclusive: true,
            exact: false,
            maximum: check2.value,
            type: "date"
          });
          status.dirty();
        }
      } else {
        util$3.assertNever(check2);
      }
    }
    return {
      status: status.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check2) {
    return new ZodDate({
      ...this._def,
      checks: [...this._def.checks, check2]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil.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.create = (params) => {
  return new ZodDate({
    checks: [],
    coerce: params?.coerce || false,
    typeName: ZodFirstPartyTypeKind.ZodDate,
    ...processCreateParams(params)
  });
};
class ZodSymbol extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.symbol,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodSymbol.create = (params) => {
  return new ZodSymbol({
    typeName: ZodFirstPartyTypeKind.ZodSymbol,
    ...processCreateParams(params)
  });
};
class ZodUndefined extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.undefined,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodUndefined.create = (params) => {
  return new ZodUndefined({
    typeName: ZodFirstPartyTypeKind.ZodUndefined,
    ...processCreateParams(params)
  });
};
class ZodNull extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.null,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodNull.create = (params) => {
  return new ZodNull({
    typeName: ZodFirstPartyTypeKind.ZodNull,
    ...processCreateParams(params)
  });
};
class ZodAny extends ZodType {
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK(input.data);
  }
}
ZodAny.create = (params) => {
  return new ZodAny({
    typeName: ZodFirstPartyTypeKind.ZodAny,
    ...processCreateParams(params)
  });
};
class ZodUnknown extends ZodType {
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK(input.data);
  }
}
ZodUnknown.create = (params) => {
  return new ZodUnknown({
    typeName: ZodFirstPartyTypeKind.ZodUnknown,
    ...processCreateParams(params)
  });
};
class ZodNever extends ZodType {
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.never,
      received: ctx.parsedType
    });
    return INVALID;
  }
}
ZodNever.create = (params) => {
  return new ZodNever({
    typeName: ZodFirstPartyTypeKind.ZodNever,
    ...processCreateParams(params)
  });
};
class ZodVoid extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.void,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodVoid.create = (params) => {
  return new ZodVoid({
    typeName: ZodFirstPartyTypeKind.ZodVoid,
    ...processCreateParams(params)
  });
};
class ZodArray extends ZodType {
  _parse(input) {
    const { ctx, status } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext(ctx, {
          code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.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(ctx, {
          code: ZodIssueCode.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(ctx, {
          code: ZodIssueCode.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(ctx, item, ctx.path, i2));
      })).then((result2) => {
        return ParseStatus.mergeArray(status, result2);
      });
    }
    const result = [...ctx.data].map((item, i2) => {
      return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
    });
    return ParseStatus.mergeArray(status, result);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new ZodArray({
      ...this._def,
      minLength: { value: minLength, message: errorUtil.toString(message) }
    });
  }
  max(maxLength, message) {
    return new ZodArray({
      ...this._def,
      maxLength: { value: maxLength, message: errorUtil.toString(message) }
    });
  }
  length(len, message) {
    return new ZodArray({
      ...this._def,
      exactLength: { value: len, message: errorUtil.toString(message) }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
}
ZodArray.create = (schema, params) => {
  return new ZodArray({
    type: schema,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind.ZodArray,
    ...processCreateParams(params)
  });
};
function deepPartialify(schema) {
  if (schema instanceof ZodObject) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray) {
    return new ZodArray({
      ...schema._def,
      type: deepPartialify(schema.element)
    });
  } else if (schema instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple) {
    return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  } else {
    return schema;
  }
}
class ZodObject extends ZodType {
  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.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const { status, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
      for (const key in ctx.data) {
        if (!shapeKeys.includes(key)) {
          extraKeys.push(key);
        }
      }
    }
    const pairs = [];
    for (const key of shapeKeys) {
      const keyValidator = shape[key];
      const value = ctx.data[key];
      pairs.push({
        key: { status: "valid", value: key },
        value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key of extraKeys) {
          pairs.push({
            key: { status: "valid", value: key },
            value: { status: "valid", value: ctx.data[key] }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.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 key of extraKeys) {
        const value = ctx.data[key];
        pairs.push({
          key: { status: "valid", value: key },
          value: catchall._parse(
            new ParseInputLazyPath(ctx, value, ctx.path, key)
            //, ctx.child(key), value, getParsedType(value)
          ),
          alwaysSet: key in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus.mergeObjectSync(status, syncPairs);
      });
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil.errToObj;
    return new ZodObject({
      ...this._def,
      unknownKeys: "strict",
      ...message !== void 0 ? {
        errorMap: (issue2, ctx) => {
          const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError;
          if (issue2.code === "unrecognized_keys")
            return {
              message: errorUtil.errToObj(message).message ?? defaultError
            };
          return {
            message: defaultError
          };
        }
      } : {}
    });
  }
  strip() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new ZodObject({
      ...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 ZodObject({
      ...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 ZodObject({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: () => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }),
      typeName: ZodFirstPartyTypeKind.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(key, schema) {
    return this.augment({ [key]: 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 ZodObject({
      ...this._def,
      catchall: index2
    });
  }
  pick(mask) {
    const shape = {};
    for (const key of util$3.objectKeys(mask)) {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    for (const key of util$3.objectKeys(this.shape)) {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    for (const key of util$3.objectKeys(this.shape)) {
      const fieldSchema = this.shape[key];
      if (mask && !mask[key]) {
        newShape[key] = fieldSchema;
      } else {
        newShape[key] = fieldSchema.optional();
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  required(mask) {
    const newShape = {};
    for (const key of util$3.objectKeys(this.shape)) {
      if (mask && !mask[key]) {
        newShape[key] = this.shape[key];
      } else {
        const fieldSchema = this.shape[key];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional) {
          newField = newField._def.innerType;
        }
        newShape[key] = newField;
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  keyof() {
    return createZodEnum(util$3.objectKeys(this.shape));
  }
}
ZodObject.create = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.strictCreate = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strict",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.lazycreate = (shape, params) => {
  return new ZodObject({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
class ZodUnion extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const options = 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(result.ctx.common.issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return Promise.all(options.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 options) {
        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(issues2));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
}
ZodUnion.create = (types2, params) => {
  return new ZodUnion({
    options: types2,
    typeName: ZodFirstPartyTypeKind.ZodUnion,
    ...processCreateParams(params)
  });
};
function mergeValues(a2, b2) {
  const aType = getParsedType(a2);
  const bType = getParsedType(b2);
  if (a2 === b2) {
    return { valid: true, data: a2 };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util$3.objectKeys(b2);
    const sharedKeys = util$3.objectKeys(a2).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a2, ...b2 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a2[key], b2[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.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(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a2 === +b2) {
    return { valid: true, data: a2 };
  } else {
    return { valid: false };
  }
}
class ZodIntersection extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const handleParsed = (parsedLeft, parsedRight) => {
      if (isAborted(parsedLeft) || isAborted(parsedRight)) {
        return INVALID;
      }
      const merged = mergeValues(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_intersection_types
        });
        return INVALID;
      }
      if (isDirty(parsedLeft) || isDirty(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.create = (left, right, params) => {
  return new ZodIntersection({
    left,
    right,
    typeName: ZodFirstPartyTypeKind.ZodIntersection,
    ...processCreateParams(params)
  });
};
class ZodTuple extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.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(ctx, item, ctx.path, itemIndex));
    }).filter((x2) => !!x2);
    if (ctx.common.async) {
      return Promise.all(items2).then((results) => {
        return ParseStatus.mergeArray(status, results);
      });
    } else {
      return ParseStatus.mergeArray(status, items2);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest) {
    return new ZodTuple({
      ...this._def,
      rest
    });
  }
}
ZodTuple.create = (schemas, params) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple({
    items: schemas,
    typeName: ZodFirstPartyTypeKind.ZodTuple,
    rest: null,
    ...processCreateParams(params)
  });
};
class ZodMap extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.map) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.map,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key, value], index2) => {
      return {
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])),
        value: valueType._parse(new ParseInputLazyPath(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 key = await pair.key;
          const value = await pair.value;
          if (key.status === "aborted" || value.status === "aborted") {
            return INVALID;
          }
          if (key.status === "dirty" || value.status === "dirty") {
            status.dirty();
          }
          finalMap.set(key.value, value.value);
        }
        return { status: status.value, value: finalMap };
      });
    } else {
      const finalMap = /* @__PURE__ */ new Map();
      for (const pair of pairs) {
        const key = pair.key;
        const value = pair.value;
        if (key.status === "aborted" || value.status === "aborted") {
          return INVALID;
        }
        if (key.status === "dirty" || value.status === "dirty") {
          status.dirty();
        }
        finalMap.set(key.value, value.value);
      }
      return { status: status.value, value: finalMap };
    }
  }
}
ZodMap.create = (keyType, valueType, params) => {
  return new ZodMap({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind.ZodMap,
    ...processCreateParams(params)
  });
};
class ZodSet extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.set) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.set,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.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(ctx, {
          code: ZodIssueCode.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;
        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(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 ZodSet({
      ...this._def,
      minSize: { value: minSize, message: errorUtil.toString(message) }
    });
  }
  max(maxSize, message) {
    return new ZodSet({
      ...this._def,
      maxSize: { value: maxSize, message: errorUtil.toString(message) }
    });
  }
  size(size2, message) {
    return this.min(size2, message).max(size2, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
}
ZodSet.create = (valueType, params) => {
  return new ZodSet({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind.ZodSet,
    ...processCreateParams(params)
  });
};
class ZodLazy extends ZodType {
  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.create = (getter, params) => {
  return new ZodLazy({
    getter,
    typeName: ZodFirstPartyTypeKind.ZodLazy,
    ...processCreateParams(params)
  });
};
class ZodLiteral extends ZodType {
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_literal,
        expected: this._def.value
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
}
ZodLiteral.create = (value, params) => {
  return new ZodLiteral({
    value,
    typeName: ZodFirstPartyTypeKind.ZodLiteral,
    ...processCreateParams(params)
  });
};
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
class ZodEnum extends ZodType {
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        expected: util$3.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    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(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(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 ZodEnum.create(values, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values, newDef = this._def) {
    return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
}
ZodEnum.create = createZodEnum;
class ZodNativeEnum extends ZodType {
  _parse(input) {
    const nativeEnumValues = util$3.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
      const expectedValues = util$3.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        expected: util$3.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    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(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get enum() {
    return this._def.values;
  }
}
ZodNativeEnum.create = (values, params) => {
  return new ZodNativeEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
    ...processCreateParams(params)
  });
};
class ZodPromise extends ZodType {
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.promise,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK(promisified.then((data2) => {
      return this._def.type.parseAsync(data2, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
}
ZodPromise.create = (schema, params) => {
  return new ZodPromise({
    type: schema,
    typeName: ZodFirstPartyTypeKind.ZodPromise,
    ...processCreateParams(params)
  });
};
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(input) {
    const { status, ctx } = this._processInputParams(input);
    const effect = this._def.effect || null;
    const checkCtx = {
      addIssue: (arg) => {
        addIssueToContext(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;
          const result = await this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
          if (result.status === "aborted")
            return INVALID;
          if (result.status === "dirty")
            return DIRTY(result.value);
          if (status.value === "dirty")
            return DIRTY(result.value);
          return result;
        });
      } else {
        if (status.value === "aborted")
          return INVALID;
        const result = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result.status === "aborted")
          return INVALID;
        if (result.status === "dirty")
          return DIRTY(result.value);
        if (status.value === "dirty")
          return DIRTY(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;
        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;
          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 base = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid(base))
          return INVALID;
        const result = effect.transform(base.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((base) => {
          if (!isValid(base))
            return INVALID;
          return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
            status: status.value,
            value: result
          }));
        });
      }
    }
    util$3.assertNever(effect);
  }
}
ZodEffects.create = (schema, effect, params) => {
  return new ZodEffects({
    schema,
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    effect,
    ...processCreateParams(params)
  });
};
ZodEffects.createWithPreprocess = (preprocess2, schema, params) => {
  return new ZodEffects({
    schema,
    effect: { type: "preprocess", transform: preprocess2 },
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    ...processCreateParams(params)
  });
};
class ZodOptional extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.undefined) {
      return OK(void 0);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodOptional.create = (type2, params) => {
  return new ZodOptional({
    innerType: type2,
    typeName: ZodFirstPartyTypeKind.ZodOptional,
    ...processCreateParams(params)
  });
};
class ZodNullable extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.null) {
      return OK(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodNullable.create = (type2, params) => {
  return new ZodNullable({
    innerType: type2,
    typeName: ZodFirstPartyTypeKind.ZodNullable,
    ...processCreateParams(params)
  });
};
class ZodDefault extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data2 = ctx.data;
    if (ctx.parsedType === ZodParsedType.undefined) {
      data2 = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data: data2,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
}
ZodDefault.create = (type2, params) => {
  return new ZodDefault({
    innerType: type2,
    typeName: ZodFirstPartyTypeKind.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams(params)
  });
};
class ZodCatch extends ZodType {
  _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(result)) {
      return result.then((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.value : this._def.catchValue({
            get error() {
              return new ZodError(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
}
ZodCatch.create = (type2, params) => {
  return new ZodCatch({
    innerType: type2,
    typeName: ZodFirstPartyTypeKind.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams(params)
  });
};
class ZodNaN extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.nan,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
}
ZodNaN.create = (params) => {
  return new ZodNaN({
    typeName: ZodFirstPartyTypeKind.ZodNaN,
    ...processCreateParams(params)
  });
};
class ZodBranded extends ZodType {
  _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;
  }
}
class ZodPipeline extends ZodType {
  _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;
        if (inResult.status === "dirty") {
          status.dirty();
          return DIRTY(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;
      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 ZodPipeline({
      in: a2,
      out: b2,
      typeName: ZodFirstPartyTypeKind.ZodPipeline
    });
  }
}
class ZodReadonly extends ZodType {
  _parse(input) {
    const result = this._def.innerType._parse(input);
    const freeze = (data2) => {
      if (isValid(data2)) {
        data2.value = Object.freeze(data2.value);
      }
      return data2;
    };
    return isAsync(result) ? result.then((data2) => freeze(data2)) : freeze(result);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodReadonly.create = (type2, params) => {
  return new ZodReadonly({
    innerType: type2,
    typeName: ZodFirstPartyTypeKind.ZodReadonly,
    ...processCreateParams(params)
  });
};
var ZodFirstPartyTypeKind;
(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 || (ZodFirstPartyTypeKind = {}));
ZodNever.create;
ZodArray.create;
const objectType = ZodObject.create;
ZodUnion.create;
ZodIntersection.create;
ZodTuple.create;
ZodEnum.create;
ZodPromise.create;
ZodOptional.create;
ZodNullable.create;
function isZ4Schema(s2) {
  const schema = s2;
  return !!schema._zod;
}
function safeParse(schema, data2) {
  if (isZ4Schema(schema)) {
    const result2 = safeParse$2(schema, data2);
    return result2;
  }
  const v3Schema = schema;
  const result = v3Schema.safeParse(data2);
  return result;
}
function getObjectShape(schema) {
  if (!schema)
    return void 0;
  let rawShape;
  if (isZ4Schema(schema)) {
    const v4Schema = schema;
    rawShape = v4Schema._zod?.def?.shape;
  } else {
    const v3Schema = schema;
    rawShape = v3Schema.shape;
  }
  if (!rawShape)
    return void 0;
  if (typeof rawShape === "function") {
    try {
      return rawShape();
    } catch {
      return void 0;
    }
  }
  return rawShape;
}
function getLiteralValue(schema) {
  if (isZ4Schema(schema)) {
    const v4Schema = schema;
    const def2 = v4Schema._zod?.def;
    if (def2) {
      if (def2.value !== void 0)
        return def2.value;
      if (Array.isArray(def2.values) && def2.values.length > 0) {
        return def2.values[0];
      }
    }
  }
  const v3Schema = schema;
  const def = v3Schema._def;
  if (def) {
    if (def.value !== void 0)
      return def.value;
    if (Array.isArray(def.values) && def.values.length > 0) {
      return def.values[0];
    }
  }
  const directValue = schema.value;
  if (directValue !== void 0)
    return directValue;
  return void 0;
}
function isTerminal(status) {
  return status === "completed" || status === "failed" || status === "cancelled";
}
new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function getMethodLiteral(schema) {
  const shape = getObjectShape(schema);
  const methodSchema = shape?.method;
  if (!methodSchema) {
    throw new Error("Schema is missing a method literal");
  }
  const value = getLiteralValue(methodSchema);
  if (typeof value !== "string") {
    throw new Error("Schema method literal must be a string");
  }
  return value;
}
function parseWithCompat(schema, data2) {
  const result = safeParse(schema, data2);
  if (!result.success) {
    throw result.error;
  }
  return result.data;
}
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._taskProgressTokens = /* @__PURE__ */ new Map();
    this._requestResolvers = /* @__PURE__ */ new Map();
    this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
      this._oncancel(notification);
    });
    this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
      this._onprogress(notification);
    });
    this.setRequestHandler(
      PingRequestSchema,
      // Automatic pong by default.
      (_request) => ({})
    );
    this._taskStore = _options?.taskStore;
    this._taskMessageQueue = _options?.taskMessageQueue;
    if (this._taskStore) {
      this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {
        const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
        if (!task) {
          throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
        }
        return {
          ...task
        };
      });
      this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
        const handleTaskResult = async () => {
          const taskId = request.params.taskId;
          if (this._taskMessageQueue) {
            let queuedMessage;
            while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
              if (queuedMessage.type === "response" || queuedMessage.type === "error") {
                const message = queuedMessage.message;
                const requestId = message.id;
                const resolver = this._requestResolvers.get(requestId);
                if (resolver) {
                  this._requestResolvers.delete(requestId);
                  if (queuedMessage.type === "response") {
                    resolver(message);
                  } else {
                    const errorMessage = message;
                    const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
                    resolver(error);
                  }
                } else {
                  const messageType = queuedMessage.type === "response" ? "Response" : "Error";
                  this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
                }
                continue;
              }
              await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });
            }
          }
          const task = await this._taskStore.getTask(taskId, extra.sessionId);
          if (!task) {
            throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
          }
          if (!isTerminal(task.status)) {
            await this._waitForTaskUpdate(taskId, extra.signal);
            return await handleTaskResult();
          }
          if (isTerminal(task.status)) {
            const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
            this._clearTaskQueue(taskId);
            return {
              ...result,
              _meta: {
                ...result._meta,
                [RELATED_TASK_META_KEY]: {
                  taskId
                }
              }
            };
          }
          return await handleTaskResult();
        };
        return await handleTaskResult();
      });
      this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {
        try {
          const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);
          return {
            tasks,
            nextCursor,
            _meta: {}
          };
        } catch (error) {
          throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);
        }
      });
      this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {
        try {
          const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
          if (!task) {
            throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);
          }
          if (isTerminal(task.status)) {
            throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
          }
          await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
          this._clearTaskQueue(request.params.taskId);
          const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
          if (!cancelledTask) {
            throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
          }
          return {
            _meta: {},
            ...cancelledTask
          };
        } catch (error) {
          if (error instanceof McpError) {
            throw error;
          }
          throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);
        }
      });
    }
  }
  async _oncancel(notification) {
    if (!notification.params.requestId) {
      return;
    }
    const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
    controller?.abort(notification.params.reason);
  }
  _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 McpError.fromError(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) {
    if (this._transport) {
      throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");
    }
    this._transport = transport;
    const _onclose = this.transport?.onclose;
    this._transport.onclose = () => {
      _onclose?.();
      this._onclose();
    };
    const _onerror = this.transport?.onerror;
    this._transport.onerror = (error) => {
      _onerror?.(error);
      this._onerror(error);
    };
    const _onmessage = this._transport?.onmessage;
    this._transport.onmessage = (message, extra) => {
      _onmessage?.(message, extra);
      if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(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() {
    const responseHandlers = this._responseHandlers;
    this._responseHandlers = /* @__PURE__ */ new Map();
    this._progressHandlers.clear();
    this._taskProgressTokens.clear();
    this._pendingDebouncedNotifications.clear();
    for (const info of this._timeoutInfo.values()) {
      clearTimeout(info.timeoutId);
    }
    this._timeoutInfo.clear();
    for (const controller of this._requestHandlerAbortControllers.values()) {
      controller.abort();
    }
    this._requestHandlerAbortControllers.clear();
    const error = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
    this._transport = void 0;
    this.onclose?.();
    for (const handler of responseHandlers.values()) {
      handler(error);
    }
  }
  _onerror(error) {
    this.onerror?.(error);
  }
  _onnotification(notification) {
    const handler = this._notificationHandlers.get(notification.method) ?? 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) {
    const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
    const capturedTransport = this._transport;
    const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
    if (handler === void 0) {
      const errorResponse = {
        jsonrpc: "2.0",
        id: request.id,
        error: {
          code: ErrorCode.MethodNotFound,
          message: "Method not found"
        }
      };
      if (relatedTaskId && this._taskMessageQueue) {
        this._enqueueTaskMessage(relatedTaskId, {
          type: "error",
          message: errorResponse,
          timestamp: Date.now()
        }, capturedTransport?.sessionId).catch((error) => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));
      } else {
        capturedTransport?.send(errorResponse).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 taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0;
    const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0;
    const fullExtra = {
      signal: abortController.signal,
      sessionId: capturedTransport?.sessionId,
      _meta: request.params?._meta,
      sendNotification: async (notification) => {
        if (abortController.signal.aborted)
          return;
        const notificationOptions = { relatedRequestId: request.id };
        if (relatedTaskId) {
          notificationOptions.relatedTask = { taskId: relatedTaskId };
        }
        await this.notification(notification, notificationOptions);
      },
      sendRequest: async (r2, resultSchema, options) => {
        if (abortController.signal.aborted) {
          throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
        }
        const requestOptions = { ...options, relatedRequestId: request.id };
        if (relatedTaskId && !requestOptions.relatedTask) {
          requestOptions.relatedTask = { taskId: relatedTaskId };
        }
        const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
        if (effectiveTaskId && taskStore) {
          await taskStore.updateTaskStatus(effectiveTaskId, "input_required");
        }
        return await this.request(r2, resultSchema, requestOptions);
      },
      authInfo: extra?.authInfo,
      requestId: request.id,
      requestInfo: extra?.requestInfo,
      taskId: relatedTaskId,
      taskStore,
      taskRequestedTtl: taskCreationParams?.ttl,
      closeSSEStream: extra?.closeSSEStream,
      closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
    };
    Promise.resolve().then(() => {
      if (taskCreationParams) {
        this.assertTaskHandlerCapability(request.method);
      }
    }).then(() => handler(request, fullExtra)).then(async (result) => {
      if (abortController.signal.aborted) {
        return;
      }
      const response = {
        result,
        jsonrpc: "2.0",
        id: request.id
      };
      if (relatedTaskId && this._taskMessageQueue) {
        await this._enqueueTaskMessage(relatedTaskId, {
          type: "response",
          message: response,
          timestamp: Date.now()
        }, capturedTransport?.sessionId);
      } else {
        await capturedTransport?.send(response);
      }
    }, async (error) => {
      if (abortController.signal.aborted) {
        return;
      }
      const errorResponse = {
        jsonrpc: "2.0",
        id: request.id,
        error: {
          code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError,
          message: error.message ?? "Internal error",
          ...error["data"] !== void 0 && { data: error["data"] }
        }
      };
      if (relatedTaskId && this._taskMessageQueue) {
        await this._enqueueTaskMessage(relatedTaskId, {
          type: "error",
          message: errorResponse,
          timestamp: Date.now()
        }, capturedTransport?.sessionId);
      } else {
        await capturedTransport?.send(errorResponse);
      }
    }).catch((error) => this._onerror(new Error(`Failed to send response: ${error}`))).finally(() => {
      if (this._requestHandlerAbortControllers.get(request.id) === abortController) {
        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) {
        this._responseHandlers.delete(messageId);
        this._progressHandlers.delete(messageId);
        this._cleanupTimeout(messageId);
        responseHandler(error);
        return;
      }
    }
    handler(params);
  }
  _onresponse(response) {
    const messageId = Number(response.id);
    const resolver = this._requestResolvers.get(messageId);
    if (resolver) {
      this._requestResolvers.delete(messageId);
      if (isJSONRPCResultResponse(response)) {
        resolver(response);
      } else {
        const error = new McpError(response.error.code, response.error.message, response.error.data);
        resolver(error);
      }
      return;
    }
    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._cleanupTimeout(messageId);
    let isTaskResponse = false;
    if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") {
      const result = response.result;
      if (result.task && typeof result.task === "object") {
        const task = result.task;
        if (typeof task.taskId === "string") {
          isTaskResponse = true;
          this._taskProgressTokens.set(task.taskId, messageId);
        }
      }
    }
    if (!isTaskResponse) {
      this._progressHandlers.delete(messageId);
    }
    if (isJSONRPCResultResponse(response)) {
      handler(response);
    } else {
      const error = McpError.fromError(response.error.code, response.error.message, response.error.data);
      handler(error);
    }
  }
  get transport() {
    return this._transport;
  }
  /**
   * Closes the connection.
   */
  async close() {
    await this._transport?.close();
  }
  /**
   * Sends a request and returns an AsyncGenerator that yields response messages.
   * The generator is guaranteed to end with either a 'result' or 'error' message.
   *
   * @example
   * ```typescript
   * const stream = protocol.requestStream(request, resultSchema, options);
   * for await (const message of stream) {
   *   switch (message.type) {
   *     case 'taskCreated':
   *       console.log('Task created:', message.task.taskId);
   *       break;
   *     case 'taskStatus':
   *       console.log('Task status:', message.task.status);
   *       break;
   *     case 'result':
   *       console.log('Final result:', message.result);
   *       break;
   *     case 'error':
   *       console.error('Error:', message.error);
   *       break;
   *   }
   * }
   * ```
   *
   * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
   */
  async *requestStream(request, resultSchema, options) {
    const { task } = options ?? {};
    if (!task) {
      try {
        const result = await this.request(request, resultSchema, options);
        yield { type: "result", result };
      } catch (error) {
        yield {
          type: "error",
          error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))
        };
      }
      return;
    }
    let taskId;
    try {
      const createResult = await this.request(request, CreateTaskResultSchema, options);
      if (createResult.task) {
        taskId = createResult.task.taskId;
        yield { type: "taskCreated", task: createResult.task };
      } else {
        throw new McpError(ErrorCode.InternalError, "Task creation did not return a task");
      }
      while (true) {
        const task2 = await this.getTask({ taskId }, options);
        yield { type: "taskStatus", task: task2 };
        if (isTerminal(task2.status)) {
          if (task2.status === "completed") {
            const result = await this.getTaskResult({ taskId }, resultSchema, options);
            yield { type: "result", result };
          } else if (task2.status === "failed") {
            yield {
              type: "error",
              error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)
            };
          } else if (task2.status === "cancelled") {
            yield {
              type: "error",
              error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)
            };
          }
          return;
        }
        if (task2.status === "input_required") {
          const result = await this.getTaskResult({ taskId }, resultSchema, options);
          yield { type: "result", result };
          return;
        }
        const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
        await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
        options?.signal?.throwIfAborted();
      }
    } catch (error) {
      yield {
        type: "error",
        error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))
      };
    }
  }
  /**
   * Sends a request and waits for a response.
   *
   * Do not use this method to emit notifications! Use notification() instead.
   */
  request(request, resultSchema, options) {
    const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
    return new Promise((resolve2, reject) => {
      const earlyReject = (error) => {
        reject(error);
      };
      if (!this._transport) {
        earlyReject(new Error("Not connected"));
        return;
      }
      if (this._options?.enforceStrictCapabilities === true) {
        try {
          this.assertCapabilityForMethod(request.method);
          if (task) {
            this.assertTaskCapability(request.method);
          }
        } catch (e2) {
          earlyReject(e2);
          return;
        }
      }
      options?.signal?.throwIfAborted();
      const messageId = this._requestMessageId++;
      const jsonrpcRequest = {
        ...request,
        jsonrpc: "2.0",
        id: messageId
      };
      if (options?.onprogress) {
        this._progressHandlers.set(messageId, options.onprogress);
        jsonrpcRequest.params = {
          ...request.params,
          _meta: {
            ...request.params?._meta || {},
            progressToken: messageId
          }
        };
      }
      if (task) {
        jsonrpcRequest.params = {
          ...jsonrpcRequest.params,
          task
        };
      }
      if (relatedTask) {
        jsonrpcRequest.params = {
          ...jsonrpcRequest.params,
          _meta: {
            ...jsonrpcRequest.params?._meta || {},
            [RELATED_TASK_META_KEY]: relatedTask
          }
        };
      }
      const cancel = (reason) => {
        this._responseHandlers.delete(messageId);
        this._progressHandlers.delete(messageId);
        this._cleanupTimeout(messageId);
        this._transport?.send({
          jsonrpc: "2.0",
          method: "notifications/cancelled",
          params: {
            requestId: messageId,
            reason: String(reason)
          }
        }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => this._onerror(new Error(`Failed to send cancellation: ${error2}`)));
        const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));
        reject(error);
      };
      this._responseHandlers.set(messageId, (response) => {
        if (options?.signal?.aborted) {
          return;
        }
        if (response instanceof Error) {
          return reject(response);
        }
        try {
          const parseResult = safeParse(resultSchema, response.result);
          if (!parseResult.success) {
            reject(parseResult.error);
          } else {
            resolve2(parseResult.data);
          }
        } catch (error) {
          reject(error);
        }
      });
      options?.signal?.addEventListener("abort", () => {
        cancel(options?.signal?.reason);
      });
      const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
      const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
      this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
      const relatedTaskId = relatedTask?.taskId;
      if (relatedTaskId) {
        const responseResolver = (response) => {
          const handler = this._responseHandlers.get(messageId);
          if (handler) {
            handler(response);
          } else {
            this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));
          }
        };
        this._requestResolvers.set(messageId, responseResolver);
        this._enqueueTaskMessage(relatedTaskId, {
          type: "request",
          message: jsonrpcRequest,
          timestamp: Date.now()
        }).catch((error) => {
          this._cleanupTimeout(messageId);
          reject(error);
        });
      } else {
        this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => {
          this._cleanupTimeout(messageId);
          reject(error);
        });
      }
    });
  }
  /**
   * Gets the current status of a task.
   *
   * @experimental Use `client.experimental.tasks.getTask()` to access this method.
   */
  async getTask(params, options) {
    return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options);
  }
  /**
   * Retrieves the result of a completed task.
   *
   * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.
   */
  async getTaskResult(params, resultSchema, options) {
    return this.request({ method: "tasks/result", params }, resultSchema, options);
  }
  /**
   * Lists tasks, optionally starting from a pagination cursor.
   *
   * @experimental Use `client.experimental.tasks.listTasks()` to access this method.
   */
  async listTasks(params, options) {
    return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options);
  }
  /**
   * Cancels a specific task.
   *
   * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.
   */
  async cancelTask(params, options) {
    return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options);
  }
  /**
   * Emits a notification, which is a one-way message that does not expect a response.
   */
  async notification(notification, options) {
    if (!this._transport) {
      throw new Error("Not connected");
    }
    this.assertNotificationCapability(notification.method);
    const relatedTaskId = options?.relatedTask?.taskId;
    if (relatedTaskId) {
      const jsonrpcNotification2 = {
        ...notification,
        jsonrpc: "2.0",
        params: {
          ...notification.params,
          _meta: {
            ...notification.params?._meta || {},
            [RELATED_TASK_META_KEY]: options.relatedTask
          }
        }
      };
      await this._enqueueTaskMessage(relatedTaskId, {
        type: "notification",
        message: jsonrpcNotification2,
        timestamp: Date.now()
      });
      return;
    }
    const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];
    const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;
    if (canDebounce) {
      if (this._pendingDebouncedNotifications.has(notification.method)) {
        return;
      }
      this._pendingDebouncedNotifications.add(notification.method);
      Promise.resolve().then(() => {
        this._pendingDebouncedNotifications.delete(notification.method);
        if (!this._transport) {
          return;
        }
        let jsonrpcNotification2 = {
          ...notification,
          jsonrpc: "2.0"
        };
        if (options?.relatedTask) {
          jsonrpcNotification2 = {
            ...jsonrpcNotification2,
            params: {
              ...jsonrpcNotification2.params,
              _meta: {
                ...jsonrpcNotification2.params?._meta || {},
                [RELATED_TASK_META_KEY]: options.relatedTask
              }
            }
          };
        }
        this._transport?.send(jsonrpcNotification2, options).catch((error) => this._onerror(error));
      });
      return;
    }
    let jsonrpcNotification = {
      ...notification,
      jsonrpc: "2.0"
    };
    if (options?.relatedTask) {
      jsonrpcNotification = {
        ...jsonrpcNotification,
        params: {
          ...jsonrpcNotification.params,
          _meta: {
            ...jsonrpcNotification.params?._meta || {},
            [RELATED_TASK_META_KEY]: options.relatedTask
          }
        }
      };
    }
    await this._transport.send(jsonrpcNotification, options);
  }
  /**
   * 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 = getMethodLiteral(requestSchema);
    this.assertRequestHandlerCapability(method);
    this._requestHandlers.set(method, (request, extra) => {
      const parsed = parseWithCompat(requestSchema, request);
      return Promise.resolve(handler(parsed, 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) {
    const method = getMethodLiteral(notificationSchema);
    this._notificationHandlers.set(method, (notification) => {
      const parsed = parseWithCompat(notificationSchema, notification);
      return Promise.resolve(handler(parsed));
    });
  }
  /**
   * Removes the notification handler for the given method.
   */
  removeNotificationHandler(method) {
    this._notificationHandlers.delete(method);
  }
  /**
   * Cleans up the progress handler associated with a task.
   * This should be called when a task reaches a terminal status.
   */
  _cleanupTaskProgressHandler(taskId) {
    const progressToken = this._taskProgressTokens.get(taskId);
    if (progressToken !== void 0) {
      this._progressHandlers.delete(progressToken);
      this._taskProgressTokens.delete(taskId);
    }
  }
  /**
   * Enqueues a task-related message for side-channel delivery via tasks/result.
   * @param taskId The task ID to associate the message with
   * @param message The message to enqueue
   * @param sessionId Optional session ID for binding the operation to a specific session
   * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
   *
   * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
   * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
   * simply propagates the error.
   */
  async _enqueueTaskMessage(taskId, message, sessionId) {
    if (!this._taskStore || !this._taskMessageQueue) {
      throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
    }
    const maxQueueSize = this._options?.maxTaskQueueSize;
    await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
  }
  /**
   * Clears the message queue for a task and rejects any pending request resolvers.
   * @param taskId The task ID whose queue should be cleared
   * @param sessionId Optional session ID for binding the operation to a specific session
   */
  async _clearTaskQueue(taskId, sessionId) {
    if (this._taskMessageQueue) {
      const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
      for (const message of messages) {
        if (message.type === "request" && isJSONRPCRequest(message.message)) {
          const requestId = message.message.id;
          const resolver = this._requestResolvers.get(requestId);
          if (resolver) {
            resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed"));
            this._requestResolvers.delete(requestId);
          } else {
            this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
          }
        }
      }
    }
  }
  /**
   * Waits for a task update (new messages or status change) with abort signal support.
   * Uses polling to check for updates at the task's configured poll interval.
   * @param taskId The task ID to wait for
   * @param signal Abort signal to cancel the wait
   * @returns Promise that resolves when an update occurs or rejects if aborted
   */
  async _waitForTaskUpdate(taskId, signal) {
    let interval = this._options?.defaultTaskPollInterval ?? 1e3;
    try {
      const task = await this._taskStore?.getTask(taskId);
      if (task?.pollInterval) {
        interval = task.pollInterval;
      }
    } catch {
    }
    return new Promise((resolve2, reject) => {
      if (signal.aborted) {
        reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
        return;
      }
      const timeoutId = setTimeout(resolve2, interval);
      signal.addEventListener("abort", () => {
        clearTimeout(timeoutId);
        reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
      }, { once: true });
    });
  }
  requestTaskStore(request, sessionId) {
    const taskStore = this._taskStore;
    if (!taskStore) {
      throw new Error("No task store configured");
    }
    return {
      createTask: async (taskParams) => {
        if (!request) {
          throw new Error("No request provided");
        }
        return await taskStore.createTask(taskParams, request.id, {
          method: request.method,
          params: request.params
        }, sessionId);
      },
      getTask: async (taskId) => {
        const task = await taskStore.getTask(taskId, sessionId);
        if (!task) {
          throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
        }
        return task;
      },
      storeTaskResult: async (taskId, status, result) => {
        await taskStore.storeTaskResult(taskId, status, result, sessionId);
        const task = await taskStore.getTask(taskId, sessionId);
        if (task) {
          const notification = TaskStatusNotificationSchema.parse({
            method: "notifications/tasks/status",
            params: task
          });
          await this.notification(notification);
          if (isTerminal(task.status)) {
            this._cleanupTaskProgressHandler(taskId);
          }
        }
      },
      getTaskResult: (taskId) => {
        return taskStore.getTaskResult(taskId, sessionId);
      },
      updateTaskStatus: async (taskId, status, statusMessage) => {
        const task = await taskStore.getTask(taskId, sessionId);
        if (!task) {
          throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
        }
        if (isTerminal(task.status)) {
          throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
        }
        await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
        const updatedTask = await taskStore.getTask(taskId, sessionId);
        if (updatedTask) {
          const notification = TaskStatusNotificationSchema.parse({
            method: "notifications/tasks/status",
            params: updatedTask
          });
          await this.notification(notification);
          if (isTerminal(updatedTask.status)) {
            this._cleanupTaskProgressHandler(taskId);
          }
        }
      },
      listTasks: (cursor) => {
        return taskStore.listTasks(cursor, sessionId);
      }
    };
  }
}
function isPlainObject$1(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
function mergeCapabilities(base, additional) {
  const result = { ...base };
  for (const key in additional) {
    const k2 = key;
    const addValue = additional[k2];
    if (addValue === void 0)
      continue;
    const baseValue = result[k2];
    if (isPlainObject$1(baseValue) && isPlainObject$1(addValue)) {
      result[k2] = { ...baseValue, ...addValue };
    } else {
      result[k2] = addValue;
    }
  }
  return result;
}
((X2) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(X2, { get: (Y2, Z2) => (typeof require < "u" ? require : Y2)[Z2] }) : X2)(function(X2) {
  if (typeof require < "u") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + X2 + '" is not supported');
});
var r = union([literal("light"), literal("dark")]).describe("Color theme preference for the host environment."), B$3 = union([literal("inline"), literal("fullscreen"), literal("pip")]).describe("Display mode for UI presentation."), HQ = union([literal("--color-background-primary"), literal("--color-background-secondary"), literal("--color-background-tertiary"), literal("--color-background-inverse"), literal("--color-background-ghost"), literal("--color-background-info"), literal("--color-background-danger"), literal("--color-background-success"), literal("--color-background-warning"), literal("--color-background-disabled"), literal("--color-text-primary"), literal("--color-text-secondary"), literal("--color-text-tertiary"), literal("--color-text-inverse"), literal("--color-text-ghost"), literal("--color-text-info"), literal("--color-text-danger"), literal("--color-text-success"), literal("--color-text-warning"), literal("--color-text-disabled"), literal("--color-border-primary"), literal("--color-border-secondary"), literal("--color-border-tertiary"), literal("--color-border-inverse"), literal("--color-border-ghost"), literal("--color-border-info"), literal("--color-border-danger"), literal("--color-border-success"), literal("--color-border-warning"), literal("--color-border-disabled"), literal("--color-ring-primary"), literal("--color-ring-secondary"), literal("--color-ring-inverse"), literal("--color-ring-info"), literal("--color-ring-danger"), literal("--color-ring-success"), literal("--color-ring-warning"), literal("--font-sans"), literal("--font-mono"), literal("--font-weight-normal"), literal("--font-weight-medium"), literal("--font-weight-semibold"), literal("--font-weight-bold"), literal("--font-text-xs-size"), literal("--font-text-sm-size"), literal("--font-text-md-size"), literal("--font-text-lg-size"), literal("--font-heading-xs-size"), literal("--font-heading-sm-size"), literal("--font-heading-md-size"), literal("--font-heading-lg-size"), literal("--font-heading-xl-size"), literal("--font-heading-2xl-size"), literal("--font-heading-3xl-size"), literal("--font-text-xs-line-height"), literal("--font-text-sm-line-height"), literal("--font-text-md-line-height"), literal("--font-text-lg-line-height"), literal("--font-heading-xs-line-height"), literal("--font-heading-sm-line-height"), literal("--font-heading-md-line-height"), literal("--font-heading-lg-line-height"), literal("--font-heading-xl-line-height"), literal("--font-heading-2xl-line-height"), literal("--font-heading-3xl-line-height"), literal("--border-radius-xs"), literal("--border-radius-sm"), literal("--border-radius-md"), literal("--border-radius-lg"), literal("--border-radius-xl"), literal("--border-radius-full"), literal("--border-width-regular"), literal("--shadow-hairline"), literal("--shadow-sm"), literal("--shadow-md"), literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."), RQ = record(HQ.describe(`Style variables for theming MCP apps.

Individual style keys are optional - hosts may provide any subset of these values.
Values are strings containing CSS values (colors, sizes, font stacks, etc.).

Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`), union([string(), _undefined()]).describe(`Style variables for theming MCP apps.

Individual style keys are optional - hosts may provide any subset of these values.
Values are strings containing CSS values (colors, sizes, font stacks, etc.).

Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps.

Individual style keys are optional - hosts may provide any subset of these values.
Values are strings containing CSS values (colors, sizes, font stacks, etc.).

Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`);
object({ method: literal("ui/open-link"), params: object({ url: string().describe("URL to open in the host's browser") }) });
object({ isError: boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).") }).passthrough();
object({ isError: boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).") }).passthrough();
object({ isError: boolean().optional().describe("True if the host rejected or failed to deliver the message.") }).passthrough();
object({ method: literal("ui/notifications/sandbox-proxy-ready"), params: object({}) });
var O$1 = object({ connectDomains: array(string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).

- Maps to CSP \`connect-src\` directive
- Empty or omitted → no network connections (secure default)`), resourceDomains: array(string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"), frameDomains: array(string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"), baseUriDomains: array(string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)") }), z = object({ camera: object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."), microphone: object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."), geolocation: object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."), clipboardWrite: object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.") });
object({ method: literal("ui/notifications/size-changed"), params: object({ width: number$1().optional().describe("New width in pixels."), height: number$1().optional().describe("New height in pixels.") }) });
object({ method: literal("ui/notifications/tool-input"), params: object({ arguments: record(string(), unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.") }) });
object({ method: literal("ui/notifications/tool-input-partial"), params: object({ arguments: record(string(), unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).") }) });
object({ method: literal("ui/notifications/tool-cancelled"), params: object({ reason: string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").') }) });
var o = object({ fonts: string().optional() }), s = object({ variables: RQ.optional().describe("CSS variables for theming the app."), css: o.optional().describe("CSS blocks that apps can inject.") });
object({ method: literal("ui/resource-teardown"), params: object({}) });
record(string(), unknown());
var F$1 = object({ text: object({}).optional().describe("Host supports text content blocks."), image: object({}).optional().describe("Host supports image content blocks."), audio: object({}).optional().describe("Host supports audio content blocks."), resource: object({}).optional().describe("Host supports resource content blocks."), resourceLink: object({}).optional().describe("Host supports resource link content blocks."), structuredContent: object({}).optional().describe("Host supports structured content.") });
object({ method: literal("ui/notifications/request-teardown"), params: object({}).optional() });
var t = object({ experimental: object({}).optional().describe("Experimental features (structure TBD)."), openLinks: object({}).optional().describe("Host supports opening external URLs."), downloadFile: object({}).optional().describe("Host supports file downloads via ui/download-file."), serverTools: object({ listChanged: boolean().optional().describe("Host supports tools/list_changed notifications.") }).optional().describe("Host can proxy tool calls to the MCP server."), serverResources: object({ listChanged: boolean().optional().describe("Host supports resources/list_changed notifications.") }).optional().describe("Host can proxy resource reads to the MCP server."), logging: object({}).optional().describe("Host accepts log messages."), sandbox: object({ permissions: z.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."), csp: O$1.optional().describe("CSP domains approved by the host.") }).optional().describe("Sandbox configuration applied by the host."), updateModelContext: F$1.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."), message: F$1.optional().describe("Host supports receiving content messages (ui/message) from the view."), sampling: object({ tools: object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.") }).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.") }), a = object({ experimental: object({}).optional().describe("Experimental features (structure TBD)."), tools: object({ listChanged: boolean().optional().describe("App supports tools/list_changed notifications.") }).optional().describe("App exposes MCP-style tools that the host can call."), availableDisplayModes: array(B$3).optional().describe("Display modes the app supports.") });
object({ method: literal("ui/notifications/initialized"), params: object({}).optional() });
object({ csp: O$1.optional().describe("Content Security Policy configuration for UI resources."), permissions: z.optional().describe("Sandbox permissions requested by the UI resource."), domain: string().optional().describe(`Dedicated origin for view sandbox.

Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.

**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include:
- Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`)
- URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`)

If omitted, host uses default sandbox origin (typically per-conversation).`), prefersBorder: boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border.

Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary.

- \`true\`: request visible border + background
- \`false\`: request no visible border + background
- omitted: host decides border`) });
object({ method: literal("ui/request-display-mode"), params: object({ mode: B$3.describe("The display mode being requested.") }) });
object({ mode: B$3.describe("The display mode that was actually set. May differ from requested if not supported.") }).passthrough();
var e = union([literal("model"), literal("app")]).describe("Tool visibility scope - who can access the tool.");
object({ resourceUri: string().optional(), visibility: array(e).optional().describe(`Who can access this tool. Default: ["model", "app"]
- "model": Tool visible to and callable by the agent
- "app": Tool callable by the app from this server only`), csp: never().optional(), permissions: never().optional() });
object({ mimeTypes: array(string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.') });
object({ method: literal("ui/download-file"), params: object({ contents: array(union([EmbeddedResourceSchema, ResourceLinkSchema])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.") }) });
object({ method: literal("ui/message"), params: object({ role: literal("user").describe('Message role, currently only "user" is supported.'), content: array(ContentBlockSchema).describe("Message content blocks (text, image, etc.).") }) });
object({ method: literal("ui/notifications/sandbox-resource-ready"), params: object({ html: string().describe("HTML content to load into the inner iframe."), sandbox: string().optional().describe("Optional override for the inner iframe's sandbox attribute."), csp: O$1.optional().describe("CSP configuration from resource metadata."), permissions: z.optional().describe("Sandbox permissions from resource metadata.") }) });
object({ method: literal("ui/notifications/tool-result"), params: CallToolResultSchema.describe("Standard MCP tool execution result.") });
var x = object({ toolInfo: object({ id: RequestIdSchema.optional().describe("JSON-RPC id of the tools/call request."), tool: ToolSchema.describe("Tool definition including name, inputSchema, etc.") }).optional().describe("Metadata of the tool call that instantiated this App."), theme: r.optional().describe("Current color theme preference."), styles: s.optional().describe("Style configuration for theming the app."), displayMode: B$3.optional().describe("How the UI is currently displayed."), availableDisplayModes: array(B$3).optional().describe("Display modes the host supports."), containerDimensions: union([object({ height: number$1().describe("Fixed container height in pixels.") }), object({ maxHeight: union([number$1(), _undefined()]).optional().describe("Maximum container height in pixels.") })]).and(union([object({ width: number$1().describe("Fixed container width in pixels.") }), object({ maxWidth: union([number$1(), _undefined()]).optional().describe("Maximum container width in pixels.") })])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`), locale: string().optional().describe("User's language and region preference in BCP 47 format."), timeZone: string().optional().describe("User's timezone in IANA format."), userAgent: string().optional().describe("Host application identifier."), platform: union([literal("web"), literal("desktop"), literal("mobile")]).optional().describe("Platform type for responsive design decisions."), deviceCapabilities: object({ touch: boolean().optional().describe("Whether the device supports touch input."), hover: boolean().optional().describe("Whether the device supports hover interactions.") }).optional().describe("Device input capabilities."), safeAreaInsets: object({ top: number$1().describe("Top safe area inset in pixels."), right: number$1().describe("Right safe area inset in pixels."), bottom: number$1().describe("Bottom safe area inset in pixels."), left: number$1().describe("Left safe area inset in pixels.") }).optional().describe("Mobile safe area boundaries in pixels.") }).passthrough();
object({ method: literal("ui/notifications/host-context-changed"), params: x.describe("Partial context update containing only changed fields.") });
object({ method: literal("ui/update-model-context"), params: object({ content: array(ContentBlockSchema).optional().describe("Context content blocks (text, image, etc.)."), structuredContent: record(string(), unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.") }) });
object({ method: literal("ui/initialize"), params: object({ appInfo: ImplementationSchema.describe("App identification (name and version)."), appCapabilities: a.describe("Features and capabilities this app provides."), protocolVersion: string().describe("Protocol version this app supports.") }) });
object({ protocolVersion: string().describe('Negotiated protocol version string (e.g., "2025-11-21").'), hostInfo: ImplementationSchema.describe("Host application identification and version."), hostCapabilities: t.describe("Features and capabilities provided by the host."), hostContext: x.describe("Rich context about the host environment.") }).passthrough();
var i = "ui/resourceUri";
function FZ(X2) {
  let Z2 = X2._meta?.ui?.resourceUri;
  if (Z2 === void 0) Z2 = X2._meta?.[i];
  if (typeof Z2 === "string" && Z2.startsWith("ui://")) return Z2;
  else if (Z2 !== void 0) throw Error(`Invalid UI resource URI: ${JSON.stringify(Z2)}`);
  return;
}
const EMPTY_DEBUGGER_STATE = {
  isInitiatingAuth: false,
  oauthTokens: null,
  oauthStep: "metadata_discovery",
  oauthMetadata: null,
  resourceMetadata: null,
  resourceMetadataError: null,
  resource: null,
  authServerUrl: null,
  oauthClientInfo: null,
  authorizationUrl: null,
  authorizationCode: "",
  latestError: null,
  statusMessage: null,
  validationError: null
};
let crypto$1;
crypto$1 = globalThis.crypto;
async function getRandomValues(size2) {
  return (await crypto$1).getRandomValues(new Uint8Array(size2));
}
async function random(size2) {
  const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
  const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
  let result = "";
  while (result.length < size2) {
    const randomBytes = await getRandomValues(size2 - result.length);
    for (const randomByte of randomBytes) {
      if (randomByte < evenDistCutoff) {
        result += mask[randomByte % mask.length];
      }
    }
  }
  return result;
}
async function generateVerifier(length) {
  return await random(length);
}
async function generateChallenge(code_verifier) {
  const buffer = await (await crypto$1).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
  return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
}
async function pkceChallenge(length) {
  if (!length)
    length = 43;
  if (length < 43 || length > 128) {
    throw `Expected a length between 43 and 128. Received ${length}.`;
  }
  const verifier = await generateVerifier(length);
  const challenge = await generateChallenge(verifier);
  return {
    code_verifier: verifier,
    code_challenge: challenge
  };
}
function resourceUrlFromServerUrl(url2) {
  const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href);
  resourceURL.hash = "";
  return resourceURL;
}
function checkResourceAllowed({ requestedResource, configuredResource }) {
  const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
  const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
  if (requested.origin !== configured.origin) {
    return false;
  }
  if (requested.pathname.length < configured.pathname.length) {
    return false;
  }
  const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
  const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
  return requestedPath.startsWith(configuredPath);
}
class OAuthError extends Error {
  constructor(message, errorUri) {
    super(message);
    this.errorUri = errorUri;
    this.name = this.constructor.name;
  }
  /**
   * Converts the error to a standard OAuth error response object
   */
  toResponseObject() {
    const response = {
      error: this.errorCode,
      error_description: this.message
    };
    if (this.errorUri) {
      response.error_uri = this.errorUri;
    }
    return response;
  }
  get errorCode() {
    return this.constructor.errorCode;
  }
}
class InvalidRequestError extends OAuthError {
}
InvalidRequestError.errorCode = "invalid_request";
class InvalidClientError extends OAuthError {
}
InvalidClientError.errorCode = "invalid_client";
class InvalidGrantError extends OAuthError {
}
InvalidGrantError.errorCode = "invalid_grant";
class UnauthorizedClientError extends OAuthError {
}
UnauthorizedClientError.errorCode = "unauthorized_client";
class UnsupportedGrantTypeError extends OAuthError {
}
UnsupportedGrantTypeError.errorCode = "unsupported_grant_type";
class InvalidScopeError extends OAuthError {
}
InvalidScopeError.errorCode = "invalid_scope";
class AccessDeniedError extends OAuthError {
}
AccessDeniedError.errorCode = "access_denied";
class ServerError extends OAuthError {
}
ServerError.errorCode = "server_error";
class TemporarilyUnavailableError extends OAuthError {
}
TemporarilyUnavailableError.errorCode = "temporarily_unavailable";
class UnsupportedResponseTypeError extends OAuthError {
}
UnsupportedResponseTypeError.errorCode = "unsupported_response_type";
class UnsupportedTokenTypeError extends OAuthError {
}
UnsupportedTokenTypeError.errorCode = "unsupported_token_type";
class InvalidTokenError extends OAuthError {
}
InvalidTokenError.errorCode = "invalid_token";
class MethodNotAllowedError extends OAuthError {
}
MethodNotAllowedError.errorCode = "method_not_allowed";
class TooManyRequestsError extends OAuthError {
}
TooManyRequestsError.errorCode = "too_many_requests";
class InvalidClientMetadataError extends OAuthError {
}
InvalidClientMetadataError.errorCode = "invalid_client_metadata";
class InsufficientScopeError extends OAuthError {
}
InsufficientScopeError.errorCode = "insufficient_scope";
class InvalidTargetError extends OAuthError {
}
InvalidTargetError.errorCode = "invalid_target";
const OAUTH_ERRORS = {
  [InvalidRequestError.errorCode]: InvalidRequestError,
  [InvalidClientError.errorCode]: InvalidClientError,
  [InvalidGrantError.errorCode]: InvalidGrantError,
  [UnauthorizedClientError.errorCode]: UnauthorizedClientError,
  [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,
  [InvalidScopeError.errorCode]: InvalidScopeError,
  [AccessDeniedError.errorCode]: AccessDeniedError,
  [ServerError.errorCode]: ServerError,
  [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,
  [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,
  [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,
  [InvalidTokenError.errorCode]: InvalidTokenError,
  [MethodNotAllowedError.errorCode]: MethodNotAllowedError,
  [TooManyRequestsError.errorCode]: TooManyRequestsError,
  [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
  [InsufficientScopeError.errorCode]: InsufficientScopeError,
  [InvalidTargetError.errorCode]: InvalidTargetError
};
class UnauthorizedError extends Error {
  constructor(message) {
    super(message ?? "Unauthorized");
  }
}
function isClientAuthMethod(method) {
  return ["client_secret_basic", "client_secret_post", "none"].includes(method);
}
const AUTHORIZATION_CODE_RESPONSE_TYPE = "code";
const AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256";
function selectClientAuthMethod(clientInformation, supportedMethods) {
  const hasClientSecret = clientInformation.client_secret !== void 0;
  if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) {
    return clientInformation.token_endpoint_auth_method;
  }
  if (supportedMethods.length === 0) {
    return hasClientSecret ? "client_secret_basic" : "none";
  }
  if (hasClientSecret && supportedMethods.includes("client_secret_basic")) {
    return "client_secret_basic";
  }
  if (hasClientSecret && supportedMethods.includes("client_secret_post")) {
    return "client_secret_post";
  }
  if (supportedMethods.includes("none")) {
    return "none";
  }
  return hasClientSecret ? "client_secret_post" : "none";
}
function applyClientAuthentication(method, clientInformation, headers, params) {
  const { client_id, client_secret } = clientInformation;
  switch (method) {
    case "client_secret_basic":
      applyBasicAuth(client_id, client_secret, headers);
      return;
    case "client_secret_post":
      applyPostAuth(client_id, client_secret, params);
      return;
    case "none":
      applyPublicAuth(client_id, params);
      return;
    default:
      throw new Error(`Unsupported client authentication method: ${method}`);
  }
}
function applyBasicAuth(clientId, clientSecret, headers) {
  if (!clientSecret) {
    throw new Error("client_secret_basic authentication requires a client_secret");
  }
  const credentials = btoa(`${clientId}:${clientSecret}`);
  headers.set("Authorization", `Basic ${credentials}`);
}
function applyPostAuth(clientId, clientSecret, params) {
  params.set("client_id", clientId);
  if (clientSecret) {
    params.set("client_secret", clientSecret);
  }
}
function applyPublicAuth(clientId, params) {
  params.set("client_id", clientId);
}
async function parseErrorResponse(input) {
  const statusCode = input instanceof Response ? input.status : void 0;
  const body = input instanceof Response ? await input.text() : input;
  try {
    const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
    const { error, error_description, error_uri } = result;
    const errorClass = OAUTH_ERRORS[error] || ServerError;
    return new errorClass(error_description || "", error_uri);
  } catch (error) {
    const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
    return new ServerError(errorMessage);
  }
}
async function auth(provider, options) {
  try {
    return await authInternal(provider, options);
  } catch (error) {
    if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {
      await provider.invalidateCredentials?.("all");
      return await authInternal(provider, options);
    } else if (error instanceof InvalidGrantError) {
      await provider.invalidateCredentials?.("tokens");
      return await authInternal(provider, options);
    }
    throw error;
  }
}
async function authInternal(provider, { serverUrl, authorizationCode, scope: scope2, resourceMetadataUrl, fetchFn }) {
  const cachedState = await provider.discoveryState?.();
  let resourceMetadata;
  let authorizationServerUrl;
  let metadata2;
  let effectiveResourceMetadataUrl = resourceMetadataUrl;
  if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) {
    effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);
  }
  if (cachedState?.authorizationServerUrl) {
    authorizationServerUrl = cachedState.authorizationServerUrl;
    resourceMetadata = cachedState.resourceMetadata;
    metadata2 = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn });
    if (!resourceMetadata) {
      try {
        resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);
      } catch {
      }
    }
    if (metadata2 !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) {
      await provider.saveDiscoveryState?.({
        authorizationServerUrl: String(authorizationServerUrl),
        resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
        resourceMetadata,
        authorizationServerMetadata: metadata2
      });
    }
  } else {
    const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn });
    authorizationServerUrl = serverInfo.authorizationServerUrl;
    metadata2 = serverInfo.authorizationServerMetadata;
    resourceMetadata = serverInfo.resourceMetadata;
    await provider.saveDiscoveryState?.({
      authorizationServerUrl: String(authorizationServerUrl),
      resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
      resourceMetadata,
      authorizationServerMetadata: metadata2
    });
  }
  const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
  const resolvedScope = scope2 || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
  let clientInformation = await Promise.resolve(provider.clientInformation());
  if (!clientInformation) {
    if (authorizationCode !== void 0) {
      throw new Error("Existing OAuth client information is required when exchanging an authorization code");
    }
    const supportsUrlBasedClientId = metadata2?.client_id_metadata_document_supported === true;
    const clientMetadataUrl = provider.clientMetadataUrl;
    if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {
      throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
    }
    const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
    if (shouldUseUrlBasedClientId) {
      clientInformation = {
        client_id: clientMetadataUrl
      };
      await provider.saveClientInformation?.(clientInformation);
    } else {
      if (!provider.saveClientInformation) {
        throw new Error("OAuth client information must be saveable for dynamic registration");
      }
      const fullInformation = await registerClient(authorizationServerUrl, {
        metadata: metadata2,
        clientMetadata: provider.clientMetadata,
        scope: resolvedScope,
        fetchFn
      });
      await provider.saveClientInformation(fullInformation);
      clientInformation = fullInformation;
    }
  }
  const nonInteractiveFlow = !provider.redirectUrl;
  if (authorizationCode !== void 0 || nonInteractiveFlow) {
    const tokens2 = await fetchToken(provider, authorizationServerUrl, {
      metadata: metadata2,
      resource,
      authorizationCode,
      fetchFn
    });
    await provider.saveTokens(tokens2);
    return "AUTHORIZED";
  }
  const tokens = await provider.tokens();
  if (tokens?.refresh_token) {
    try {
      const newTokens = await refreshAuthorization(authorizationServerUrl, {
        metadata: metadata2,
        clientInformation,
        refreshToken: tokens.refresh_token,
        resource,
        addClientAuthentication: provider.addClientAuthentication,
        fetchFn
      });
      await provider.saveTokens(newTokens);
      return "AUTHORIZED";
    } catch (error) {
      if (!(error instanceof OAuthError) || error instanceof ServerError) ;
      else {
        throw error;
      }
    }
  }
  const state = provider.state ? await provider.state() : void 0;
  const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
    metadata: metadata2,
    clientInformation,
    state,
    redirectUrl: provider.redirectUrl,
    scope: resolvedScope,
    resource
  });
  await provider.saveCodeVerifier(codeVerifier);
  await provider.redirectToAuthorization(authorizationUrl);
  return "REDIRECT";
}
function isHttpsUrl(value) {
  if (!value)
    return false;
  try {
    const url2 = new URL(value);
    return url2.protocol === "https:" && url2.pathname !== "/";
  } catch {
    return false;
  }
}
async function selectResourceURL(serverUrl, provider, resourceMetadata) {
  const defaultResource = resourceUrlFromServerUrl(serverUrl);
  if (provider.validateResourceURL) {
    return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);
  }
  if (!resourceMetadata) {
    return void 0;
  }
  if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {
    throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
  }
  return new URL(resourceMetadata.resource);
}
function extractWWWAuthenticateParams(res) {
  const authenticateHeader = res.headers.get("WWW-Authenticate");
  if (!authenticateHeader) {
    return {};
  }
  const [type2, scheme] = authenticateHeader.split(" ");
  if (type2.toLowerCase() !== "bearer" || !scheme) {
    return {};
  }
  const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0;
  let resourceMetadataUrl;
  if (resourceMetadataMatch) {
    try {
      resourceMetadataUrl = new URL(resourceMetadataMatch);
    } catch {
    }
  }
  const scope2 = extractFieldFromWwwAuth(res, "scope") || void 0;
  const error = extractFieldFromWwwAuth(res, "error") || void 0;
  return {
    resourceMetadataUrl,
    scope: scope2,
    error
  };
}
function extractFieldFromWwwAuth(response, fieldName) {
  const wwwAuthHeader = response.headers.get("WWW-Authenticate");
  if (!wwwAuthHeader) {
    return null;
  }
  const pattern2 = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`);
  const match = wwwAuthHeader.match(pattern2);
  if (match) {
    return match[1] || match[2];
  }
  return null;
}
async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
  const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
    protocolVersion: opts?.protocolVersion,
    metadataUrl: opts?.resourceMetadataUrl
  });
  if (!response || response.status === 404) {
    await response?.body?.cancel();
    throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
  }
  if (!response.ok) {
    await response.body?.cancel();
    throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
  }
  return OAuthProtectedResourceMetadataSchema.parse(await response.json());
}
async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
  try {
    return await fetchFn(url2, { headers });
  } catch (error) {
    if (error instanceof TypeError) {
      if (headers) {
        return fetchWithCorsRetry(url2, void 0, fetchFn);
      } else {
        return void 0;
      }
    }
    throw error;
  }
}
function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
  if (pathname.endsWith("/")) {
    pathname = pathname.slice(0, -1);
  }
  return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
}
async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
  const headers = {
    "MCP-Protocol-Version": protocolVersion
  };
  return await fetchWithCorsRetry(url2, headers, fetchFn);
}
function shouldAttemptFallback(response, pathname) {
  return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
}
async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
  const issuer = new URL(serverUrl);
  const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;
  let url2;
  if (opts?.metadataUrl) {
    url2 = new URL(opts.metadataUrl);
  } else {
    const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
    url2 = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
    url2.search = issuer.search;
  }
  let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn);
  if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {
    const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
    response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
  }
  return response;
}
function buildDiscoveryUrls(authorizationServerUrl) {
  const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
  const hasPath = url2.pathname !== "/";
  const urlsToTry = [];
  if (!hasPath) {
    urlsToTry.push({
      url: new URL("/.well-known/oauth-authorization-server", url2.origin),
      type: "oauth"
    });
    urlsToTry.push({
      url: new URL(`/.well-known/openid-configuration`, url2.origin),
      type: "oidc"
    });
    return urlsToTry;
  }
  let pathname = url2.pathname;
  if (pathname.endsWith("/")) {
    pathname = pathname.slice(0, -1);
  }
  urlsToTry.push({
    url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin),
    type: "oauth"
  });
  urlsToTry.push({
    url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin),
    type: "oidc"
  });
  urlsToTry.push({
    url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin),
    type: "oidc"
  });
  return urlsToTry;
}
async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
  const headers = {
    "MCP-Protocol-Version": protocolVersion,
    Accept: "application/json"
  };
  const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
  for (const { url: endpointUrl, type: type2 } of urlsToTry) {
    const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
    if (!response) {
      continue;
    }
    if (!response.ok) {
      await response.body?.cancel();
      if (response.status >= 400 && response.status < 500) {
        continue;
      }
      throw new Error(`HTTP ${response.status} trying to load ${type2 === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
    }
    if (type2 === "oauth") {
      return OAuthMetadataSchema.parse(await response.json());
    } else {
      return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
    }
  }
  return void 0;
}
async function discoverOAuthServerInfo(serverUrl, opts) {
  let resourceMetadata;
  let authorizationServerUrl;
  try {
    resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn);
    if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
      authorizationServerUrl = resourceMetadata.authorization_servers[0];
    }
  } catch {
  }
  if (!authorizationServerUrl) {
    authorizationServerUrl = String(new URL("/", serverUrl));
  }
  const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });
  return {
    authorizationServerUrl,
    authorizationServerMetadata,
    resourceMetadata
  };
}
async function startAuthorization(authorizationServerUrl, { metadata: metadata2, clientInformation, redirectUrl, scope: scope2, state, resource }) {
  let authorizationUrl;
  if (metadata2) {
    authorizationUrl = new URL(metadata2.authorization_endpoint);
    if (!metadata2.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {
      throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
    }
    if (metadata2.code_challenge_methods_supported && !metadata2.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {
      throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);
    }
  } else {
    authorizationUrl = new URL("/authorize", authorizationServerUrl);
  }
  const challenge = await pkceChallenge();
  const codeVerifier = challenge.code_verifier;
  const codeChallenge = challenge.code_challenge;
  authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE);
  authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
  authorizationUrl.searchParams.set("code_challenge", codeChallenge);
  authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD);
  authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
  if (state) {
    authorizationUrl.searchParams.set("state", state);
  }
  if (scope2) {
    authorizationUrl.searchParams.set("scope", scope2);
  }
  if (scope2?.includes("offline_access")) {
    authorizationUrl.searchParams.append("prompt", "consent");
  }
  if (resource) {
    authorizationUrl.searchParams.set("resource", resource.href);
  }
  return { authorizationUrl, codeVerifier };
}
function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
  return new URLSearchParams({
    grant_type: "authorization_code",
    code: authorizationCode,
    code_verifier: codeVerifier,
    redirect_uri: String(redirectUri)
  });
}
async function executeTokenRequest(authorizationServerUrl, { metadata: metadata2, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
  const tokenUrl = metadata2?.token_endpoint ? new URL(metadata2.token_endpoint) : new URL("/token", authorizationServerUrl);
  const headers = new Headers({
    "Content-Type": "application/x-www-form-urlencoded",
    Accept: "application/json"
  });
  if (resource) {
    tokenRequestParams.set("resource", resource.href);
  }
  if (addClientAuthentication) {
    await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata2);
  } else if (clientInformation) {
    const supportedMethods = metadata2?.token_endpoint_auth_methods_supported ?? [];
    const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
    applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
  }
  const response = await (fetchFn ?? fetch)(tokenUrl, {
    method: "POST",
    headers,
    body: tokenRequestParams
  });
  if (!response.ok) {
    throw await parseErrorResponse(response);
  }
  return OAuthTokensSchema.parse(await response.json());
}
async function exchangeAuthorization(authorizationServerUrl, { metadata: metadata2, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) {
  const tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri);
  return executeTokenRequest(authorizationServerUrl, {
    metadata: metadata2,
    tokenRequestParams,
    clientInformation,
    addClientAuthentication,
    resource,
    fetchFn
  });
}
async function refreshAuthorization(authorizationServerUrl, { metadata: metadata2, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
  const tokenRequestParams = new URLSearchParams({
    grant_type: "refresh_token",
    refresh_token: refreshToken
  });
  const tokens = await executeTokenRequest(authorizationServerUrl, {
    metadata: metadata2,
    tokenRequestParams,
    clientInformation,
    addClientAuthentication,
    resource,
    fetchFn
  });
  return { refresh_token: refreshToken, ...tokens };
}
async function fetchToken(provider, authorizationServerUrl, { metadata: metadata2, resource, authorizationCode, fetchFn } = {}) {
  const scope2 = provider.clientMetadata.scope;
  let tokenRequestParams;
  if (provider.prepareTokenRequest) {
    tokenRequestParams = await provider.prepareTokenRequest(scope2);
  }
  if (!tokenRequestParams) {
    if (!authorizationCode) {
      throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");
    }
    if (!provider.redirectUrl) {
      throw new Error("redirectUrl is required for authorization_code flow");
    }
    const codeVerifier = await provider.codeVerifier();
    tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
  }
  const clientInformation = await provider.clientInformation();
  return executeTokenRequest(authorizationServerUrl, {
    metadata: metadata2,
    tokenRequestParams,
    clientInformation: clientInformation ?? void 0,
    addClientAuthentication: provider.addClientAuthentication,
    resource,
    fetchFn
  });
}
async function registerClient(authorizationServerUrl, { metadata: metadata2, clientMetadata, scope: scope2, fetchFn }) {
  let registrationUrl;
  if (metadata2) {
    if (!metadata2.registration_endpoint) {
      throw new Error("Incompatible auth server: does not support dynamic client registration");
    }
    registrationUrl = new URL(metadata2.registration_endpoint);
  } else {
    registrationUrl = new URL("/register", authorizationServerUrl);
  }
  const response = await (fetchFn ?? fetch)(registrationUrl, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      ...clientMetadata,
      ...scope2 !== void 0 ? { scope: scope2 } : {}
    })
  });
  if (!response.ok) {
    throw await parseErrorResponse(response);
  }
  return OAuthClientInformationFullSchema.parse(await response.json());
}
const parseOAuthCallbackParams = (location) => {
  const params = new URLSearchParams(location);
  const code2 = params.get("code");
  if (code2) {
    return { successful: true, code: code2 };
  }
  const error = params.get("error");
  const error_description = params.get("error_description");
  const error_uri = params.get("error_uri");
  if (error) {
    return { successful: false, error, error_description, error_uri };
  }
  return {
    successful: false,
    error: "invalid_request",
    error_description: "Missing code or error in response",
    error_uri: null
  };
};
const generateOAuthState = () => {
  const array2 = new Uint8Array(32);
  crypto.getRandomValues(array2);
  return Array.from(array2, (byte) => byte.toString(16).padStart(2, "0")).join(
    ""
  );
};
const generateOAuthErrorDescription = (params) => {
  const error = params.error;
  const errorDescription = params.error_description;
  const errorUri = params.error_uri;
  return [
    `Error: ${error}.`,
    errorDescription ? `Details: ${errorDescription}.` : "",
    errorUri ? `More info: ${errorUri}.` : ""
  ].filter(Boolean).join("\n");
};
const getAuthorizationServerMetadataDiscoveryUrl = (authorizationServerUrl) => {
  const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
  const hasPath = url2.pathname !== "/";
  if (!hasPath) {
    return new URL("/.well-known/oauth-authorization-server", url2.origin).href;
  }
  const pathname = url2.pathname.endsWith("/") ? url2.pathname.slice(0, -1) : url2.pathname;
  return new URL(
    `/.well-known/oauth-authorization-server${pathname}`,
    url2.origin
  ).href;
};
function validateRedirectUrl(url2) {
  try {
    const parsedUrl = new URL(url2);
    if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
      throw new Error("Authorization URL must be HTTP or HTTPS");
    }
  } catch (error) {
    if (error instanceof Error && error.message === "Authorization URL must be HTTP or HTTPS") {
      throw error;
    }
    throw new Error(`Invalid URL: ${url2}`);
  }
}
const discoverScopes = async (serverUrl, resourceMetadata, fetchFn) => {
  try {
    const metadata2 = await discoverAuthorizationServerMetadata(
      new URL("/", serverUrl),
      { fetchFn }
    );
    const resourceScopes = resourceMetadata?.scopes_supported;
    const oauthScopes = metadata2?.scopes_supported;
    const scopesSupported = resourceScopes && resourceScopes.length > 0 ? resourceScopes : oauthScopes;
    return scopesSupported && scopesSupported.length > 0 ? scopesSupported.join(" ") : void 0;
  } catch (error) {
    console.debug("OAuth scope discovery failed:", error);
    return void 0;
  }
};
const getClientInformationFromSessionStorage = async ({
  serverUrl,
  isPreregistered
}) => {
  const key = getServerSpecificKey(
    isPreregistered ? SESSION_KEYS.PREREGISTERED_CLIENT_INFORMATION : SESSION_KEYS.CLIENT_INFORMATION,
    serverUrl
  );
  const value = sessionStorage.getItem(key);
  if (!value) {
    return void 0;
  }
  return await OAuthClientInformationSchema.parseAsync(JSON.parse(value));
};
const saveClientInformationToSessionStorage = ({
  serverUrl,
  clientInformation,
  isPreregistered
}) => {
  const key = getServerSpecificKey(
    isPreregistered ? SESSION_KEYS.PREREGISTERED_CLIENT_INFORMATION : SESSION_KEYS.CLIENT_INFORMATION,
    serverUrl
  );
  sessionStorage.setItem(key, JSON.stringify(clientInformation));
};
const clearClientInformationFromSessionStorage = ({
  serverUrl,
  isPreregistered
}) => {
  const key = getServerSpecificKey(
    isPreregistered ? SESSION_KEYS.PREREGISTERED_CLIENT_INFORMATION : SESSION_KEYS.CLIENT_INFORMATION,
    serverUrl
  );
  sessionStorage.removeItem(key);
};
const getScopeFromSessionStorage = (serverUrl) => {
  const key = getServerSpecificKey(SESSION_KEYS.SCOPE, serverUrl);
  const value = sessionStorage.getItem(key);
  return value || void 0;
};
const saveScopeToSessionStorage = (serverUrl, scope2) => {
  const key = getServerSpecificKey(SESSION_KEYS.SCOPE, serverUrl);
  if (scope2) {
    sessionStorage.setItem(key, scope2);
  } else {
    sessionStorage.removeItem(key);
  }
};
const clearScopeFromSessionStorage = (serverUrl) => {
  const key = getServerSpecificKey(SESSION_KEYS.SCOPE, serverUrl);
  sessionStorage.removeItem(key);
};
class InspectorOAuthClientProvider {
  constructor(serverUrl) {
    this.serverUrl = serverUrl;
    sessionStorage.setItem(SESSION_KEYS.SERVER_URL, serverUrl);
  }
  serverUrl;
  get scope() {
    return getScopeFromSessionStorage(this.serverUrl);
  }
  get redirectUrl() {
    return window.location.origin + "/oauth/callback";
  }
  get debugRedirectUrl() {
    return window.location.origin + "/oauth/callback/debug";
  }
  get redirect_uris() {
    const callbackUrl = window.location.origin + "/oauth/callback";
    const debugCallbackUrl = window.location.origin + "/oauth/callback/debug";
    return [callbackUrl, debugCallbackUrl];
  }
  get clientMetadata() {
    const metadata2 = {
      redirect_uris: this.redirect_uris,
      token_endpoint_auth_method: "none",
      grant_types: ["authorization_code", "refresh_token"],
      response_types: ["code"],
      client_name: "MCP Inspector",
      client_uri: "https://github.com/modelcontextprotocol/inspector"
    };
    if (this.scope) {
      metadata2.scope = this.scope;
    }
    return metadata2;
  }
  state() {
    return generateOAuthState();
  }
  async clientInformation() {
    const preregisteredClientInformation = await getClientInformationFromSessionStorage({
      serverUrl: this.serverUrl,
      isPreregistered: true
    });
    return preregisteredClientInformation ?? await getClientInformationFromSessionStorage({
      serverUrl: this.serverUrl,
      isPreregistered: false
    });
  }
  saveClientInformation(clientInformation) {
    saveClientInformationToSessionStorage({
      serverUrl: this.serverUrl,
      clientInformation,
      isPreregistered: false
    });
  }
  async tokens() {
    const key = getServerSpecificKey(SESSION_KEYS.TOKENS, this.serverUrl);
    const tokens = sessionStorage.getItem(key);
    if (!tokens) {
      return void 0;
    }
    return await OAuthTokensSchema.parseAsync(JSON.parse(tokens));
  }
  saveTokens(tokens) {
    const key = getServerSpecificKey(SESSION_KEYS.TOKENS, this.serverUrl);
    sessionStorage.setItem(key, JSON.stringify(tokens));
  }
  redirectToAuthorization(authorizationUrl) {
    validateRedirectUrl(authorizationUrl.href);
    window.location.href = authorizationUrl.href;
  }
  saveCodeVerifier(codeVerifier) {
    const key = getServerSpecificKey(
      SESSION_KEYS.CODE_VERIFIER,
      this.serverUrl
    );
    sessionStorage.setItem(key, codeVerifier);
  }
  codeVerifier() {
    const key = getServerSpecificKey(
      SESSION_KEYS.CODE_VERIFIER,
      this.serverUrl
    );
    const verifier = sessionStorage.getItem(key);
    if (!verifier) {
      throw new Error("No code verifier saved for session");
    }
    return verifier;
  }
  clear() {
    clearClientInformationFromSessionStorage({
      serverUrl: this.serverUrl,
      isPreregistered: false
    });
    sessionStorage.removeItem(
      getServerSpecificKey(SESSION_KEYS.TOKENS, this.serverUrl)
    );
    sessionStorage.removeItem(
      getServerSpecificKey(SESSION_KEYS.CODE_VERIFIER, this.serverUrl)
    );
  }
}
class DebugInspectorOAuthClientProvider extends InspectorOAuthClientProvider {
  get redirectUrl() {
    return this.debugRedirectUrl;
  }
  saveServerMetadata(metadata2) {
    const key = getServerSpecificKey(
      SESSION_KEYS.SERVER_METADATA,
      this.serverUrl
    );
    sessionStorage.setItem(key, JSON.stringify(metadata2));
  }
  getServerMetadata() {
    const key = getServerSpecificKey(
      SESSION_KEYS.SERVER_METADATA,
      this.serverUrl
    );
    const metadata2 = sessionStorage.getItem(key);
    if (!metadata2) {
      return null;
    }
    return JSON.parse(metadata2);
  }
  clear() {
    super.clear();
    sessionStorage.removeItem(
      getServerSpecificKey(SESSION_KEYS.SERVER_METADATA, this.serverUrl)
    );
  }
}
const oauthTransitions = {
  metadata_discovery: {
    canTransition: async () => true,
    execute: async (context) => {
      let authServerUrl = new URL("/", context.serverUrl);
      let resourceMetadata = null;
      let resourceMetadataError = null;
      try {
        resourceMetadata = await discoverOAuthProtectedResourceMetadata(
          context.serverUrl,
          {},
          context.fetchFn
        );
        if (resourceMetadata?.authorization_servers?.length) {
          authServerUrl = new URL(resourceMetadata.authorization_servers[0]);
        }
      } catch (e2) {
        if (e2 instanceof Error) {
          resourceMetadataError = e2;
        } else {
          resourceMetadataError = new Error(String(e2));
        }
      }
      const resource = await selectResourceURL(
        context.serverUrl,
        context.provider,
        // we default to null, so swap it for undefined if not set
        resourceMetadata ?? void 0
      );
      const metadata2 = await discoverAuthorizationServerMetadata(
        authServerUrl,
        { fetchFn: context.fetchFn }
      );
      if (!metadata2) {
        throw new Error("Failed to discover OAuth metadata");
      }
      const parsedMetadata = await OAuthMetadataSchema.parseAsync(metadata2);
      context.provider.saveServerMetadata(parsedMetadata);
      context.updateState({
        resourceMetadata,
        resource,
        resourceMetadataError,
        authServerUrl,
        oauthMetadata: parsedMetadata,
        oauthStep: "client_registration"
      });
    }
  },
  client_registration: {
    canTransition: async (context) => !!context.state.oauthMetadata,
    execute: async (context) => {
      const metadata2 = context.state.oauthMetadata;
      const clientMetadata = context.provider.clientMetadata;
      if (!context.provider.scope || context.provider.scope.trim() === "") {
        const scopesSupported = context.state.resourceMetadata?.scopes_supported || metadata2.scopes_supported;
        if (scopesSupported) {
          clientMetadata.scope = scopesSupported.join(" ");
        }
      }
      let fullInformation = await context.provider.clientInformation();
      if (!fullInformation) {
        fullInformation = await registerClient(context.serverUrl, {
          metadata: metadata2,
          clientMetadata,
          fetchFn: context.fetchFn
        });
        context.provider.saveClientInformation(fullInformation);
      }
      context.updateState({
        oauthClientInfo: fullInformation,
        oauthStep: "authorization_redirect"
      });
    }
  },
  authorization_redirect: {
    canTransition: async (context) => !!context.state.oauthMetadata && !!context.state.oauthClientInfo,
    execute: async (context) => {
      const metadata2 = context.state.oauthMetadata;
      const clientInformation = context.state.oauthClientInfo;
      let scope2 = context.provider.scope;
      if (!scope2 || scope2.trim() === "") {
        scope2 = await discoverScopes(
          context.serverUrl,
          context.state.resourceMetadata ?? void 0,
          context.fetchFn
        );
      }
      const { authorizationUrl, codeVerifier } = await startAuthorization(
        context.serverUrl,
        {
          metadata: metadata2,
          clientInformation,
          redirectUrl: context.provider.redirectUrl,
          scope: scope2,
          state: generateOAuthState(),
          resource: context.state.resource ?? void 0
        }
      );
      context.provider.saveCodeVerifier(codeVerifier);
      context.updateState({
        authorizationUrl,
        oauthStep: "authorization_code"
      });
    }
  },
  authorization_code: {
    canTransition: async () => true,
    execute: async (context) => {
      if (!context.state.authorizationCode || context.state.authorizationCode.trim() === "") {
        context.updateState({
          validationError: "You need to provide an authorization code"
        });
        throw new Error("Authorization code required");
      }
      context.updateState({
        validationError: null,
        oauthStep: "token_request"
      });
    }
  },
  token_request: {
    canTransition: async (context) => {
      return !!context.state.authorizationCode && !!context.provider.getServerMetadata() && !!await context.provider.clientInformation();
    },
    execute: async (context) => {
      const codeVerifier = context.provider.codeVerifier();
      const metadata2 = context.provider.getServerMetadata();
      const clientInformation = await context.provider.clientInformation();
      const tokens = await exchangeAuthorization(context.serverUrl, {
        metadata: metadata2,
        clientInformation,
        authorizationCode: context.state.authorizationCode,
        codeVerifier,
        redirectUri: context.provider.redirectUrl,
        resource: context.state.resource ? context.state.resource instanceof URL ? context.state.resource : new URL(context.state.resource) : void 0,
        fetchFn: context.fetchFn
      });
      context.provider.saveTokens(tokens);
      context.updateState({
        oauthTokens: tokens,
        oauthStep: "complete"
      });
    }
  },
  complete: {
    canTransition: async () => false,
    execute: async () => {
    }
  }
};
class OAuthStateMachine {
  constructor(serverUrl, updateState, fetchFn) {
    this.serverUrl = serverUrl;
    this.updateState = updateState;
    this.fetchFn = fetchFn;
  }
  serverUrl;
  updateState;
  fetchFn;
  async executeStep(state) {
    const provider = new DebugInspectorOAuthClientProvider(this.serverUrl);
    const context = {
      state,
      serverUrl: this.serverUrl,
      provider,
      updateState: this.updateState,
      fetchFn: this.fetchFn
    };
    const transition = oauthTransitions[state.oauthStep];
    if (!await transition.canTransition(context)) {
      throw new Error(`Cannot transition from ${state.oauthStep}`);
    }
    await transition.execute(context);
  }
}
const getSearchParam = (key) => {
  try {
    const url2 = new URL(window.location.href);
    return url2.searchParams.get(key);
  } catch {
    return null;
  }
};
const getMCPProxyAddress = (config2) => {
  let proxyFullAddress = config2.MCP_PROXY_FULL_ADDRESS.value;
  if (proxyFullAddress) {
    proxyFullAddress = proxyFullAddress.replace(/\/+$/, "");
    return proxyFullAddress;
  }
  const proxyPort = getSearchParam("MCP_PROXY_PORT") || DEFAULT_MCP_PROXY_LISTEN_PORT;
  return `${window.location.protocol}//${window.location.hostname}:${proxyPort}`;
};
const getMCPServerRequestTimeout = (config2) => {
  return config2.MCP_SERVER_REQUEST_TIMEOUT.value;
};
const resetRequestTimeoutOnProgress = (config2) => {
  return config2.MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS.value;
};
const getMCPServerRequestMaxTotalTimeout = (config2) => {
  return config2.MCP_REQUEST_MAX_TOTAL_TIMEOUT.value;
};
const getMCPProxyAuthToken = (config2) => {
  return {
    token: config2.MCP_PROXY_AUTH_TOKEN.value,
    header: "X-MCP-Proxy-Auth"
  };
};
const getMCPTaskTtl = (config2) => {
  return config2.MCP_TASK_TTL.value;
};
const getInitialTransportType = () => {
  const param = getSearchParam("transport");
  if (param === "stdio" || param === "sse" || param === "streamable-http") {
    return param;
  }
  return localStorage.getItem("lastTransportType") || "stdio";
};
const getInitialSseUrl = () => {
  const param = getSearchParam("serverUrl");
  if (param) return param;
  return localStorage.getItem("lastSseUrl") || "http://localhost:3001/sse";
};
const getInitialCommand = () => {
  const param = getSearchParam("serverCommand");
  if (param) return param;
  return localStorage.getItem("lastCommand") || "mcp-server-everything";
};
const getInitialArgs = () => {
  const param = getSearchParam("serverArgs");
  if (param) return param;
  return localStorage.getItem("lastArgs") || "";
};
const getConfigOverridesFromQueryParams = (defaultConfig) => {
  const url2 = new URL(window.location.href);
  const overrides = {};
  for (const key of Object.keys(defaultConfig)) {
    const param = url2.searchParams.get(key);
    if (param !== null) {
      const defaultValue = defaultConfig[key].value;
      let value = param;
      if (typeof defaultValue === "number") {
        value = Number(param);
      } else if (typeof defaultValue === "boolean") {
        value = param === "true";
      }
      overrides[key] = {
        ...defaultConfig[key],
        value
      };
    }
  }
  return overrides;
};
const initializeInspectorConfig = (localStorageKey) => {
  const savedPersistentConfig = localStorage.getItem(localStorageKey);
  const savedEphemeralConfig = sessionStorage.getItem(
    `${localStorageKey}_ephemeral`
  );
  let baseConfig = { ...DEFAULT_INSPECTOR_CONFIG };
  if (savedPersistentConfig) {
    const parsedPersistentConfig = JSON.parse(savedPersistentConfig);
    baseConfig = { ...baseConfig, ...parsedPersistentConfig };
  }
  if (savedEphemeralConfig) {
    const parsedEphemeralConfig = JSON.parse(savedEphemeralConfig);
    baseConfig = { ...baseConfig, ...parsedEphemeralConfig };
  }
  for (const [key, value] of Object.entries(baseConfig)) {
    baseConfig[key] = {
      ...value,
      label: DEFAULT_INSPECTOR_CONFIG[key].label,
      description: DEFAULT_INSPECTOR_CONFIG[key].description,
      is_session_item: DEFAULT_INSPECTOR_CONFIG[key].is_session_item
    };
  }
  const overrides = getConfigOverridesFromQueryParams(DEFAULT_INSPECTOR_CONFIG);
  return { ...baseConfig, ...overrides };
};
const saveInspectorConfig = (localStorageKey, config2) => {
  const persistentConfig = {};
  const ephemeralConfig = {};
  for (const [key, value] of Object.entries(config2)) {
    if (value.is_session_item) {
      ephemeralConfig[key] = value;
    } else {
      persistentConfig[key] = value;
    }
  }
  localStorage.setItem(localStorageKey, JSON.stringify(persistentConfig));
  sessionStorage.setItem(
    `${localStorageKey}_ephemeral`,
    JSON.stringify(ephemeralConfig)
  );
};
function isJsonObject(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function messageFromProxyInfrastructureError(data2) {
  if (!isJsonObject(data2)) {
    return null;
  }
  const rec = data2;
  if (!("error" in rec) || "status" in rec) {
    return null;
  }
  if (typeof rec.message === "string") {
    return rec.message;
  }
  if (typeof rec.error === "string") {
    return rec.error;
  }
  return "Proxy fetch failed";
}
function parseMirroredUpstreamJson(data2) {
  if (!isJsonObject(data2)) {
    return null;
  }
  const rec = data2;
  if (typeof rec.status !== "number") {
    return null;
  }
  if (typeof rec.body !== "string") {
    return null;
  }
  if (typeof rec.statusText !== "string") {
    return null;
  }
  if (typeof rec.ok !== "boolean") {
    return null;
  }
  if (rec.headers === null || typeof rec.headers !== "object") {
    return null;
  }
  if (Array.isArray(rec.headers)) {
    return null;
  }
  const headers = {};
  for (const [key, val] of Object.entries(rec.headers)) {
    if (typeof val !== "string") {
      return null;
    }
    headers[key] = val;
  }
  return {
    ok: rec.ok,
    status: rec.status,
    statusText: rec.statusText,
    headers,
    body: rec.body
  };
}
function createProxyFetch(config2) {
  const proxyAddress = getMCPProxyAddress(config2);
  const { token, header } = getMCPProxyAuthToken(config2);
  return async (input, init) => {
    const url2 = typeof input === "string" ? input : input instanceof Request ? input.url : input.toString();
    let serializedBody;
    if (init?.body != null) {
      if (typeof init.body === "string") {
        serializedBody = init.body;
      } else if (init.body instanceof URLSearchParams) {
        serializedBody = init.body.toString();
      } else {
        serializedBody = String(init.body);
      }
    }
    const proxyResponse = await fetch(`${proxyAddress}/fetch`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        [header]: `Bearer ${token}`
      },
      body: JSON.stringify({
        url: url2,
        init: {
          method: init?.method,
          headers: init?.headers ? Object.fromEntries(new Headers(init.headers)) : void 0,
          body: serializedBody
        }
      })
    });
    let data2;
    try {
      data2 = await proxyResponse.json();
    } catch {
      throw new Error(
        `Proxy fetch failed: ${proxyResponse.status} ${proxyResponse.statusText}`
      );
    }
    const infraMessage = messageFromProxyInfrastructureError(data2);
    if (infraMessage !== null) {
      throw new Error(infraMessage);
    }
    const mirrored = parseMirroredUpstreamJson(data2);
    if (mirrored === null) {
      throw new Error("Proxy fetch failed: unexpected response shape");
    }
    return new Response(mirrored.body, {
      status: mirrored.status,
      statusText: mirrored.statusText,
      headers: new Headers(mirrored.headers)
    });
  };
}
var uri_all$1 = { exports: {} };
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(module, exports) {
    (function(global2, factory) {
      factory(exports);
    })(uri_all, (function(exports2) {
      function merge2() {
        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 xl2 = sets.length - 1;
          for (var x2 = 1; x2 < xl2; ++x2) {
            sets[x2] = sets[x2].slice(1, -1);
          }
          sets[xl2] = sets[xl2].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 key in source) {
            obj[key] = source[key];
          }
        }
        return obj;
      }
      function buildExps(isIRI) {
        var ALPHA$$ = "[A-Za-z]", DIGIT$$ = "[0-9]", HEXDIG$$2 = merge2(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$$ = merge2(GEN_DELIMS$$, SUB_DELIMS$$), UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", UNRESERVED$$2 = merge2(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$);
        subexp(ALPHA$$ + merge2(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*");
        subexp(subexp(PCT_ENCODED$2 + "|" + merge2(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 + "+\\." + merge2(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]") + "+");
        subexp(subexp(PCT_ENCODED$2 + "|" + merge2(UNRESERVED$$2, SUB_DELIMS$$)) + "*");
        var PCHAR$ = subexp(PCT_ENCODED$2 + "|" + merge2(UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@]"));
        subexp(subexp(PCT_ENCODED$2 + "|" + merge2(UNRESERVED$$2, SUB_DELIMS$$, "[\\@]")) + "+");
        subexp(subexp(PCHAR$ + "|" + merge2("[\\/\\?]", IPRIVATE$$)) + "*");
        return {
          NOT_SCHEME: new RegExp(merge2("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
          NOT_USERINFO: new RegExp(merge2("[^\\%\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          NOT_HOST: new RegExp(merge2("[^\\%\\[\\]\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          NOT_PATH: new RegExp(merge2("[^\\%\\/\\:\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          NOT_PATH_NOSCHEME: new RegExp(merge2("[^\\%\\/\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          NOT_QUERY: new RegExp(merge2("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
          NOT_FRAGMENT: new RegExp(merge2("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
          ESCAPE: new RegExp(merge2("[^]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          UNRESERVED: new RegExp(UNRESERVED$$2, "g"),
          OTHER_CHARS: new RegExp(merge2("[^\\%]", 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 _n2 = true;
          var _d2 = false;
          var _e2 = void 0;
          try {
            for (var _i2 = arr[Symbol.iterator](), _s2; !(_n2 = (_s2 = _i2.next()).done); _n2 = true) {
              _arr.push(_s2.value);
              if (i2 && _arr.length === i2) break;
            }
          } catch (err) {
            _d2 = true;
            _e2 = err;
          } finally {
            try {
              if (!_n2 && _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 base = 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 errors2 = {
        "overflow": "Overflow: input needs wider integers to process",
        "not-basic": "Illegal input >= 0x80 (not a basic code point)",
        "invalid-input": "Invalid input"
      };
      var baseMinusTMin = base - tMin;
      var floor2 = Math.floor;
      var stringFromCharCode = String.fromCharCode;
      function error$1(type2) {
        throw new RangeError(errors2[type2]);
      }
      function map(array2, fn2) {
        var result = [];
        var length = array2.length;
        while (length--) {
          result[length] = fn2(array2[length]);
        }
        return result;
      }
      function mapDomain(string2, fn2) {
        var parts = string2.split("@");
        var result = "";
        if (parts.length > 1) {
          result = parts[0] + "@";
          string2 = parts[1];
        }
        string2 = string2.replace(regexSeparators, ".");
        var labels = string2.split(".");
        var encoded = map(labels, fn2).join(".");
        return result + encoded;
      }
      function ucs2decode(string2) {
        var output = [];
        var counter = 0;
        var length = string2.length;
        while (counter < length) {
          var value = string2.charCodeAt(counter++);
          if (value >= 55296 && value <= 56319 && counter < length) {
            var extra = string2.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(array2) {
        return String.fromCodePoint.apply(String, toConsumableArray(array2));
      };
      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 base;
      };
      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 += base
        ) {
          delta = floor2(delta / baseMinusTMin);
        }
        return floor2(k2 + (baseMinusTMin + 1) * delta / (delta + skew));
      };
      var decode = function decode2(input) {
        var output = [];
        var inputLength = input.length;
        var i2 = 0;
        var n = 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 w2 = 1, k2 = base;
            ;
            /* no condition */
            k2 += base
          ) {
            if (index2 >= inputLength) {
              error$1("invalid-input");
            }
            var digit = basicToDigit(input.charCodeAt(index2++));
            if (digit >= base || digit > floor2((maxInt - i2) / w2)) {
              error$1("overflow");
            }
            i2 += digit * w2;
            var t2 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias;
            if (digit < t2) {
              break;
            }
            var baseMinusT = base - t2;
            if (w2 > floor2(maxInt / baseMinusT)) {
              error$1("overflow");
            }
            w2 *= baseMinusT;
          }
          var out = output.length + 1;
          bias = adapt(i2 - oldi, out, oldi == 0);
          if (floor2(i2 / out) > maxInt - n) {
            error$1("overflow");
          }
          n += floor2(i2 / out);
          i2 %= out;
          output.splice(i2++, 0, n);
        }
        return String.fromCodePoint.apply(String, output);
      };
      var encode = function encode2(input) {
        var output = [];
        input = ucs2decode(input);
        var inputLength = input.length;
        var n = 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 m2 = 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 >= n && currentValue < m2) {
                m2 = 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 (m2 - n > floor2((maxInt - delta) / handledCPCountPlusOne)) {
            error$1("overflow");
          }
          delta += (m2 - n) * handledCPCountPlusOne;
          n = m2;
          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 < n && ++delta > maxInt) {
                error$1("overflow");
              }
              if (_currentValue == n) {
                var q2 = delta;
                for (
                  var k2 = base;
                  ;
                  /* no condition */
                  k2 += base
                ) {
                  var t2 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias;
                  if (q2 < t2) {
                    break;
                  }
                  var qMinusT = q2 - t2;
                  var baseMinusT = base - t2;
                  output.push(stringFromCharCode(digitToBasic(t2 + qMinusT % baseMinusT, 0)));
                  q2 = floor2(qMinusT / baseMinusT);
                }
                output.push(stringFromCharCode(digitToBasic(q2, 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;
          ++n;
        }
        return output.join("");
      };
      var toUnicode = function toUnicode2(input) {
        return mapDomain(input, function(string2) {
          return regexPunycode.test(string2) ? decode(string2.slice(4).toLowerCase()) : string2;
        });
      };
      var toASCII = function toASCII2(input) {
        return mapDomain(input, function(string2) {
          return regexNonASCII.test(string2) ? "xn--" + encode(string2) : string2;
        });
      };
      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": decode,
        "encode": encode,
        "toASCII": toASCII,
        "toUnicode": toUnicode
      };
      var SCHEMES = {};
      function pctEncChar(chr) {
        var c = chr.charCodeAt(0);
        var e2 = void 0;
        if (c < 16) e2 = "%0" + c.toString(16).toUpperCase();
        else if (c < 128) e2 = "%" + c.toString(16).toUpperCase();
        else if (c < 2048) e2 = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
        else e2 = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
        return e2;
      }
      function pctDecChars(str) {
        var newStr = "";
        var i2 = 0;
        var il2 = str.length;
        while (i2 < il2) {
          var c = parseInt(str.substr(i2 + 1, 2), 16);
          if (c < 128) {
            newStr += String.fromCharCode(c);
            i2 += 3;
          } else if (c >= 194 && c < 224) {
            if (il2 - i2 >= 6) {
              var c2 = parseInt(str.substr(i2 + 4, 2), 16);
              newStr += String.fromCharCode((c & 31) << 6 | c2 & 63);
            } else {
              newStr += str.substr(i2, 6);
            }
            i2 += 6;
          } else if (c >= 224) {
            if (il2 - i2 >= 9) {
              var _c = parseInt(str.substr(i2 + 4, 2), 16);
              var c3 = parseInt(str.substr(i2 + 7, 2), 16);
              newStr += String.fromCharCode((c & 15) << 12 | (_c & 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 parse2(uriString) {
        var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        var components = {};
        var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
        if (options.reference === "suffix") uriString = (options.scheme ? options.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 (options.reference && options.reference !== "suffix" && options.reference !== components.reference) {
            components.error = components.error || "URI is not a " + options.reference + " reference.";
          }
          var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
          if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
            if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) {
              try {
                components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
              } catch (e2) {
                components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e2;
              }
            }
            _normalizeComponentEncoding(components, URI_PROTOCOL);
          } else {
            _normalizeComponentEncoding(components, protocol);
          }
          if (schemeHandler && schemeHandler.parse) {
            schemeHandler.parse(components, options);
          }
        } else {
          components.error = components.error || "URI can not be parsed.";
        }
        return components;
      }
      function _recomposeAuthority(components, options) {
        var protocol = options.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 im2 = input.match(RDS5);
            if (im2) {
              var s2 = im2[0];
              input = input.slice(s2.length);
              output.push(s2);
            } else {
              throw new Error("Unexpected dot segment condition");
            }
          }
        }
        return output.join("");
      }
      function serialize(components) {
        var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL;
        var uriTokens = [];
        var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
        if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);
        if (components.host) {
          if (protocol.IPV6ADDRESS.test(components.host)) ;
          else if (options.domainHost || schemeHandler && schemeHandler.domainHost) {
            try {
              components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
            } catch (e2) {
              components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e2;
            }
          }
        }
        _normalizeComponentEncoding(components, protocol);
        if (options.reference !== "suffix" && components.scheme) {
          uriTokens.push(components.scheme);
          uriTokens.push(":");
        }
        var authority = _recomposeAuthority(components, options);
        if (authority !== void 0) {
          if (options.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 (!options.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(base2, relative) {
        var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
        var skipNormalization = arguments[3];
        var target = {};
        if (!skipNormalization) {
          base2 = parse2(serialize(base2, options), options);
          relative = parse2(serialize(relative, options), options);
        }
        options = options || {};
        if (!options.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 = base2.path;
              if (relative.query !== void 0) {
                target.query = relative.query;
              } else {
                target.query = base2.query;
              }
            } else {
              if (relative.path.charAt(0) === "/") {
                target.path = removeDotSegments(relative.path);
              } else {
                if ((base2.userinfo !== void 0 || base2.host !== void 0 || base2.port !== void 0) && !base2.path) {
                  target.path = "/" + relative.path;
                } else if (!base2.path) {
                  target.path = relative.path;
                } else {
                  target.path = base2.path.slice(0, base2.path.lastIndexOf("/") + 1) + relative.path;
                }
                target.path = removeDotSegments(target.path);
              }
              target.query = relative.query;
            }
            target.userinfo = base2.userinfo;
            target.host = base2.host;
            target.port = base2.port;
          }
          target.scheme = base2.scheme;
        }
        target.fragment = relative.fragment;
        return target;
      }
      function resolve2(baseURI, relativeURI, options) {
        var schemelessOptions = assign({ scheme: "null" }, options);
        return serialize(resolveComponents(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
      }
      function normalize(uri2, options) {
        if (typeof uri2 === "string") {
          uri2 = serialize(parse2(uri2, options), options);
        } else if (typeOf(uri2) === "object") {
          uri2 = parse2(serialize(uri2, options), options);
        }
        return uri2;
      }
      function equal2(uriA, uriB, options) {
        if (typeof uriA === "string") {
          uriA = serialize(parse2(uriA, options), options);
        } else if (typeOf(uriA) === "object") {
          uriA = serialize(uriA, options);
        }
        if (typeof uriB === "string") {
          uriB = serialize(parse2(uriB, options), options);
        } else if (typeOf(uriB) === "object") {
          uriB = serialize(uriB, options);
        }
        return uriA === uriB;
      }
      function escapeComponent(str, options) {
        return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
      }
      function unescapeComponent(str, options) {
        return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
      }
      var handler = {
        scheme: "http",
        domainHost: true,
        parse: function parse3(components, options) {
          if (!components.host) {
            components.error = components.error || "HTTP URIs must have a host.";
          }
          return components;
        },
        serialize: function serialize2(components, options) {
          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 parse3(components, options) {
          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 serialize2(wsComponents, options) {
          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$$ = merge2(QTEXT$$, '[\\"\\\\]');
      var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
      var UNRESERVED = new RegExp(UNRESERVED$$, "g");
      var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
      var NOT_LOCAL_PART = new RegExp(merge2("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
      var NOT_HFNAME = new RegExp(merge2("[^]", 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, options) {
          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, xl2 = hfields.length; x2 < xl2; ++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], options);
                  break;
                case "body":
                  mailtoComponents.body = unescapeComponent(hfield[1], options);
                  break;
                default:
                  unknownHeaders = true;
                  headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);
                  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 (!options.unicodeSupport) {
              try {
                addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());
              } catch (e2) {
                mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e2;
              }
            } else {
              addr[1] = unescapeComponent(addr[1], options).toLowerCase();
            }
            to2[_x2] = addr.join("@");
          }
          return mailtoComponents;
        },
        serialize: function serialize$$1(mailtoComponents, options) {
          var components = mailtoComponents;
          var to2 = toArray(mailtoComponents.to);
          if (to2) {
            for (var x2 = 0, xl2 = to2.length; x2 < xl2; ++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 = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain);
              } catch (e2) {
                components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e2;
              }
              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 name2 in headers) {
            if (headers[name2] !== O2[name2]) {
              fields.push(name2.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name2].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, options) {
          var matches = components.path && components.path.match(URN_PARSE);
          var urnComponents = components;
          if (matches) {
            var scheme = options.scheme || urnComponents.scheme || "urn";
            var nid = matches[1].toLowerCase();
            var nss = matches[2];
            var urnScheme = scheme + ":" + (options.nid || nid);
            var schemeHandler = SCHEMES[urnScheme];
            urnComponents.nid = nid;
            urnComponents.nss = nss;
            urnComponents.path = void 0;
            if (schemeHandler) {
              urnComponents = schemeHandler.parse(urnComponents, options);
            }
          } else {
            urnComponents.error = urnComponents.error || "URN can not be parsed.";
          }
          return urnComponents;
        },
        serialize: function serialize$$1(urnComponents, options) {
          var scheme = options.scheme || urnComponents.scheme || "urn";
          var nid = urnComponents.nid;
          var urnScheme = scheme + ":" + (options.nid || nid);
          var schemeHandler = SCHEMES[urnScheme];
          if (schemeHandler) {
            urnComponents = schemeHandler.serialize(urnComponents, options);
          }
          var uriComponents = urnComponents;
          var nss = urnComponents.nss;
          uriComponents.path = (nid || options.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 parse3(urnComponents, options) {
          var uuidComponents = urnComponents;
          uuidComponents.uuid = uuidComponents.nss;
          uuidComponents.nss = void 0;
          if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {
            uuidComponents.error = uuidComponents.error || "UUID is not valid.";
          }
          return uuidComponents;
        },
        serialize: function serialize2(uuidComponents, options) {
          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 = parse2;
      exports2.removeDotSegments = removeDotSegments;
      exports2.serialize = serialize;
      exports2.resolveComponents = resolveComponents;
      exports2.resolve = resolve2;
      exports2.normalize = normalize;
      exports2.equal = equal2;
      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 equal2(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 (!equal2(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 key = keys[i2];
        if (!equal2(a2[key], b2[key])) return false;
      }
      return true;
    }
    return a2 !== a2 && b2 !== b2;
  };
  return fastDeepEqual;
}
var ucs2length$2;
var hasRequiredUcs2length$2;
function requireUcs2length$2() {
  if (hasRequiredUcs2length$2) return ucs2length$2;
  hasRequiredUcs2length$2 = 1;
  ucs2length$2 = 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$2;
}
var util$2;
var hasRequiredUtil$2;
function requireUtil$2() {
  if (hasRequiredUtil$2) return util$2;
  hasRequiredUtil$2 = 1;
  util$2 = {
    copy,
    checkDataType,
    checkDataTypes,
    coerceToTypes,
    toHash,
    getProperty,
    escapeQuotes,
    equal: requireFastDeepEqual(),
    ucs2length: requireUcs2length$2(),
    varOccurences,
    varReplace,
    schemaHasRules,
    schemaHasRulesExcept,
    schemaUnknownRules,
    toQuotedString,
    getPathExpr,
    getPath,
    getData,
    unescapeFragment,
    unescapeJsonPointer,
    escapeFragment,
    escapeJsonPointer
  };
  function copy(o2, to2) {
    to2 = to2 || {};
    for (var key in o2) to2[key] = o2[key];
    return to2;
  }
  function checkDataType(dataType2, data2, strictNumbers, negate) {
    var EQUAL = negate ? " !== " : " === ", AND = negate ? " || " : " && ", OK2 = negate ? "!" : "", NOT = negate ? "" : "!";
    switch (dataType2) {
      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 + '"' + dataType2 + '"' + (strictNumbers ? AND + OK2 + "isFinite(" + data2 + ")" : "") + ")";
      default:
        return "typeof " + data2 + EQUAL + '"' + dataType2 + '"';
    }
  }
  function checkDataTypes(dataTypes, data2, strictNumbers) {
    switch (dataTypes.length) {
      case 1:
        return checkDataType(dataTypes[0], data2, strictNumbers, true);
      default:
        var code2 = "";
        var types2 = toHash(dataTypes);
        if (types2.array && types2.object) {
          code2 = types2.null ? "(" : "(!" + data2 + " || ";
          code2 += "typeof " + data2 + ' !== "object")';
          delete types2.null;
          delete types2.array;
          delete types2.object;
        }
        if (types2.number) delete types2.integer;
        for (var t2 in types2)
          code2 += (code2 ? " && " : "") + checkDataType(t2, data2, strictNumbers, true);
        return code2;
    }
  }
  var COERCE_TO_TYPES = toHash(["string", "number", "integer", "boolean", "null"]);
  function coerceToTypes(optionCoerceTypes, dataTypes) {
    if (Array.isArray(dataTypes)) {
      var types2 = [];
      for (var i2 = 0; i2 < dataTypes.length; i2++) {
        var t2 = dataTypes[i2];
        if (COERCE_TO_TYPES[t2]) types2[types2.length] = t2;
        else if (optionCoerceTypes === "array" && t2 === "array") types2[types2.length] = t2;
      }
      if (types2.length) return types2;
    } else if (COERCE_TO_TYPES[dataTypes]) {
      return [dataTypes];
    } else if (optionCoerceTypes === "array" && dataTypes === "array") {
      return ["array"];
    }
  }
  function toHash(arr) {
    var hash = {};
    for (var i2 = 0; i2 < arr.length; i2++) hash[arr[i2]] = true;
    return hash;
  }
  var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
  var SINGLE_QUOTE = /'|\\/g;
  function getProperty(key) {
    return typeof key == "number" ? "[" + key + "]" : IDENTIFIER.test(key) ? "." + key : "['" + escapeQuotes(key) + "']";
  }
  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 key in schema) if (rules2[key]) return true;
  }
  function schemaHasRulesExcept(schema, rules2, exceptKeyword) {
    if (typeof schema == "boolean") return !schema && exceptKeyword != "not";
    for (var key in schema) if (key != exceptKeyword && rules2[key]) return true;
  }
  function schemaUnknownRules(schema, rules2) {
    if (typeof schema == "boolean") return;
    for (var key in schema) if (!rules2[key]) return key;
  }
  function toQuotedString(str) {
    return "'" + escapeQuotes(str) + "'";
  }
  function getPathExpr(currentPath, expr, jsonPointers, isNumber2) {
    var path = jsonPointers ? "'/' + " + expr + (isNumber2 ? "" : ".replace(/~/g, '~0').replace(/\\//g, '~1')") : isNumber2 ? "'[' + " + expr + " + ']'" : "'[\\'' + " + expr + " + '\\']'";
    return joinPaths(currentPath, path);
  }
  function getPath(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 up2, 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);
      up2 = +matches[1];
      jsonPointer = matches[2];
      if (jsonPointer == "#") {
        if (up2 >= lvl) throw new Error("Cannot access property/index " + up2 + " levels up, current level is " + lvl);
        return paths[lvl - up2];
      }
      if (up2 > lvl) throw new Error("Cannot access data " + up2 + " levels up, current level is " + lvl);
      data2 = "data" + (lvl - up2 || "");
      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$2();
  schema_obj = SchemaObject;
  function SchemaObject(obj) {
    util2.copy(obj, this);
  }
  return schema_obj;
}
var jsonSchemaTraverse$2 = { exports: {} };
var hasRequiredJsonSchemaTraverse$2;
function requireJsonSchemaTraverse$2() {
  if (hasRequiredJsonSchemaTraverse$2) return jsonSchemaTraverse$2.exports;
  hasRequiredJsonSchemaTraverse$2 = 1;
  var traverse = jsonSchemaTraverse$2.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 key in schema) {
        var sch = schema[key];
        if (Array.isArray(sch)) {
          if (key in traverse.arrayKeywords) {
            for (var i2 = 0; i2 < sch.length; i2++)
              _traverse(opts, pre, post, sch[i2], jsonPtr + "/" + key + "/" + i2, rootSchema, jsonPtr, key, schema, i2);
          }
        } else if (key in traverse.propsKeywords) {
          if (sch && typeof sch == "object") {
            for (var prop in sch)
              _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
          }
        } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
          _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
        }
      }
      post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    }
  }
  function escapeJsonPtr(str) {
    return str.replace(/~/g, "~0").replace(/\//g, "~1");
  }
  return jsonSchemaTraverse$2.exports;
}
var resolve_1;
var hasRequiredResolve$2;
function requireResolve$2() {
  if (hasRequiredResolve$2) return resolve_1;
  hasRequiredResolve$2 = 1;
  var URI = requireUri_all(), equal2 = requireFastDeepEqual(), util2 = requireUtil$2(), SchemaObject = requireSchema_obj(), traverse = requireJsonSchemaTraverse$2();
  resolve_1 = resolve2;
  resolve2.normalizeId = normalizeId;
  resolve2.fullPath = getFullPath;
  resolve2.url = resolveUrl;
  resolve2.ids = resolveIds;
  resolve2.inlineRef = inlineRef;
  resolve2.schema = resolveSchema;
  function resolve2(compile2, root, ref2) {
    var refVal = this._refs[ref2];
    if (typeof refVal == "string") {
      if (this._refs[refVal]) refVal = this._refs[refVal];
      else return resolve2.call(this, compile2, 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 || compile2.call(this, schema.schema, root, void 0, baseId);
    } else if (schema !== void 0) {
      v2 = inlineRef(schema, this._opts.inlineRefs) ? schema : compile2.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 id2 = normalizeId(refPath);
      var refVal = this._refs[id2];
      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[id2];
        if (refVal instanceof SchemaObject) {
          if (!refVal.validate) this._compile(refVal);
          if (id2 == 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 id2 = this._getId(schema);
      if (id2) baseId = resolveUrl(baseId, id2);
      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 id2;
        if (!PREVENT_SCOPE_CHANGE[part]) {
          id2 = this._getId(schema);
          if (id2) baseId = resolveUrl(baseId, id2);
          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, limit2) {
    if (limit2 === false) return false;
    if (limit2 === void 0 || limit2 === true) return checkNoRef(schema);
    else if (limit2) return countKeys(schema) <= limit2;
  }
  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 key in schema) {
        if (key == "$ref") return false;
        item = schema[key];
        if (typeof item == "object" && !checkNoRef(item)) return false;
      }
    }
    return true;
  }
  function countKeys(schema) {
    var count2 = 0, item;
    if (Array.isArray(schema)) {
      for (var i2 = 0; i2 < schema.length; i2++) {
        item = schema[i2];
        if (typeof item == "object") count2 += countKeys(item);
        if (count2 == Infinity) return Infinity;
      }
    } else {
      for (var key in schema) {
        if (key == "$ref") return Infinity;
        if (SIMPLE_INLINED[key]) {
          count2++;
        } else {
          item = schema[key];
          if (typeof item == "object") count2 += countKeys(item) + 1;
          if (count2 == Infinity) return Infinity;
        }
      }
    }
    return count2;
  }
  function getFullPath(id2, normalize) {
    if (normalize !== false) id2 = normalizeId(id2);
    var p2 = URI.parse(id2);
    return _getFullPath(p2);
  }
  function _getFullPath(p2) {
    return URI.serialize(p2).split("#")[0] + "#";
  }
  var TRAILING_SLASH_HASH = /#\/?$/;
  function normalizeId(id2) {
    return id2 ? id2.replace(TRAILING_SLASH_HASH, "") : "";
  }
  function resolveUrl(baseId, id2) {
    id2 = normalizeId(id2);
    return URI.resolve(baseId, id2);
  }
  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 id2 = 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 id2 == "string") {
        id2 = baseId = normalizeId(baseId ? URI.resolve(baseId, id2) : id2);
        var refVal = self2._refs[id2];
        if (typeof refVal == "string") refVal = self2._refs[refVal];
        if (refVal && refVal.schema) {
          if (!equal2(sch, refVal.schema))
            throw new Error('id "' + id2 + '" resolves to more than one schema');
        } else if (id2 != normalizeId(fullPath)) {
          if (id2[0] == "#") {
            if (localRefs[id2] && !equal2(sch, localRefs[id2]))
              throw new Error('id "' + id2 + '" resolves to more than one schema');
            localRefs[id2] = sch;
          } else {
            self2._refs[id2] = 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$2();
  error_classes = {
    Validation: errorSubclass(ValidationError),
    MissingRef: errorSubclass(MissingRefError)
  };
  function ValidationError(errors2) {
    this.message = "validation failed";
    this.errors = errors2;
    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(node) {
        return function(a2, b2) {
          var aobj = { key: a2, value: node[a2] };
          var bobj = { key: b2, value: node[b2] };
          return f2(aobj, bobj);
        };
      };
    })(opts.cmp);
    var seen2 = [];
    return (function stringify(node) {
      if (node && node.toJSON && typeof node.toJSON === "function") {
        node = node.toJSON();
      }
      if (node === void 0) return;
      if (typeof node == "number") return isFinite(node) ? "" + node : "null";
      if (typeof node !== "object") return JSON.stringify(node);
      var i2, out;
      if (Array.isArray(node)) {
        out = "[";
        for (i2 = 0; i2 < node.length; i2++) {
          if (i2) out += ",";
          out += stringify(node[i2]) || "null";
        }
        return out + "]";
      }
      if (node === null) return "null";
      if (seen2.indexOf(node) !== -1) {
        if (cycles) return JSON.stringify("__cycle__");
        throw new TypeError("Converting circular structure to JSON");
      }
      var seenIndex = seen2.push(node) - 1;
      var keys = Object.keys(node).sort(cmp && cmp(node));
      out = "";
      for (i2 = 0; i2 < keys.length; i2++) {
        var key = keys[i2];
        var value = stringify(node[key]);
        if (!value) continue;
        if (out) out += ",";
        out += JSON.stringify(key) + ":" + value;
      }
      seen2.splice(seenIndex, 1);
      return "{" + out + "}";
    })(data2);
  };
  return fastJsonStableStringify;
}
var validate$2;
var hasRequiredValidate$2;
function requireValidate$2() {
  if (hasRequiredValidate$2) return validate$2;
  hasRequiredValidate$2 = 1;
  validate$2 = function generate_validate(it2, $keyword, $ruleType) {
    var out = "";
    var $async = it2.schema.$async === true, $refKeywords = it2.util.schemaHasRulesExcept(it2.schema, it2.RULES.all, "$ref"), $id2 = it2.self._getId(it2.schema);
    if (it2.opts.strictKeywords) {
      var $unknownKwd = it2.util.schemaUnknownRules(it2.schema, it2.RULES.keywords);
      if ($unknownKwd) {
        var $keywordsMsg = "unknown keyword: " + $unknownKwd;
        if (it2.opts.strictKeywords === "log") it2.logger.warn($keywordsMsg);
        else throw new Error($keywordsMsg);
      }
    }
    if (it2.isTop) {
      out += " var validate = ";
      if ($async) {
        it2.async = true;
        out += "async ";
      }
      out += "function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ";
      if ($id2 && (it2.opts.sourceCode || it2.opts.processCode)) {
        out += " " + ("/*# sourceURL=" + $id2 + " */") + " ";
      }
    }
    if (typeof it2.schema == "boolean" || !($refKeywords || it2.schema.$ref)) {
      var $keyword = "false schema";
      var $lvl = it2.level;
      var $dataLvl = it2.dataLevel;
      var $schema2 = it2.schema[$keyword];
      var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
      var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it2.opts.allErrors;
      var $errorKeyword;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      if (it2.schema === false) {
        if (it2.isTop) {
          $breakOnError = true;
        } else {
          out += " var " + $valid + " = false; ";
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it2.createErrors !== false) {
          out += " { keyword: '" + ($errorKeyword || "false schema") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: {} ";
          if (it2.opts.messages !== false) {
            out += " , message: 'boolean schema is false' ";
          }
          if (it2.opts.verbose) {
            out += " , schema: false , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it2.compositeRule && $breakOnError) {
          if (it2.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 (it2.isTop) {
          if ($async) {
            out += " return data; ";
          } else {
            out += " validate.errors = null; return true; ";
          }
        } else {
          out += " var " + $valid + " = true; ";
        }
      }
      if (it2.isTop) {
        out += " }; return validate; ";
      }
      return out;
    }
    if (it2.isTop) {
      var $top = it2.isTop, $lvl = it2.level = 0, $dataLvl = it2.dataLevel = 0, $data = "data";
      it2.rootId = it2.resolve.fullPath(it2.self._getId(it2.root.schema));
      it2.baseId = it2.baseId || it2.rootId;
      delete it2.isTop;
      it2.dataPathArr = [""];
      if (it2.schema.default !== void 0 && it2.opts.useDefaults && it2.opts.strictDefaults) {
        var $defaultMsg = "default is ignored in the schema root";
        if (it2.opts.strictDefaults === "log") it2.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 = it2.level, $dataLvl = it2.dataLevel, $data = "data" + ($dataLvl || "");
      if ($id2) it2.baseId = it2.resolve.url(it2.baseId, $id2);
      if ($async && !it2.async) throw new Error("async schema in sync schema");
      out += " var errs_" + $lvl + " = errors;";
    }
    var $valid = "valid" + $lvl, $breakOnError = !it2.opts.allErrors, $closingBraces1 = "", $closingBraces2 = "";
    var $errorKeyword;
    var $typeSchema = it2.schema.type, $typeIsArray = Array.isArray($typeSchema);
    if ($typeSchema && it2.opts.nullable && it2.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 (it2.schema.$ref && $refKeywords) {
      if (it2.opts.extendRefs == "fail") {
        throw new Error('$ref: validation keywords used in schema at path "' + it2.errSchemaPath + '" (see option extendRefs)');
      } else if (it2.opts.extendRefs !== true) {
        $refKeywords = false;
        it2.logger.warn('$ref: keywords ignored in schema at path "' + it2.errSchemaPath + '"');
      }
    }
    if (it2.schema.$comment && it2.opts.$comment) {
      out += " " + it2.RULES.all.$comment.code(it2, "$comment");
    }
    if ($typeSchema) {
      if (it2.opts.coerceTypes) {
        var $coerceToTypes = it2.util.coerceToTypes(it2.opts.coerceTypes, $typeSchema);
      }
      var $rulesGroup = it2.RULES.types[$typeSchema];
      if ($coerceToTypes || $typeIsArray || $rulesGroup === true || $rulesGroup && !$shouldUseGroup($rulesGroup)) {
        var $schemaPath = it2.schemaPath + ".type", $errSchemaPath = it2.errSchemaPath + "/type";
        var $schemaPath = it2.schemaPath + ".type", $errSchemaPath = it2.errSchemaPath + "/type", $method = $typeIsArray ? "checkDataTypes" : "checkDataType";
        out += " if (" + it2.util[$method]($typeSchema, $data, it2.opts.strictNumbers, true) + ") { ";
        if ($coerceToTypes) {
          var $dataType = "dataType" + $lvl, $coerced = "coerced" + $lvl;
          out += " var " + $dataType + " = typeof " + $data + "; var " + $coerced + " = undefined; ";
          if (it2.opts.coerceTypes == "array") {
            out += " if (" + $dataType + " == 'object' && Array.isArray(" + $data + ") && " + $data + ".length == 1) { " + $data + " = " + $data + "[0]; " + $dataType + " = typeof " + $data + "; if (" + it2.util.checkDataType(it2.schema.type, $data, it2.opts.strictNumbers) + ") " + $coerced + " = " + $data + "; } ";
          }
          out += " if (" + $coerced + " !== undefined) ; ";
          var arr1 = $coerceToTypes;
          if (arr1) {
            var $type, $i2 = -1, l1 = arr1.length - 1;
            while ($i2 < l1) {
              $type = arr1[$i2 += 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 (it2.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 (it2.createErrors !== false) {
            out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { type: '";
            if ($typeIsArray) {
              out += "" + $typeSchema.join(",");
            } else {
              out += "" + $typeSchema;
            }
            out += "' } ";
            if (it2.opts.messages !== false) {
              out += " , message: 'should be ";
              if ($typeIsArray) {
                out += "" + $typeSchema.join(",");
              } else {
                out += "" + $typeSchema;
              }
              out += "' ";
            }
            if (it2.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it2.compositeRule && $breakOnError) {
            if (it2.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 ? it2.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 (it2.createErrors !== false) {
            out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { type: '";
            if ($typeIsArray) {
              out += "" + $typeSchema.join(",");
            } else {
              out += "" + $typeSchema;
            }
            out += "' } ";
            if (it2.opts.messages !== false) {
              out += " , message: 'should be ";
              if ($typeIsArray) {
                out += "" + $typeSchema.join(",");
              } else {
                out += "" + $typeSchema;
              }
              out += "' ";
            }
            if (it2.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it2.compositeRule && $breakOnError) {
            if (it2.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 (it2.schema.$ref && !$refKeywords) {
      out += " " + it2.RULES.all.$ref.code(it2, "$ref") + " ";
      if ($breakOnError) {
        out += " } if (errors === ";
        if ($top) {
          out += "0";
        } else {
          out += "errs_" + $lvl;
        }
        out += ") { ";
        $closingBraces2 += "}";
      }
    } else {
      var arr2 = it2.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 (" + it2.util.checkDataType($rulesGroup.type, $data, it2.opts.strictNumbers) + ") { ";
            }
            if (it2.opts.useDefaults) {
              if ($rulesGroup.type == "object" && it2.schema.properties) {
                var $schema2 = it2.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 + it2.util.getProperty($propertyKey);
                      if (it2.compositeRule) {
                        if (it2.opts.strictDefaults) {
                          var $defaultMsg = "default is ignored for: " + $passData;
                          if (it2.opts.strictDefaults === "log") it2.logger.warn($defaultMsg);
                          else throw new Error($defaultMsg);
                        }
                      } else {
                        out += " if (" + $passData + " === undefined ";
                        if (it2.opts.useDefaults == "empty") {
                          out += " || " + $passData + " === null || " + $passData + " === '' ";
                        }
                        out += " ) " + $passData + " = ";
                        if (it2.opts.useDefaults == "shared") {
                          out += " " + it2.useDefault($sch.default) + " ";
                        } else {
                          out += " " + JSON.stringify($sch.default) + " ";
                        }
                        out += "; ";
                      }
                    }
                  }
                }
              } else if ($rulesGroup.type == "array" && Array.isArray(it2.schema.items)) {
                var arr4 = it2.schema.items;
                if (arr4) {
                  var $sch, $i2 = -1, l4 = arr4.length - 1;
                  while ($i2 < l4) {
                    $sch = arr4[$i2 += 1];
                    if ($sch.default !== void 0) {
                      var $passData = $data + "[" + $i2 + "]";
                      if (it2.compositeRule) {
                        if (it2.opts.strictDefaults) {
                          var $defaultMsg = "default is ignored for: " + $passData;
                          if (it2.opts.strictDefaults === "log") it2.logger.warn($defaultMsg);
                          else throw new Error($defaultMsg);
                        }
                      } else {
                        out += " if (" + $passData + " === undefined ";
                        if (it2.opts.useDefaults == "empty") {
                          out += " || " + $passData + " === null || " + $passData + " === '' ";
                        }
                        out += " ) " + $passData + " = ";
                        if (it2.opts.useDefaults == "shared") {
                          out += " " + it2.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(it2, $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 = it2.schemaPath + ".type", $errSchemaPath = it2.errSchemaPath + "/type";
                var $$outStack = $$outStack || [];
                $$outStack.push(out);
                out = "";
                if (it2.createErrors !== false) {
                  out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { type: '";
                  if ($typeIsArray) {
                    out += "" + $typeSchema.join(",");
                  } else {
                    out += "" + $typeSchema;
                  }
                  out += "' } ";
                  if (it2.opts.messages !== false) {
                    out += " , message: 'should be ";
                    if ($typeIsArray) {
                      out += "" + $typeSchema.join(",");
                    } else {
                      out += "" + $typeSchema;
                    }
                    out += "' ";
                  }
                  if (it2.opts.verbose) {
                    out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
                  }
                  out += " } ";
                } else {
                  out += " {} ";
                }
                var __err = out;
                out = $$outStack.pop();
                if (!it2.compositeRule && $breakOnError) {
                  if (it2.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 it2.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 (it2.schema[impl[i4]] !== void 0) return true;
    }
    return out;
  };
  return validate$2;
}
var compile_1;
var hasRequiredCompile$2;
function requireCompile$2() {
  if (hasRequiredCompile$2) return compile_1;
  hasRequiredCompile$2 = 1;
  var resolve2 = requireResolve$2(), util2 = requireUtil$2(), errorClasses = requireError_classes(), stableStringify = requireFastJsonStableStringify();
  var validateGenerator = requireValidate$2();
  var ucs2length2 = util2.ucs2length;
  var equal2 = requireFastDeepEqual();
  var ValidationError = errorClasses.Validation;
  compile_1 = compile2;
  function compile2(schema, root, localRefs, baseId) {
    var self2 = this, opts = this._opts, refVal = [void 0], refs = {}, patterns = [], patternsHash = {}, defaults2 = [], defaultsHash = {}, customRules = [];
    function patternCode(i2, patterns2) {
      var regExpCode = opts.regExp ? "regExp" : "new RegExp";
      return "var pattern" + i2 + " = " + regExpCode + "(" + util2.toQuotedString(patterns2[i2]) + ");";
    }
    root = root || { schema, refVal, refs };
    var c = checkCompiling.call(this, schema, root, baseId);
    var compilation = this._compilations[c.index];
    if (c.compiling) return compilation.callValidate = callValidate;
    var formats2 = this._formats;
    var RULES = this.RULES;
    try {
      var v2 = localCompile(schema, root, localRefs, baseId);
      compilation.validate = v2;
      var cv2 = compilation.callValidate;
      if (cv2) {
        cv2.schema = v2.schema;
        cv2.errors = null;
        cv2.refs = v2.refs;
        cv2.refVal = v2.refVal;
        cv2.root = v2.root;
        cv2.$async = v2.$async;
        if (opts.sourceCode) cv2.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 compile2.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: resolveRef2,
        usePattern,
        useDefault,
        useCustomRule,
        opts,
        formats: formats2,
        logger: self2.logger,
        self: self2
      });
      sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults2, 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",
          "regExp",
          sourceCode
        );
        validate2 = makeValidate(
          self2,
          RULES,
          formats2,
          root,
          refVal,
          defaults2,
          customRules,
          equal2,
          ucs2length2,
          ValidationError,
          opts.regExp
        );
        refVal[0] = validate2;
      } catch (e2) {
        self2.logger.error("Error compiling schema, function code:", sourceCode);
        throw e2;
      }
      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: defaults2
        };
      }
      return validate2;
    }
    function resolveRef2(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 : compile2.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, code2) {
      return typeof refVal2 == "object" || typeof refVal2 == "boolean" ? { code: code2, schema: refVal2, inline: true } : { code: code2, $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] = defaults2.length;
            defaults2[index2] = value;
          }
          return "default" + index2;
      }
    }
    function useCustomRule(rule, schema2, parentSchema, it2) {
      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 compile3 = rule.definition.compile, inline = rule.definition.inline, macro = rule.definition.macro;
      var validate2;
      if (compile3) {
        validate2 = compile3.call(self2, schema2, parentSchema, it2);
      } else if (macro) {
        validate2 = macro.call(self2, schema2, parentSchema, it2);
        if (opts.validateSchema !== false) self2.validateSchema(validate2, true);
      } else if (inline) {
        validate2 = inline.call(self2, it2, 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 c = this._compilations[i2];
      if (c.schema == schema && c.root == root && c.baseId == baseId) return i2;
    }
    return -1;
  }
  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 code2 = "";
    for (var i2 = 0; i2 < arr.length; i2++)
      code2 += statement(i2, arr);
    return code2;
  }
  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(key, value) {
    this._cache[key] = value;
  };
  Cache.prototype.get = function Cache_get(key) {
    return this._cache[key];
  };
  Cache.prototype.del = function Cache_del(key) {
    delete this._cache[key];
  };
  Cache.prototype.clear = function Cache_clear() {
    this._cache = {};
  };
  return cache.exports;
}
var formats_1;
var hasRequiredFormats$1;
function requireFormats$1() {
  if (hasRequiredFormats$1) return formats_1;
  hasRequiredFormats$1 = 1;
  var util2 = requireUtil$2();
  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 = formats2;
  function formats2(mode) {
    mode = mode == "full" ? "full" : "fast";
    return util2.copy(formats2[mode], /* @__PURE__ */ Object.create(null));
  }
  formats2.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
  };
  formats2.full = {
    date: date2,
    time: time2,
    "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 time2(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]) && time2(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 (e2) {
      return false;
    }
  }
  return formats_1;
}
var ref$2;
var hasRequiredRef$2;
function requireRef$2() {
  if (hasRequiredRef$2) return ref$2;
  hasRequiredRef$2 = 1;
  ref$2 = function generate_ref(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $async, $refCode;
    if ($schema2 == "#" || $schema2 == "#/") {
      if (it2.isRoot) {
        $async = it2.async;
        $refCode = "validate";
      } else {
        $async = it2.root.schema.$async === true;
        $refCode = "root.refVal[0]";
      }
    } else {
      var $refVal = it2.resolveRef(it2.baseId, $schema2, it2.isRoot);
      if ($refVal === void 0) {
        var $message = it2.MissingRefError.message(it2.baseId, $schema2);
        if (it2.opts.missingRefs == "fail") {
          it2.logger.error($message);
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it2.createErrors !== false) {
            out += " { keyword: '$ref' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { ref: '" + it2.util.escapeQuotes($schema2) + "' } ";
            if (it2.opts.messages !== false) {
              out += " , message: 'can\\'t resolve reference " + it2.util.escapeQuotes($schema2) + "' ";
            }
            if (it2.opts.verbose) {
              out += " , schema: " + it2.util.toQuotedString($schema2) + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it2.compositeRule && $breakOnError) {
            if (it2.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 (it2.opts.missingRefs == "ignore") {
          it2.logger.warn($message);
          if ($breakOnError) {
            out += " if (true) { ";
          }
        } else {
          throw new it2.MissingRefError(it2.baseId, $schema2, $message);
        }
      } else if ($refVal.inline) {
        var $it = it2.util.copy(it2);
        $it.level++;
        var $nextValid = "valid" + $it.level;
        $it.schema = $refVal.schema;
        $it.schemaPath = "";
        $it.errSchemaPath = $schema2;
        var $code = it2.validate($it).replace(/validate\.schema/g, $refVal.code);
        out += " " + $code + " ";
        if ($breakOnError) {
          out += " if (" + $nextValid + ") { ";
        }
      } else {
        $async = $refVal.$async === true || it2.async && $refVal.$async !== false;
        $refCode = $refVal.code;
      }
    }
    if ($refCode) {
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it2.opts.passContext) {
        out += " " + $refCode + ".call(this, ";
      } else {
        out += " " + $refCode + "( ";
      }
      out += " " + $data + ", (dataPath || '')";
      if (it2.errorPath != '""') {
        out += " + " + it2.errorPath;
      }
      var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it2.dataPathArr[$dataLvl] : "parentDataProperty";
      out += " , " + $parentData + " , " + $parentDataProperty + ", rootData)  ";
      var __callValidate = out;
      out = $$outStack.pop();
      if ($async) {
        if (!it2.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$2;
}
var allOf$2;
var hasRequiredAllOf$2;
function requireAllOf$2() {
  if (hasRequiredAllOf$2) return allOf$2;
  hasRequiredAllOf$2 = 1;
  allOf$2 = function generate_allOf(it2, $keyword, $ruleType) {
    var out = " ";
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $it = it2.util.copy(it2);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $currentBaseId = $it.baseId, $allSchemasEmpty = true;
    var arr1 = $schema2;
    if (arr1) {
      var $sch, $i2 = -1, l1 = arr1.length - 1;
      while ($i2 < l1) {
        $sch = arr1[$i2 += 1];
        if (it2.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it2.util.schemaHasRules($sch, it2.RULES.all)) {
          $allSchemasEmpty = false;
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + "[" + $i2 + "]";
          $it.errSchemaPath = $errSchemaPath + "/" + $i2;
          out += "  " + it2.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$2;
}
var anyOf$2;
var hasRequiredAnyOf$2;
function requireAnyOf$2() {
  if (hasRequiredAnyOf$2) return anyOf$2;
  hasRequiredAnyOf$2 = 1;
  anyOf$2 = function generate_anyOf(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $errs = "errs__" + $lvl;
    var $it = it2.util.copy(it2);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $noEmptySchema = $schema2.every(function($sch2) {
      return it2.opts.strictKeywords ? typeof $sch2 == "object" && Object.keys($sch2).length > 0 || $sch2 === false : it2.util.schemaHasRules($sch2, it2.RULES.all);
    });
    if ($noEmptySchema) {
      var $currentBaseId = $it.baseId;
      out += " var " + $errs + " = errors; var " + $valid + " = false;  ";
      var $wasComposite = it2.compositeRule;
      it2.compositeRule = $it.compositeRule = true;
      var arr1 = $schema2;
      if (arr1) {
        var $sch, $i2 = -1, l1 = arr1.length - 1;
        while ($i2 < l1) {
          $sch = arr1[$i2 += 1];
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + "[" + $i2 + "]";
          $it.errSchemaPath = $errSchemaPath + "/" + $i2;
          out += "  " + it2.validate($it) + " ";
          $it.baseId = $currentBaseId;
          out += " " + $valid + " = " + $valid + " || " + $nextValid + "; if (!" + $valid + ") { ";
          $closingBraces += "}";
        }
      }
      it2.compositeRule = $it.compositeRule = $wasComposite;
      out += " " + $closingBraces + " if (!" + $valid + ") {   var err =   ";
      if (it2.createErrors !== false) {
        out += " { keyword: 'anyOf' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: {} ";
        if (it2.opts.messages !== false) {
          out += " , message: 'should match some schema in anyOf' ";
        }
        if (it2.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      if (!it2.compositeRule && $breakOnError) {
        if (it2.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 (it2.opts.allErrors) {
        out += " } ";
      }
    } else {
      if ($breakOnError) {
        out += " if (true) { ";
      }
    }
    return out;
  };
  return anyOf$2;
}
var comment;
var hasRequiredComment;
function requireComment() {
  if (hasRequiredComment) return comment;
  hasRequiredComment = 1;
  comment = function generate_comment(it2, $keyword, $ruleType) {
    var out = " ";
    var $schema2 = it2.schema[$keyword];
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    !it2.opts.allErrors;
    var $comment = it2.util.toQuotedString($schema2);
    if (it2.opts.$comment === true) {
      out += " console.log(" + $comment + ");";
    } else if (typeof it2.opts.$comment == "function") {
      out += " self._opts.$comment(" + $comment + ", " + it2.util.toQuotedString($errSchemaPath) + ", validate.root.schema);";
    }
    return out;
  };
  return comment;
}
var _const$2;
var hasRequired_const$2;
function require_const$2() {
  if (hasRequired_const$2) return _const$2;
  hasRequired_const$2 = 1;
  _const$2 = function generate_const(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $isData = it2.opts.$data && $schema2 && $schema2.$data;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it2.util.getData($schema2.$data, $dataLvl, it2.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 (it2.createErrors !== false) {
      out += " { keyword: 'const' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { allowedValue: schema" + $lvl + " } ";
      if (it2.opts.messages !== false) {
        out += " , message: 'should be equal to constant' ";
      }
      if (it2.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it2.compositeRule && $breakOnError) {
      if (it2.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$2;
}
var contains$2;
var hasRequiredContains$2;
function requireContains$2() {
  if (hasRequiredContains$2) return contains$2;
  hasRequiredContains$2 = 1;
  contains$2 = function generate_contains(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $errs = "errs__" + $lvl;
    var $it = it2.util.copy(it2);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $idx = "i" + $lvl, $dataNxt = $it.dataLevel = it2.dataLevel + 1, $nextData = "data" + $dataNxt, $currentBaseId = it2.baseId, $nonEmptySchema = it2.opts.strictKeywords ? typeof $schema2 == "object" && Object.keys($schema2).length > 0 || $schema2 === false : it2.util.schemaHasRules($schema2, it2.RULES.all);
    out += "var " + $errs + " = errors;var " + $valid + ";";
    if ($nonEmptySchema) {
      var $wasComposite = it2.compositeRule;
      it2.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 = it2.util.getPathExpr(it2.errorPath, $idx, it2.opts.jsonPointers, true);
      var $passData = $data + "[" + $idx + "]";
      $it.dataPathArr[$dataNxt] = $idx;
      var $code = it2.validate($it);
      $it.baseId = $currentBaseId;
      if (it2.util.varOccurences($code, $nextData) < 2) {
        out += " " + it2.util.varReplace($code, $nextData, $passData) + " ";
      } else {
        out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
      }
      out += " if (" + $nextValid + ") break; }  ";
      it2.compositeRule = $it.compositeRule = $wasComposite;
      out += " " + $closingBraces + " if (!" + $nextValid + ") {";
    } else {
      out += " if (" + $data + ".length == 0) {";
    }
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it2.createErrors !== false) {
      out += " { keyword: 'contains' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: {} ";
      if (it2.opts.messages !== false) {
        out += " , message: 'should contain a valid item' ";
      }
      if (it2.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it2.compositeRule && $breakOnError) {
      if (it2.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 (it2.opts.allErrors) {
      out += " } ";
    }
    return out;
  };
  return contains$2;
}
var dependencies$2;
var hasRequiredDependencies$2;
function requireDependencies$2() {
  if (hasRequiredDependencies$2) return dependencies$2;
  hasRequiredDependencies$2 = 1;
  dependencies$2 = function generate_dependencies(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $errs = "errs__" + $lvl;
    var $it = it2.util.copy(it2);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $schemaDeps = {}, $propertyDeps = {}, $ownProperties = it2.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 = it2.errorPath;
    out += "var missing" + $lvl + ";";
    for (var $property in $propertyDeps) {
      $deps = $propertyDeps[$property];
      if ($deps.length) {
        out += " if ( " + $data + it2.util.getProperty($property) + " !== undefined ";
        if ($ownProperties) {
          out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($property) + "') ";
        }
        if ($breakOnError) {
          out += " && ( ";
          var arr1 = $deps;
          if (arr1) {
            var $propertyKey, $i2 = -1, l1 = arr1.length - 1;
            while ($i2 < l1) {
              $propertyKey = arr1[$i2 += 1];
              if ($i2) {
                out += " || ";
              }
              var $prop = it2.util.getProperty($propertyKey), $useData = $data + $prop;
              out += " ( ( " + $useData + " === undefined ";
              if ($ownProperties) {
                out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($propertyKey) + "') ";
              }
              out += ") && (missing" + $lvl + " = " + it2.util.toQuotedString(it2.opts.jsonPointers ? $propertyKey : $prop) + ") ) ";
            }
          }
          out += ")) {  ";
          var $propertyPath = "missing" + $lvl, $missingProperty = "' + " + $propertyPath + " + '";
          if (it2.opts._errorDataPathProperty) {
            it2.errorPath = it2.opts.jsonPointers ? it2.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + " + " + $propertyPath;
          }
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it2.createErrors !== false) {
            out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { property: '" + it2.util.escapeQuotes($property) + "', missingProperty: '" + $missingProperty + "', depsCount: " + $deps.length + ", deps: '" + it2.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + "' } ";
            if (it2.opts.messages !== false) {
              out += " , message: 'should have ";
              if ($deps.length == 1) {
                out += "property " + it2.util.escapeQuotes($deps[0]);
              } else {
                out += "properties " + it2.util.escapeQuotes($deps.join(", "));
              }
              out += " when property " + it2.util.escapeQuotes($property) + " is present' ";
            }
            if (it2.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it2.compositeRule && $breakOnError) {
            if (it2.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 = it2.util.getProperty($propertyKey), $missingProperty = it2.util.escapeQuotes($propertyKey), $useData = $data + $prop;
              if (it2.opts._errorDataPathProperty) {
                it2.errorPath = it2.util.getPath($currentErrorPath, $propertyKey, it2.opts.jsonPointers);
              }
              out += " if ( " + $useData + " === undefined ";
              if ($ownProperties) {
                out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($propertyKey) + "') ";
              }
              out += ") {  var err =   ";
              if (it2.createErrors !== false) {
                out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { property: '" + it2.util.escapeQuotes($property) + "', missingProperty: '" + $missingProperty + "', depsCount: " + $deps.length + ", deps: '" + it2.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + "' } ";
                if (it2.opts.messages !== false) {
                  out += " , message: 'should have ";
                  if ($deps.length == 1) {
                    out += "property " + it2.util.escapeQuotes($deps[0]);
                  } else {
                    out += "properties " + it2.util.escapeQuotes($deps.join(", "));
                  }
                  out += " when property " + it2.util.escapeQuotes($property) + " is present' ";
                }
                if (it2.opts.verbose) {
                  out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
                }
                out += " } ";
              } else {
                out += " {} ";
              }
              out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ";
            }
          }
        }
        out += " }   ";
        if ($breakOnError) {
          $closingBraces += "}";
          out += " else { ";
        }
      }
    }
    it2.errorPath = $currentErrorPath;
    var $currentBaseId = $it.baseId;
    for (var $property in $schemaDeps) {
      var $sch = $schemaDeps[$property];
      if (it2.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it2.util.schemaHasRules($sch, it2.RULES.all)) {
        out += " " + $nextValid + " = true; if ( " + $data + it2.util.getProperty($property) + " !== undefined ";
        if ($ownProperties) {
          out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($property) + "') ";
        }
        out += ") { ";
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + it2.util.getProperty($property);
        $it.errSchemaPath = $errSchemaPath + "/" + it2.util.escapeFragment($property);
        out += "  " + it2.validate($it) + " ";
        $it.baseId = $currentBaseId;
        out += " }  ";
        if ($breakOnError) {
          out += " if (" + $nextValid + ") { ";
          $closingBraces += "}";
        }
      }
    }
    if ($breakOnError) {
      out += "   " + $closingBraces + " if (" + $errs + " == errors) {";
    }
    return out;
  };
  return dependencies$2;
}
var _enum$2;
var hasRequired_enum$2;
function require_enum$2() {
  if (hasRequired_enum$2) return _enum$2;
  hasRequired_enum$2 = 1;
  _enum$2 = function generate_enum(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $isData = it2.opts.$data && $schema2 && $schema2.$data;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it2.util.getData($schema2.$data, $dataLvl, it2.dataPathArr) + "; ";
    }
    var $i2 = "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 " + $i2 + "=0; " + $i2 + "<" + $vSchema + ".length; " + $i2 + "++) if (equal(" + $data + ", " + $vSchema + "[" + $i2 + "])) { " + $valid + " = true; break; }";
    if ($isData) {
      out += "  }  ";
    }
    out += " if (!" + $valid + ") {   ";
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it2.createErrors !== false) {
      out += " { keyword: 'enum' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { allowedValues: schema" + $lvl + " } ";
      if (it2.opts.messages !== false) {
        out += " , message: 'should be equal to one of the allowed values' ";
      }
      if (it2.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it2.compositeRule && $breakOnError) {
      if (it2.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$2;
}
var format$4;
var hasRequiredFormat$4;
function requireFormat$4() {
  if (hasRequiredFormat$4) return format$4;
  hasRequiredFormat$4 = 1;
  format$4 = function generate_format(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    if (it2.opts.format === false) {
      if ($breakOnError) {
        out += " if (true) { ";
      }
      return out;
    }
    var $isData = it2.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it2.util.getData($schema2.$data, $dataLvl, it2.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    var $unknownFormats = it2.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 (it2.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 (it2.async) {
        out += " (async" + $lvl + " ? await " + $format + "(" + $data + ") : " + $format + "(" + $data + ")) ";
      } else {
        out += " " + $format + "(" + $data + ") ";
      }
      out += " : " + $format + ".test(" + $data + "))))) {";
    } else {
      var $format = it2.formats[$schema2];
      if (!$format) {
        if ($unknownFormats == "ignore") {
          it2.logger.warn('unknown format "' + $schema2 + '" ignored in schema at path "' + it2.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 "' + it2.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 (!it2.async) throw new Error("async format in sync schema");
        var $formatRef = "formats" + it2.util.getProperty($schema2) + ".validate";
        out += " if (!(await " + $formatRef + "(" + $data + "))) { ";
      } else {
        out += " if (! ";
        var $formatRef = "formats" + it2.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 (it2.createErrors !== false) {
      out += " { keyword: 'format' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { format:  ";
      if ($isData) {
        out += "" + $schemaValue;
      } else {
        out += "" + it2.util.toQuotedString($schema2);
      }
      out += "  } ";
      if (it2.opts.messages !== false) {
        out += ` , message: 'should match format "`;
        if ($isData) {
          out += "' + " + $schemaValue + " + '";
        } else {
          out += "" + it2.util.escapeQuotes($schema2);
        }
        out += `"' `;
      }
      if (it2.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + it2.util.toQuotedString($schema2);
        }
        out += "         , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it2.compositeRule && $breakOnError) {
      if (it2.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$4;
}
var _if$2;
var hasRequired_if$2;
function require_if$2() {
  if (hasRequired_if$2) return _if$2;
  hasRequired_if$2 = 1;
  _if$2 = function generate_if(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $errs = "errs__" + $lvl;
    var $it = it2.util.copy(it2);
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $thenSch = it2.schema["then"], $elseSch = it2.schema["else"], $thenPresent = $thenSch !== void 0 && (it2.opts.strictKeywords ? typeof $thenSch == "object" && Object.keys($thenSch).length > 0 || $thenSch === false : it2.util.schemaHasRules($thenSch, it2.RULES.all)), $elsePresent = $elseSch !== void 0 && (it2.opts.strictKeywords ? typeof $elseSch == "object" && Object.keys($elseSch).length > 0 || $elseSch === false : it2.util.schemaHasRules($elseSch, it2.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 = it2.compositeRule;
      it2.compositeRule = $it.compositeRule = true;
      out += "  " + it2.validate($it) + " ";
      $it.baseId = $currentBaseId;
      $it.createErrors = true;
      out += "  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; }  ";
      it2.compositeRule = $it.compositeRule = $wasComposite;
      if ($thenPresent) {
        out += " if (" + $nextValid + ") {  ";
        $it.schema = it2.schema["then"];
        $it.schemaPath = it2.schemaPath + ".then";
        $it.errSchemaPath = it2.errSchemaPath + "/then";
        out += "  " + it2.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 = it2.schema["else"];
        $it.schemaPath = it2.schemaPath + ".else";
        $it.errSchemaPath = it2.errSchemaPath + "/else";
        out += "  " + it2.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 (it2.createErrors !== false) {
        out += " { keyword: 'if' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { failingKeyword: " + $ifClause + " } ";
        if (it2.opts.messages !== false) {
          out += ` , message: 'should match "' + ` + $ifClause + ` + '" schema' `;
        }
        if (it2.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      if (!it2.compositeRule && $breakOnError) {
        if (it2.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$2;
}
var items$2;
var hasRequiredItems$2;
function requireItems$2() {
  if (hasRequiredItems$2) return items$2;
  hasRequiredItems$2 = 1;
  items$2 = function generate_items(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $errs = "errs__" + $lvl;
    var $it = it2.util.copy(it2);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $idx = "i" + $lvl, $dataNxt = $it.dataLevel = it2.dataLevel + 1, $nextData = "data" + $dataNxt, $currentBaseId = it2.baseId;
    out += "var " + $errs + " = errors;var " + $valid + ";";
    if (Array.isArray($schema2)) {
      var $additionalItems = it2.schema.additionalItems;
      if ($additionalItems === false) {
        out += " " + $valid + " = " + $data + ".length <= " + $schema2.length + "; ";
        var $currErrSchemaPath = $errSchemaPath;
        $errSchemaPath = it2.errSchemaPath + "/additionalItems";
        out += "  if (!" + $valid + ") {   ";
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it2.createErrors !== false) {
          out += " { keyword: 'additionalItems' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schema2.length + " } ";
          if (it2.opts.messages !== false) {
            out += " , message: 'should NOT have more than " + $schema2.length + " items' ";
          }
          if (it2.opts.verbose) {
            out += " , schema: false , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it2.compositeRule && $breakOnError) {
          if (it2.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, $i2 = -1, l1 = arr1.length - 1;
        while ($i2 < l1) {
          $sch = arr1[$i2 += 1];
          if (it2.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it2.util.schemaHasRules($sch, it2.RULES.all)) {
            out += " " + $nextValid + " = true; if (" + $data + ".length > " + $i2 + ") { ";
            var $passData = $data + "[" + $i2 + "]";
            $it.schema = $sch;
            $it.schemaPath = $schemaPath + "[" + $i2 + "]";
            $it.errSchemaPath = $errSchemaPath + "/" + $i2;
            $it.errorPath = it2.util.getPathExpr(it2.errorPath, $i2, it2.opts.jsonPointers, true);
            $it.dataPathArr[$dataNxt] = $i2;
            var $code = it2.validate($it);
            $it.baseId = $currentBaseId;
            if (it2.util.varOccurences($code, $nextData) < 2) {
              out += " " + it2.util.varReplace($code, $nextData, $passData) + " ";
            } else {
              out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
            }
            out += " }  ";
            if ($breakOnError) {
              out += " if (" + $nextValid + ") { ";
              $closingBraces += "}";
            }
          }
        }
      }
      if (typeof $additionalItems == "object" && (it2.opts.strictKeywords ? typeof $additionalItems == "object" && Object.keys($additionalItems).length > 0 || $additionalItems === false : it2.util.schemaHasRules($additionalItems, it2.RULES.all))) {
        $it.schema = $additionalItems;
        $it.schemaPath = it2.schemaPath + ".additionalItems";
        $it.errSchemaPath = it2.errSchemaPath + "/additionalItems";
        out += " " + $nextValid + " = true; if (" + $data + ".length > " + $schema2.length + ") {  for (var " + $idx + " = " + $schema2.length + "; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
        $it.errorPath = it2.util.getPathExpr(it2.errorPath, $idx, it2.opts.jsonPointers, true);
        var $passData = $data + "[" + $idx + "]";
        $it.dataPathArr[$dataNxt] = $idx;
        var $code = it2.validate($it);
        $it.baseId = $currentBaseId;
        if (it2.util.varOccurences($code, $nextData) < 2) {
          out += " " + it2.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 (it2.opts.strictKeywords ? typeof $schema2 == "object" && Object.keys($schema2).length > 0 || $schema2 === false : it2.util.schemaHasRules($schema2, it2.RULES.all)) {
      $it.schema = $schema2;
      $it.schemaPath = $schemaPath;
      $it.errSchemaPath = $errSchemaPath;
      out += "  for (var " + $idx + " = 0; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
      $it.errorPath = it2.util.getPathExpr(it2.errorPath, $idx, it2.opts.jsonPointers, true);
      var $passData = $data + "[" + $idx + "]";
      $it.dataPathArr[$dataNxt] = $idx;
      var $code = it2.validate($it);
      $it.baseId = $currentBaseId;
      if (it2.util.varOccurences($code, $nextData) < 2) {
        out += " " + it2.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$2;
}
var _limit;
var hasRequired_limit;
function require_limit() {
  if (hasRequired_limit) return _limit;
  hasRequired_limit = 1;
  _limit = function generate__limit(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $errorKeyword;
    var $data = "data" + ($dataLvl || "");
    var $isData = it2.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it2.util.getData($schema2.$data, $dataLvl, it2.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    var $isMax = $keyword == "maximum", $exclusiveKeyword = $isMax ? "exclusiveMaximum" : "exclusiveMinimum", $schemaExcl = it2.schema[$exclusiveKeyword], $isDataExcl = it2.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 = it2.util.getData($schemaExcl.$data, $dataLvl, it2.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 (it2.createErrors !== false) {
        out += " { keyword: '" + ($errorKeyword || "_exclusiveLimit") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: {} ";
        if (it2.opts.messages !== false) {
          out += " , message: '" + $exclusiveKeyword + " should be boolean' ";
        }
        if (it2.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it2.compositeRule && $breakOnError) {
        if (it2.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 = it2.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 = it2.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 = it2.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 (it2.createErrors !== false) {
      out += " { keyword: '" + ($errorKeyword || "_limit") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { comparison: " + $opExpr + ", limit: " + $schemaValue + ", exclusive: " + $exclusive + " } ";
      if (it2.opts.messages !== false) {
        out += " , message: 'should be " + $opStr + " ";
        if ($isData) {
          out += "' + " + $schemaValue;
        } else {
          out += "" + $schemaValue + "'";
        }
      }
      if (it2.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + $schema2;
        }
        out += "         , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it2.compositeRule && $breakOnError) {
      if (it2.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(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $errorKeyword;
    var $data = "data" + ($dataLvl || "");
    var $isData = it2.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it2.util.getData($schema2.$data, $dataLvl, it2.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 (it2.createErrors !== false) {
      out += " { keyword: '" + ($errorKeyword || "_limitItems") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
      if (it2.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 (it2.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + $schema2;
        }
        out += "         , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it2.compositeRule && $breakOnError) {
      if (it2.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(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $errorKeyword;
    var $data = "data" + ($dataLvl || "");
    var $isData = it2.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it2.util.getData($schema2.$data, $dataLvl, it2.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 (it2.opts.unicode === false) {
      out += " " + $data + ".length ";
    } else {
      out += " ucs2length(" + $data + ") ";
    }
    out += " " + $op + " " + $schemaValue + ") { ";
    var $errorKeyword = $keyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it2.createErrors !== false) {
      out += " { keyword: '" + ($errorKeyword || "_limitLength") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
      if (it2.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 (it2.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + $schema2;
        }
        out += "         , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it2.compositeRule && $breakOnError) {
      if (it2.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(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $errorKeyword;
    var $data = "data" + ($dataLvl || "");
    var $isData = it2.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it2.util.getData($schema2.$data, $dataLvl, it2.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 (it2.createErrors !== false) {
      out += " { keyword: '" + ($errorKeyword || "_limitProperties") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
      if (it2.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 (it2.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + $schema2;
        }
        out += "         , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it2.compositeRule && $breakOnError) {
      if (it2.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$2;
var hasRequiredMultipleOf$2;
function requireMultipleOf$2() {
  if (hasRequiredMultipleOf$2) return multipleOf$2;
  hasRequiredMultipleOf$2 = 1;
  multipleOf$2 = function generate_multipleOf(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $isData = it2.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it2.util.getData($schema2.$data, $dataLvl, it2.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 (it2.opts.multipleOfPrecision) {
      out += " Math.abs(Math.round(division" + $lvl + ") - division" + $lvl + ") > 1e-" + it2.opts.multipleOfPrecision + " ";
    } else {
      out += " division" + $lvl + " !== parseInt(division" + $lvl + ") ";
    }
    out += " ) ";
    if ($isData) {
      out += "  )  ";
    }
    out += " ) {   ";
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it2.createErrors !== false) {
      out += " { keyword: 'multipleOf' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { multipleOf: " + $schemaValue + " } ";
      if (it2.opts.messages !== false) {
        out += " , message: 'should be multiple of ";
        if ($isData) {
          out += "' + " + $schemaValue;
        } else {
          out += "" + $schemaValue + "'";
        }
      }
      if (it2.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + $schema2;
        }
        out += "         , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it2.compositeRule && $breakOnError) {
      if (it2.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$2;
}
var not$2;
var hasRequiredNot$2;
function requireNot$2() {
  if (hasRequiredNot$2) return not$2;
  hasRequiredNot$2 = 1;
  not$2 = function generate_not(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $errs = "errs__" + $lvl;
    var $it = it2.util.copy(it2);
    $it.level++;
    var $nextValid = "valid" + $it.level;
    if (it2.opts.strictKeywords ? typeof $schema2 == "object" && Object.keys($schema2).length > 0 || $schema2 === false : it2.util.schemaHasRules($schema2, it2.RULES.all)) {
      $it.schema = $schema2;
      $it.schemaPath = $schemaPath;
      $it.errSchemaPath = $errSchemaPath;
      out += " var " + $errs + " = errors;  ";
      var $wasComposite = it2.compositeRule;
      it2.compositeRule = $it.compositeRule = true;
      $it.createErrors = false;
      var $allErrorsOption;
      if ($it.opts.allErrors) {
        $allErrorsOption = $it.opts.allErrors;
        $it.opts.allErrors = false;
      }
      out += " " + it2.validate($it) + " ";
      $it.createErrors = true;
      if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
      it2.compositeRule = $it.compositeRule = $wasComposite;
      out += " if (" + $nextValid + ") {   ";
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it2.createErrors !== false) {
        out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: {} ";
        if (it2.opts.messages !== false) {
          out += " , message: 'should NOT be valid' ";
        }
        if (it2.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it2.compositeRule && $breakOnError) {
        if (it2.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 (it2.opts.allErrors) {
        out += " } ";
      }
    } else {
      out += "  var err =   ";
      if (it2.createErrors !== false) {
        out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: {} ";
        if (it2.opts.messages !== false) {
          out += " , message: 'should NOT be valid' ";
        }
        if (it2.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.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$2;
}
var oneOf$2;
var hasRequiredOneOf$2;
function requireOneOf$2() {
  if (hasRequiredOneOf$2) return oneOf$2;
  hasRequiredOneOf$2 = 1;
  oneOf$2 = function generate_oneOf(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $errs = "errs__" + $lvl;
    var $it = it2.util.copy(it2);
    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 = it2.compositeRule;
    it2.compositeRule = $it.compositeRule = true;
    var arr1 = $schema2;
    if (arr1) {
      var $sch, $i2 = -1, l1 = arr1.length - 1;
      while ($i2 < l1) {
        $sch = arr1[$i2 += 1];
        if (it2.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it2.util.schemaHasRules($sch, it2.RULES.all)) {
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + "[" + $i2 + "]";
          $it.errSchemaPath = $errSchemaPath + "/" + $i2;
          out += "  " + it2.validate($it) + " ";
          $it.baseId = $currentBaseId;
        } else {
          out += " var " + $nextValid + " = true; ";
        }
        if ($i2) {
          out += " if (" + $nextValid + " && " + $prevValid + ") { " + $valid + " = false; " + $passingSchemas + " = [" + $passingSchemas + ", " + $i2 + "]; } else { ";
          $closingBraces += "}";
        }
        out += " if (" + $nextValid + ") { " + $valid + " = " + $prevValid + " = true; " + $passingSchemas + " = " + $i2 + "; }";
      }
    }
    it2.compositeRule = $it.compositeRule = $wasComposite;
    out += "" + $closingBraces + "if (!" + $valid + ") {   var err =   ";
    if (it2.createErrors !== false) {
      out += " { keyword: 'oneOf' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { passingSchemas: " + $passingSchemas + " } ";
      if (it2.opts.messages !== false) {
        out += " , message: 'should match exactly one schema in oneOf' ";
      }
      if (it2.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    if (!it2.compositeRule && $breakOnError) {
      if (it2.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 (it2.opts.allErrors) {
      out += " } ";
    }
    return out;
  };
  return oneOf$2;
}
var pattern$2;
var hasRequiredPattern$2;
function requirePattern$2() {
  if (hasRequiredPattern$2) return pattern$2;
  hasRequiredPattern$2 = 1;
  pattern$2 = function generate_pattern(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $isData = it2.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it2.util.getData($schema2.$data, $dataLvl, it2.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    var $regExpCode = it2.opts.regExp ? "regExp" : "new RegExp";
    if ($isData) {
      out += " var " + $valid + " = true; try { " + $valid + " = " + $regExpCode + "(" + $schemaValue + ").test(" + $data + "); } catch(e) { " + $valid + " = false; } if ( ";
      if ($isData) {
        out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'string') || ";
      }
      out += " !" + $valid + ") {";
    } else {
      var $regexp = it2.usePattern($schema2);
      out += " if ( ";
      if ($isData) {
        out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'string') || ";
      }
      out += " !" + $regexp + ".test(" + $data + ") ) {";
    }
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it2.createErrors !== false) {
      out += " { keyword: 'pattern' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { pattern:  ";
      if ($isData) {
        out += "" + $schemaValue;
      } else {
        out += "" + it2.util.toQuotedString($schema2);
      }
      out += "  } ";
      if (it2.opts.messages !== false) {
        out += ` , message: 'should match pattern "`;
        if ($isData) {
          out += "' + " + $schemaValue + " + '";
        } else {
          out += "" + it2.util.escapeQuotes($schema2);
        }
        out += `"' `;
      }
      if (it2.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + it2.util.toQuotedString($schema2);
        }
        out += "         , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it2.compositeRule && $breakOnError) {
      if (it2.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$2;
}
var properties$8;
var hasRequiredProperties$2;
function requireProperties$2() {
  if (hasRequiredProperties$2) return properties$8;
  hasRequiredProperties$2 = 1;
  properties$8 = function generate_properties(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $errs = "errs__" + $lvl;
    var $it = it2.util.copy(it2);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $key = "key" + $lvl, $idx = "idx" + $lvl, $dataNxt = $it.dataLevel = it2.dataLevel + 1, $nextData = "data" + $dataNxt, $dataProperties = "dataProperties" + $lvl;
    var $schemaKeys = Object.keys($schema2 || {}).filter(notProto), $pProperties = it2.schema.patternProperties || {}, $pPropertyKeys = Object.keys($pProperties).filter(notProto), $aProperties = it2.schema.additionalProperties, $someProperties = $schemaKeys.length || $pPropertyKeys.length, $noAdditional = $aProperties === false, $additionalIsSchema = typeof $aProperties == "object" && Object.keys($aProperties).length, $removeAdditional = it2.opts.removeAdditional, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, $ownProperties = it2.opts.ownProperties, $currentBaseId = it2.baseId;
    var $required = it2.schema.required;
    if ($required && !(it2.opts.$data && $required.$data) && $required.length < it2.opts.loopRequired) {
      var $requiredHash = it2.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 + " == " + it2.util.toQuotedString($propertyKey) + " ";
              }
            }
          }
        }
        if ($pPropertyKeys.length) {
          var arr2 = $pPropertyKeys;
          if (arr2) {
            var $pProperty, $i2 = -1, l2 = arr2.length - 1;
            while ($i2 < l2) {
              $pProperty = arr2[$i2 += 1];
              out += " || " + it2.usePattern($pProperty) + ".test(" + $key + ") ";
            }
          }
        }
        out += " ); if (isAdditional" + $lvl + ") { ";
      }
      if ($removeAdditional == "all") {
        out += " delete " + $data + "[" + $key + "]; ";
      } else {
        var $currentErrorPath = it2.errorPath;
        var $additionalProperty = "' + " + $key + " + '";
        if (it2.opts._errorDataPathProperty) {
          it2.errorPath = it2.util.getPathExpr(it2.errorPath, $key, it2.opts.jsonPointers);
        }
        if ($noAdditional) {
          if ($removeAdditional) {
            out += " delete " + $data + "[" + $key + "]; ";
          } else {
            out += " " + $nextValid + " = false; ";
            var $currErrSchemaPath = $errSchemaPath;
            $errSchemaPath = it2.errSchemaPath + "/additionalProperties";
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = "";
            if (it2.createErrors !== false) {
              out += " { keyword: 'additionalProperties' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { additionalProperty: '" + $additionalProperty + "' } ";
              if (it2.opts.messages !== false) {
                out += " , message: '";
                if (it2.opts._errorDataPathProperty) {
                  out += "is an invalid additional property";
                } else {
                  out += "should NOT have additional properties";
                }
                out += "' ";
              }
              if (it2.opts.verbose) {
                out += " , schema: false , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            var __err = out;
            out = $$outStack.pop();
            if (!it2.compositeRule && $breakOnError) {
              if (it2.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 = it2.compositeRule;
            it2.compositeRule = $it.compositeRule = true;
            $it.schema = $aProperties;
            $it.schemaPath = it2.schemaPath + ".additionalProperties";
            $it.errSchemaPath = it2.errSchemaPath + "/additionalProperties";
            $it.errorPath = it2.opts._errorDataPathProperty ? it2.errorPath : it2.util.getPathExpr(it2.errorPath, $key, it2.opts.jsonPointers);
            var $passData = $data + "[" + $key + "]";
            $it.dataPathArr[$dataNxt] = $key;
            var $code = it2.validate($it);
            $it.baseId = $currentBaseId;
            if (it2.util.varOccurences($code, $nextData) < 2) {
              out += " " + it2.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 + "]; }  ";
            it2.compositeRule = $it.compositeRule = $wasComposite;
          } else {
            $it.schema = $aProperties;
            $it.schemaPath = it2.schemaPath + ".additionalProperties";
            $it.errSchemaPath = it2.errSchemaPath + "/additionalProperties";
            $it.errorPath = it2.opts._errorDataPathProperty ? it2.errorPath : it2.util.getPathExpr(it2.errorPath, $key, it2.opts.jsonPointers);
            var $passData = $data + "[" + $key + "]";
            $it.dataPathArr[$dataNxt] = $key;
            var $code = it2.validate($it);
            $it.baseId = $currentBaseId;
            if (it2.util.varOccurences($code, $nextData) < 2) {
              out += " " + it2.util.varReplace($code, $nextData, $passData) + " ";
            } else {
              out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
            }
            if ($breakOnError) {
              out += " if (!" + $nextValid + ") break; ";
            }
          }
        }
        it2.errorPath = $currentErrorPath;
      }
      if ($someProperties) {
        out += " } ";
      }
      out += " }  ";
      if ($breakOnError) {
        out += " if (" + $nextValid + ") { ";
        $closingBraces += "}";
      }
    }
    var $useDefaults = it2.opts.useDefaults && !it2.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 (it2.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it2.util.schemaHasRules($sch, it2.RULES.all)) {
            var $prop = it2.util.getProperty($propertyKey), $passData = $data + $prop, $hasDefault = $useDefaults && $sch.default !== void 0;
            $it.schema = $sch;
            $it.schemaPath = $schemaPath + $prop;
            $it.errSchemaPath = $errSchemaPath + "/" + it2.util.escapeFragment($propertyKey);
            $it.errorPath = it2.util.getPath(it2.errorPath, $propertyKey, it2.opts.jsonPointers);
            $it.dataPathArr[$dataNxt] = it2.util.toQuotedString($propertyKey);
            var $code = it2.validate($it);
            $it.baseId = $currentBaseId;
            if (it2.util.varOccurences($code, $nextData) < 2) {
              $code = it2.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 + ", '" + it2.util.escapeQuotes($propertyKey) + "') ";
                }
                out += ") { " + $nextValid + " = false; ";
                var $currentErrorPath = it2.errorPath, $currErrSchemaPath = $errSchemaPath, $missingProperty = it2.util.escapeQuotes($propertyKey);
                if (it2.opts._errorDataPathProperty) {
                  it2.errorPath = it2.util.getPath($currentErrorPath, $propertyKey, it2.opts.jsonPointers);
                }
                $errSchemaPath = it2.errSchemaPath + "/required";
                var $$outStack = $$outStack || [];
                $$outStack.push(out);
                out = "";
                if (it2.createErrors !== false) {
                  out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
                  if (it2.opts.messages !== false) {
                    out += " , message: '";
                    if (it2.opts._errorDataPathProperty) {
                      out += "is a required property";
                    } else {
                      out += "should have required property \\'" + $missingProperty + "\\'";
                    }
                    out += "' ";
                  }
                  if (it2.opts.verbose) {
                    out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
                  }
                  out += " } ";
                } else {
                  out += " {} ";
                }
                var __err = out;
                out = $$outStack.pop();
                if (!it2.compositeRule && $breakOnError) {
                  if (it2.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;
                it2.errorPath = $currentErrorPath;
                out += " } else { ";
              } else {
                if ($breakOnError) {
                  out += " if ( " + $useData + " === undefined ";
                  if ($ownProperties) {
                    out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($propertyKey) + "') ";
                  }
                  out += ") { " + $nextValid + " = true; } else { ";
                } else {
                  out += " if (" + $useData + " !== undefined ";
                  if ($ownProperties) {
                    out += " &&   Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.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 (it2.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it2.util.schemaHasRules($sch, it2.RULES.all)) {
            $it.schema = $sch;
            $it.schemaPath = it2.schemaPath + ".patternProperties" + it2.util.getProperty($pProperty);
            $it.errSchemaPath = it2.errSchemaPath + "/patternProperties/" + it2.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 (" + it2.usePattern($pProperty) + ".test(" + $key + ")) { ";
            $it.errorPath = it2.util.getPathExpr(it2.errorPath, $key, it2.opts.jsonPointers);
            var $passData = $data + "[" + $key + "]";
            $it.dataPathArr[$dataNxt] = $key;
            var $code = it2.validate($it);
            $it.baseId = $currentBaseId;
            if (it2.util.varOccurences($code, $nextData) < 2) {
              out += " " + it2.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$8;
}
var propertyNames$2;
var hasRequiredPropertyNames$2;
function requirePropertyNames$2() {
  if (hasRequiredPropertyNames$2) return propertyNames$2;
  hasRequiredPropertyNames$2 = 1;
  propertyNames$2 = function generate_propertyNames(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $errs = "errs__" + $lvl;
    var $it = it2.util.copy(it2);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    out += "var " + $errs + " = errors;";
    if (it2.opts.strictKeywords ? typeof $schema2 == "object" && Object.keys($schema2).length > 0 || $schema2 === false : it2.util.schemaHasRules($schema2, it2.RULES.all)) {
      $it.schema = $schema2;
      $it.schemaPath = $schemaPath;
      $it.errSchemaPath = $errSchemaPath;
      var $key = "key" + $lvl, $idx = "idx" + $lvl, $i2 = "i" + $lvl, $invalidName = "' + " + $key + " + '", $dataNxt = $it.dataLevel = it2.dataLevel + 1, $nextData = "data" + $dataNxt, $dataProperties = "dataProperties" + $lvl, $ownProperties = it2.opts.ownProperties, $currentBaseId = it2.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 = it2.compositeRule;
      it2.compositeRule = $it.compositeRule = true;
      var $code = it2.validate($it);
      $it.baseId = $currentBaseId;
      if (it2.util.varOccurences($code, $nextData) < 2) {
        out += " " + it2.util.varReplace($code, $nextData, $passData) + " ";
      } else {
        out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
      }
      it2.compositeRule = $it.compositeRule = $wasComposite;
      out += " if (!" + $nextValid + ") { for (var " + $i2 + "=startErrs" + $lvl + "; " + $i2 + "<errors; " + $i2 + "++) { vErrors[" + $i2 + "].propertyName = " + $key + "; }   var err =   ";
      if (it2.createErrors !== false) {
        out += " { keyword: 'propertyNames' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { propertyName: '" + $invalidName + "' } ";
        if (it2.opts.messages !== false) {
          out += " , message: 'property name \\'" + $invalidName + "\\' is invalid' ";
        }
        if (it2.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      if (!it2.compositeRule && $breakOnError) {
        if (it2.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$2;
}
var required$5;
var hasRequiredRequired$2;
function requireRequired$2() {
  if (hasRequiredRequired$2) return required$5;
  hasRequiredRequired$2 = 1;
  required$5 = function generate_required(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $isData = it2.opts.$data && $schema2 && $schema2.$data;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it2.util.getData($schema2.$data, $dataLvl, it2.dataPathArr) + "; ";
    }
    var $vSchema = "schema" + $lvl;
    if (!$isData) {
      if ($schema2.length < it2.opts.loopRequired && it2.schema.properties && Object.keys(it2.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 = it2.schema.properties[$property];
            if (!($propertySch && (it2.opts.strictKeywords ? typeof $propertySch == "object" && Object.keys($propertySch).length > 0 || $propertySch === false : it2.util.schemaHasRules($propertySch, it2.RULES.all)))) {
              $required[$required.length] = $property;
            }
          }
        }
      } else {
        var $required = $schema2;
      }
    }
    if ($isData || $required.length) {
      var $currentErrorPath = it2.errorPath, $loopRequired = $isData || $required.length >= it2.opts.loopRequired, $ownProperties = it2.opts.ownProperties;
      if ($breakOnError) {
        out += " var missing" + $lvl + "; ";
        if ($loopRequired) {
          if (!$isData) {
            out += " var " + $vSchema + " = validate.schema" + $schemaPath + "; ";
          }
          var $i2 = "i" + $lvl, $propertyPath = "schema" + $lvl + "[" + $i2 + "]", $missingProperty = "' + " + $propertyPath + " + '";
          if (it2.opts._errorDataPathProperty) {
            it2.errorPath = it2.util.getPathExpr($currentErrorPath, $propertyPath, it2.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 " + $i2 + " = 0; " + $i2 + " < " + $vSchema + ".length; " + $i2 + "++) { " + $valid + " = " + $data + "[" + $vSchema + "[" + $i2 + "]] !== undefined ";
          if ($ownProperties) {
            out += " &&   Object.prototype.hasOwnProperty.call(" + $data + ", " + $vSchema + "[" + $i2 + "]) ";
          }
          out += "; if (!" + $valid + ") break; } ";
          if ($isData) {
            out += "  }  ";
          }
          out += "  if (!" + $valid + ") {   ";
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it2.createErrors !== false) {
            out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
            if (it2.opts.messages !== false) {
              out += " , message: '";
              if (it2.opts._errorDataPathProperty) {
                out += "is a required property";
              } else {
                out += "should have required property \\'" + $missingProperty + "\\'";
              }
              out += "' ";
            }
            if (it2.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it2.compositeRule && $breakOnError) {
            if (it2.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, $i2 = -1, l2 = arr2.length - 1;
            while ($i2 < l2) {
              $propertyKey = arr2[$i2 += 1];
              if ($i2) {
                out += " || ";
              }
              var $prop = it2.util.getProperty($propertyKey), $useData = $data + $prop;
              out += " ( ( " + $useData + " === undefined ";
              if ($ownProperties) {
                out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($propertyKey) + "') ";
              }
              out += ") && (missing" + $lvl + " = " + it2.util.toQuotedString(it2.opts.jsonPointers ? $propertyKey : $prop) + ") ) ";
            }
          }
          out += ") {  ";
          var $propertyPath = "missing" + $lvl, $missingProperty = "' + " + $propertyPath + " + '";
          if (it2.opts._errorDataPathProperty) {
            it2.errorPath = it2.opts.jsonPointers ? it2.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + " + " + $propertyPath;
          }
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it2.createErrors !== false) {
            out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
            if (it2.opts.messages !== false) {
              out += " , message: '";
              if (it2.opts._errorDataPathProperty) {
                out += "is a required property";
              } else {
                out += "should have required property \\'" + $missingProperty + "\\'";
              }
              out += "' ";
            }
            if (it2.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it2.compositeRule && $breakOnError) {
            if (it2.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 $i2 = "i" + $lvl, $propertyPath = "schema" + $lvl + "[" + $i2 + "]", $missingProperty = "' + " + $propertyPath + " + '";
          if (it2.opts._errorDataPathProperty) {
            it2.errorPath = it2.util.getPathExpr($currentErrorPath, $propertyPath, it2.opts.jsonPointers);
          }
          if ($isData) {
            out += " if (" + $vSchema + " && !Array.isArray(" + $vSchema + ")) {  var err =   ";
            if (it2.createErrors !== false) {
              out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
              if (it2.opts.messages !== false) {
                out += " , message: '";
                if (it2.opts._errorDataPathProperty) {
                  out += "is a required property";
                } else {
                  out += "should have required property \\'" + $missingProperty + "\\'";
                }
                out += "' ";
              }
              if (it2.opts.verbose) {
                out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (" + $vSchema + " !== undefined) { ";
          }
          out += " for (var " + $i2 + " = 0; " + $i2 + " < " + $vSchema + ".length; " + $i2 + "++) { if (" + $data + "[" + $vSchema + "[" + $i2 + "]] === undefined ";
          if ($ownProperties) {
            out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", " + $vSchema + "[" + $i2 + "]) ";
          }
          out += ") {  var err =   ";
          if (it2.createErrors !== false) {
            out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
            if (it2.opts.messages !== false) {
              out += " , message: '";
              if (it2.opts._errorDataPathProperty) {
                out += "is a required property";
              } else {
                out += "should have required property \\'" + $missingProperty + "\\'";
              }
              out += "' ";
            }
            if (it2.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.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 = it2.util.getProperty($propertyKey), $missingProperty = it2.util.escapeQuotes($propertyKey), $useData = $data + $prop;
              if (it2.opts._errorDataPathProperty) {
                it2.errorPath = it2.util.getPath($currentErrorPath, $propertyKey, it2.opts.jsonPointers);
              }
              out += " if ( " + $useData + " === undefined ";
              if ($ownProperties) {
                out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($propertyKey) + "') ";
              }
              out += ") {  var err =   ";
              if (it2.createErrors !== false) {
                out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
                if (it2.opts.messages !== false) {
                  out += " , message: '";
                  if (it2.opts._errorDataPathProperty) {
                    out += "is a required property";
                  } else {
                    out += "should have required property \\'" + $missingProperty + "\\'";
                  }
                  out += "' ";
                }
                if (it2.opts.verbose) {
                  out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
                }
                out += " } ";
              } else {
                out += " {} ";
              }
              out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ";
            }
          }
        }
      }
      it2.errorPath = $currentErrorPath;
    } else if ($breakOnError) {
      out += " if (true) {";
    }
    return out;
  };
  return required$5;
}
var uniqueItems$2;
var hasRequiredUniqueItems$2;
function requireUniqueItems$2() {
  if (hasRequiredUniqueItems$2) return uniqueItems$2;
  hasRequiredUniqueItems$2 = 1;
  uniqueItems$2 = function generate_uniqueItems(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $isData = it2.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it2.util.getData($schema2.$data, $dataLvl, it2.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    if (($schema2 || $isData) && it2.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 = it2.schema.items && it2.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 (" + it2.util[$method]($itemType, "item", it2.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 (it2.createErrors !== false) {
        out += " { keyword: 'uniqueItems' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { i: i, j: j } ";
        if (it2.opts.messages !== false) {
          out += " , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' ";
        }
        if (it2.opts.verbose) {
          out += " , schema:  ";
          if ($isData) {
            out += "validate.schema" + $schemaPath;
          } else {
            out += "" + $schema2;
          }
          out += "         , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it2.compositeRule && $breakOnError) {
        if (it2.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$2;
}
var dotjs;
var hasRequiredDotjs;
function requireDotjs() {
  if (hasRequiredDotjs) return dotjs;
  hasRequiredDotjs = 1;
  dotjs = {
    "$ref": requireRef$2(),
    allOf: requireAllOf$2(),
    anyOf: requireAnyOf$2(),
    "$comment": requireComment(),
    const: require_const$2(),
    contains: requireContains$2(),
    dependencies: requireDependencies$2(),
    "enum": require_enum$2(),
    format: requireFormat$4(),
    "if": require_if$2(),
    items: requireItems$2(),
    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$2(),
    not: requireNot$2(),
    oneOf: requireOneOf$2(),
    pattern: requirePattern$2(),
    properties: requireProperties$2(),
    propertyNames: requirePropertyNames$2(),
    required: requireRequired$2(),
    uniqueItems: requireUniqueItems$2(),
    validate: requireValidate$2()
  };
  return dotjs;
}
var rules$2;
var hasRequiredRules$2;
function requireRules$2() {
  if (hasRequiredRules$2) return rules$2;
  hasRequiredRules$2 = 1;
  var ruleModules = requireDotjs(), toHash = requireUtil$2().toHash;
  rules$2 = 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 key = Object.keys(keyword2)[0];
          implKeywords = keyword2[key];
          keyword2 = key;
          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$2;
}
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 key = KEYWORDS[j];
        var schema = keywords[key];
        if (schema) {
          keywords[key] = {
            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 (e2) {
        if (e2 instanceof MissingRefError) return loadMissingSchema(e2);
        throw e2;
      }
      function loadMissingSchema(e2) {
        var ref2 = e2.missingSchema;
        if (added(ref2)) throw new Error("Schema " + ref2 + " is loaded but " + e2.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;
var hasRequiredCustom;
function requireCustom() {
  if (hasRequiredCustom) return custom;
  hasRequiredCustom = 1;
  custom = function generate_custom(it2, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it2.level;
    var $dataLvl = it2.dataLevel;
    var $schema2 = it2.schema[$keyword];
    var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
    var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it2.opts.allErrors;
    var $errorKeyword;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $errs = "errs__" + $lvl;
    var $isData = it2.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it2.util.getData($schema2.$data, $dataLvl, it2.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 = it2.useCustomRule($rule, $schema2, it2.schema, it2);
      if (!$ruleValidate) return;
      $schemaValue = "validate.schema" + $schemaPath;
      $validateCode = $ruleValidate.code;
      $compile = $rDef.compile;
      $inline = $rDef.inline;
      $macro = $rDef.macro;
    }
    var $ruleErrs = $validateCode + ".errors", $i2 = "i" + $lvl, $ruleErr = "ruleErr" + $lvl, $asyncKeyword = $rDef.async;
    if ($asyncKeyword && !it2.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 = it2.util.copy(it2);
      var $closingBraces = "";
      $it.level++;
      var $nextValid = "valid" + $it.level;
      $it.schema = $ruleValidate.validate;
      $it.schemaPath = "";
      var $wasComposite = it2.compositeRule;
      it2.compositeRule = $it.compositeRule = true;
      var $code = it2.validate($it).replace(/validate\.schema/g, $validateCode);
      it2.compositeRule = $it.compositeRule = $wasComposite;
      out += " " + $code;
    } else {
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      out += "  " + $validateCode + ".call( ";
      if (it2.opts.passContext) {
        out += "this";
      } else {
        out += "self";
      }
      if ($compile || $rDef.schema === false) {
        out += " , " + $data + " ";
      } else {
        out += " , " + $schemaValue + " , " + $data + " , validate.schema" + it2.schemaPath + " ";
      }
      out += " , (dataPath || '')";
      if (it2.errorPath != '""') {
        out += " + " + it2.errorPath;
      }
      var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it2.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 (it2.createErrors !== false) {
        out += " { keyword: '" + ($errorKeyword || "custom") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { keyword: '" + $rule.keyword + "' } ";
        if (it2.opts.messages !== false) {
          out += ` , message: 'should pass "` + $rule.keyword + `" keyword validation' `;
        }
        if (it2.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it2.compositeRule && $breakOnError) {
        if (it2.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 " + $i2 + "=" + $errs + "; " + $i2 + "<errors; " + $i2 + "++) { var " + $ruleErr + " = vErrors[" + $i2 + "]; if (" + $ruleErr + ".dataPath === undefined) " + $ruleErr + ".dataPath = (dataPath || '') + " + it2.errorPath + "; if (" + $ruleErr + ".schemaPath === undefined) { " + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; } ';
            if (it2.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 " + $i2 + "=" + $errs + "; " + $i2 + "<errors; " + $i2 + "++) { var " + $ruleErr + " = vErrors[" + $i2 + "]; if (" + $ruleErr + ".dataPath === undefined) " + $ruleErr + ".dataPath = (dataPath || '') + " + it2.errorPath + "; if (" + $ruleErr + ".schemaPath === undefined) { " + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; } ';
            if (it2.opts.verbose) {
              out += " " + $ruleErr + ".schema = " + $schemaValue + "; " + $ruleErr + ".data = " + $data + "; ";
            }
            out += " } } ";
          }
        }
      } else if ($macro) {
        out += "   var err =   ";
        if (it2.createErrors !== false) {
          out += " { keyword: '" + ($errorKeyword || "custom") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { keyword: '" + $rule.keyword + "' } ";
          if (it2.opts.messages !== false) {
            out += ` , message: 'should pass "` + $rule.keyword + `" keyword validation' `;
          }
          if (it2.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        if (!it2.compositeRule && $breakOnError) {
          if (it2.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 " + $i2 + "=" + $errs + "; " + $i2 + "<errors; " + $i2 + "++) { var " + $ruleErr + " = vErrors[" + $i2 + "]; if (" + $ruleErr + ".dataPath === undefined) " + $ruleErr + ".dataPath = (dataPath || '') + " + it2.errorPath + ";  " + $ruleErr + '.schemaPath = "' + $errSchemaPath + '";  ';
          if (it2.opts.verbose) {
            out += " " + $ruleErr + ".schema = " + $schemaValue + "; " + $ruleErr + ".data = " + $data + "; ";
          }
          out += " } } else { " + def_customError + " } ";
        }
      }
      out += " } ";
      if ($breakOnError) {
        out += " else { ";
      }
    }
    return out;
  };
  return custom;
}
const $schema$3 = "http://json-schema.org/draft-07/schema#";
const $id$5 = "http://json-schema.org/draft-07/schema#";
const title$2 = "Core schema meta-schema";
const definitions$2 = { "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$5 = ["object", "boolean"];
const properties$7 = { "$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$3,
  $id: $id$5,
  title: title$2,
  definitions: definitions$2,
  type: type$5,
  properties: properties$7,
  "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$2;
var hasRequiredKeyword$2;
function requireKeyword$2() {
  if (hasRequiredKeyword$2) return keyword$2;
  hasRequiredKeyword$2 = 1;
  var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
  var customRuleCode = requireCustom();
  var definitionSchema = requireDefinition_schema();
  keyword$2 = {
    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 dataType2 = definition.type;
      if (Array.isArray(dataType2)) {
        for (var i2 = 0; i2 < dataType2.length; i2++)
          _addRule(keyword2, dataType2[i2], definition);
      } else {
        _addRule(keyword2, dataType2, 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, dataType3, definition2) {
      var ruleGroup;
      for (var i3 = 0; i3 < RULES.length; i3++) {
        var rg = RULES[i3];
        if (rg.type == dataType3) {
          ruleGroup = rg;
          break;
        }
      }
      if (!ruleGroup) {
        ruleGroup = { type: dataType3, 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$2;
}
const $schema$2 = "http://json-schema.org/draft-07/schema#";
const $id$4 = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#";
const description$2 = "Meta-schema for $data reference (JSON Schema extension proposal)";
const type$4 = "object";
const required$4 = ["$data"];
const properties$6 = { "$data": { "type": "string", "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] } };
const additionalProperties$4 = false;
const require$$12 = {
  $schema: $schema$2,
  $id: $id$4,
  description: description$2,
  type: type$4,
  required: required$4,
  properties: properties$6,
  additionalProperties: additionalProperties$4
};
var ajv$3;
var hasRequiredAjv$2;
function requireAjv$2() {
  if (hasRequiredAjv$2) return ajv$3;
  hasRequiredAjv$2 = 1;
  var compileSchema = requireCompile$2(), resolve2 = requireResolve$2(), Cache = requireCache(), SchemaObject = requireSchema_obj(), stableStringify = requireFastJsonStableStringify(), formats2 = requireFormats$1(), rules2 = requireRules$2(), $dataMetaSchema = requireData(), util2 = requireUtil$2();
  ajv$3 = Ajv2;
  Ajv2.prototype.validate = validate2;
  Ajv2.prototype.compile = compile2;
  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$2();
  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 = formats2(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 compile2(schema, _meta) {
    var schemaObj = this._addSchema(schema, void 0, _meta);
    return schemaObj.validate || this._compile(schemaObj);
  }
  function addSchema(schema, key, _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 id2 = this._getId(schema);
    if (id2 !== void 0 && typeof id2 != "string")
      throw new Error("schema id must be string");
    key = resolve2.normalizeId(key || id2);
    checkUnique(this, key);
    this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
    return this;
  }
  function addMetaSchema(schema, key, skipValidation) {
    this.addSchema(schema, key, 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 serialize = this._opts.serialize;
        var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
        this._cache.del(cacheKey);
        var id2 = this._getId(schemaKeyRef);
        if (id2) {
          id2 = resolve2.normalizeId(id2);
          delete this._schemas[id2];
          delete this._refs[id2];
        }
    }
    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 serialize = this._opts.serialize;
    var cacheKey = serialize ? serialize(schema) : schema;
    var cached2 = this._cache.get(cacheKey);
    if (cached2) return cached2;
    shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
    var id2 = resolve2.normalizeId(this._getId(schema));
    if (id2 && shouldAddSchema) checkUnique(this, id2);
    var willValidate = this._opts.validateSchema !== false && !skipValidation;
    var recursiveMeta;
    if (willValidate && !(recursiveMeta = id2 && id2 == resolve2.normalizeId(schema.$schema)))
      this.validateSchema(schema, true);
    var localRefs = resolve2.ids.call(this, schema);
    var schemaObj = new SchemaObject({
      id: id2,
      schema,
      localRefs,
      cacheKey,
      meta
    });
    if (id2[0] != "#" && shouldAddSchema) this._refs[id2] = 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 (e2) {
      delete schemaObj.validate;
      throw e2;
    } 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(errors2, options) {
    errors2 = errors2 || this.errors;
    if (!errors2) return "No errors";
    options = options || {};
    var separator = options.separator === void 0 ? ", " : options.separator;
    var dataVar = options.dataVar === void 0 ? "data" : options.dataVar;
    var text = "";
    for (var i2 = 0; i2 < errors2.length; i2++) {
      var e2 = errors2[i2];
      if (e2) text += dataVar + e2.dataPath + " " + e2.message + separator;
    }
    return text.slice(0, -separator.length);
  }
  function addFormat(name2, format2) {
    if (typeof format2 == "string") format2 = new RegExp(format2);
    this._formats[name2] = 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 key in optsSchemas) self2.addSchema(optsSchemas[key], key);
  }
  function addInitialFormats(self2) {
    for (var name2 in self2._opts.formats) {
      var format2 = self2._opts.formats[name2];
      self2.addFormat(name2, format2);
    }
  }
  function addInitialKeywords(self2) {
    for (var name2 in self2._opts.keywords) {
      var keyword2 = self2._opts.keywords[name2];
      self2.addKeyword(name2, keyword2);
    }
  }
  function checkUnique(self2, id2) {
    if (self2._schemas[id2] || self2._refs[id2])
      throw new Error('schema with key or id "' + id2 + '" 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: noop3, warn: noop3, error: noop3 };
    } 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 noop3() {
  }
  return ajv$3;
}
var ajvExports$1 = requireAjv$2();
const Ajv$1 = /* @__PURE__ */ getDefaultExportFromCjs(ajvExports$1);
const ajv$2 = new Ajv$1();
const toolOutputValidators = /* @__PURE__ */ new Map();
function cacheToolOutputSchemas(tools) {
  toolOutputValidators.clear();
  for (const tool of tools) {
    if (tool.outputSchema) {
      try {
        const validator = ajv$2.compile(tool.outputSchema);
        toolOutputValidators.set(tool.name, validator);
      } catch (error) {
        console.warn(
          `Failed to compile output schema for tool ${tool.name}:`,
          error
        );
      }
    }
  }
}
function getToolOutputValidator(toolName) {
  return toolOutputValidators.get(toolName);
}
function validateToolOutput(toolName, structuredContent) {
  const validator = getToolOutputValidator(toolName);
  if (!validator) {
    return { isValid: true };
  }
  const isValid2 = validator(structuredContent);
  if (!isValid2) {
    return {
      isValid: false,
      error: ajv$2.errorsText(validator.errors)
    };
  }
  return { isValid: true };
}
function hasOutputSchema(toolName) {
  return toolOutputValidators.has(toolName);
}
function generateDefaultValue(schema, propertyName, parentSchema) {
  if ("default" in schema && schema.default !== void 0) {
    return schema.default;
  }
  const isRequired = propertyName && parentSchema ? isPropertyRequired(propertyName, parentSchema) : false;
  const isRootSchema = propertyName === void 0 && parentSchema === void 0;
  switch (schema.type) {
    case "string":
      return isRequired ? "" : void 0;
    case "number":
    case "integer":
      return isRequired ? 0 : void 0;
    case "boolean":
      return isRequired ? false : void 0;
    case "array":
      return isRequired ? [] : void 0;
    case "object": {
      if (!schema.properties) {
        return isRequired || isRootSchema ? {} : void 0;
      }
      const obj = {};
      Object.entries(schema.properties).forEach(([key, prop]) => {
        const hasExplicitDefault = "default" in prop && prop.default !== void 0;
        if (isPropertyRequired(key, schema) || hasExplicitDefault) {
          const value = generateDefaultValue(prop, key, schema);
          if (value !== void 0) {
            obj[key] = value;
          }
        }
      });
      if (Object.keys(obj).length === 0) {
        return isRequired || isRootSchema ? {} : void 0;
      }
      return obj;
    }
    case "null":
      return null;
    default:
      return void 0;
  }
}
function isPropertyRequired(propertyName, schema) {
  return schema.required?.includes(propertyName) ?? false;
}
function resolveRef(schema, rootSchema, visitedRefs = /* @__PURE__ */ new Set()) {
  if (!schema) return schema;
  if (!("$ref" in schema) || !schema.$ref) {
    if (schema.anyOf && Array.isArray(schema.anyOf)) {
      const resolvedAnyOf = schema.anyOf.map((item) => {
        if (typeof item === "object" && item !== null) {
          return resolveRef(item, rootSchema, visitedRefs);
        }
        return item;
      });
      return {
        ...schema,
        anyOf: resolvedAnyOf
      };
    }
    return schema;
  }
  const ref2 = schema.$ref;
  if (ref2.startsWith("#/")) {
    if (visitedRefs.has(ref2)) {
      console.warn(`Circular reference detected: ${ref2}`);
      return schema;
    }
    visitedRefs.add(ref2);
    const path = ref2.substring(2).split("/");
    let current = rootSchema;
    for (const segment of path) {
      if (current && typeof current === "object" && current !== null && segment in current) {
        current = current[segment];
      } else {
        visitedRefs.delete(ref2);
        console.warn(`Could not resolve $ref: ${ref2}`);
        return schema;
      }
    }
    const resolved = current;
    return resolveRef(resolved, rootSchema, visitedRefs);
  }
  console.warn(`Unsupported $ref format: ${ref2}`);
  return schema;
}
function normalizeUnionType(schema) {
  if (schema.anyOf && schema.anyOf.length === 2 && schema.anyOf.some((t2) => t2.type === "null")) {
    const nonNullItem = schema.anyOf.find((t2) => {
      const item = t2;
      return item?.type !== "null";
    });
    if (nonNullItem?.type || nonNullItem?.enum) {
      return {
        ...schema,
        ...nonNullItem,
        type: nonNullItem?.type || (nonNullItem?.enum ? "string" : void 0),
        nullable: true,
        anyOf: void 0
      };
    }
  }
  if (Array.isArray(schema.type) && schema.type.length === 2 && schema.type.includes("string") && schema.type.includes("null")) {
    return { ...schema, type: "string", nullable: true };
  }
  if (Array.isArray(schema.type) && schema.type.length === 2 && schema.type.includes("boolean") && schema.type.includes("null")) {
    return { ...schema, type: "boolean", nullable: true };
  }
  if (Array.isArray(schema.type) && schema.type.length === 2 && schema.type.includes("number") && schema.type.includes("null")) {
    return { ...schema, type: "number", nullable: true };
  }
  if (Array.isArray(schema.type) && schema.type.length === 2 && schema.type.includes("integer") && schema.type.includes("null")) {
    return { ...schema, type: "integer", nullable: true };
  }
  return schema;
}
function resolveRefsInMessage(message) {
  if (!isJSONRPCRequest(message) || !message.params?.requestedSchema) {
    return message;
  }
  const requestedSchema = message.params.requestedSchema;
  if (!requestedSchema?.properties) {
    return message;
  }
  const resolvedMessage = {
    ...message,
    params: {
      ...message.params,
      requestedSchema: {
        ...requestedSchema,
        properties: Object.fromEntries(
          Object.entries(requestedSchema.properties).map(
            ([key, propSchema]) => {
              const resolved = resolveRef(propSchema, requestedSchema);
              const normalized = normalizeUnionType(resolved);
              return [key, normalized];
            }
          )
        )
      }
    }
  };
  return resolvedMessage;
}
function cleanParams(params, schema) {
  const cleaned = {};
  const required2 = schema.required || [];
  const properties2 = schema.properties || {};
  for (const [key, value] of Object.entries(params)) {
    const isFieldRequired = required2.includes(key);
    const fieldSchema = properties2[key];
    const hasDefault = fieldSchema && "default" in fieldSchema;
    const defaultValue = hasDefault ? fieldSchema.default : void 0;
    if (isFieldRequired) {
      cleaned[key] = value;
    } else if (hasDefault && value === defaultValue) {
      cleaned[key] = value;
    } else {
      if (value !== void 0 && value !== "" && value !== null) {
        cleaned[key] = value;
      }
    }
  }
  return cleaned;
}
var ajv$1 = { exports: {} };
var core$3 = {};
var validate$1 = {};
var boolSchema$1 = {};
var errors$1 = {};
var codegen$1 = {};
var code$3 = {};
var hasRequiredCode$3;
function requireCode$3() {
  if (hasRequiredCode$3) return code$3;
  hasRequiredCode$3 = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
    class _CodeOrName {
    }
    exports._CodeOrName = _CodeOrName;
    exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
    class Name extends _CodeOrName {
      constructor(s2) {
        super();
        if (!exports.IDENTIFIER.test(s2))
          throw new Error("CodeGen: name must be a valid identifier");
        this.str = s2;
      }
      toString() {
        return this.str;
      }
      emptyStr() {
        return false;
      }
      get names() {
        return { [this.str]: 1 };
      }
    }
    exports.Name = Name;
    class _Code extends _CodeOrName {
      constructor(code2) {
        super();
        this._items = typeof code2 === "string" ? [code2] : code2;
      }
      toString() {
        return this.str;
      }
      emptyStr() {
        if (this._items.length > 1)
          return false;
        const item = this._items[0];
        return item === "" || item === '""';
      }
      get str() {
        var _a2;
        return (_a2 = this._str) !== null && _a2 !== void 0 ? _a2 : this._str = this._items.reduce((s2, c) => `${s2}${c}`, "");
      }
      get names() {
        var _a2;
        return (_a2 = this._names) !== null && _a2 !== void 0 ? _a2 : this._names = this._items.reduce((names2, c) => {
          if (c instanceof Name)
            names2[c.str] = (names2[c.str] || 0) + 1;
          return names2;
        }, {});
      }
    }
    exports._Code = _Code;
    exports.nil = new _Code("");
    function _2(strs, ...args) {
      const code2 = [strs[0]];
      let i2 = 0;
      while (i2 < args.length) {
        addCodeArg(code2, args[i2]);
        code2.push(strs[++i2]);
      }
      return new _Code(code2);
    }
    exports._ = _2;
    const plus = new _Code("+");
    function str(strs, ...args) {
      const expr = [safeStringify(strs[0])];
      let i2 = 0;
      while (i2 < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i2]);
        expr.push(plus, safeStringify(strs[++i2]));
      }
      optimize(expr);
      return new _Code(expr);
    }
    exports.str = str;
    function addCodeArg(code2, arg) {
      if (arg instanceof _Code)
        code2.push(...arg._items);
      else if (arg instanceof Name)
        code2.push(arg);
      else
        code2.push(interpolate(arg));
    }
    exports.addCodeArg = addCodeArg;
    function optimize(expr) {
      let i2 = 1;
      while (i2 < expr.length - 1) {
        if (expr[i2] === plus) {
          const res = mergeExprItems(expr[i2 - 1], expr[i2 + 1]);
          if (res !== void 0) {
            expr.splice(i2 - 1, 3, res);
            continue;
          }
          expr[i2++] = "+";
        }
        i2++;
      }
    }
    function mergeExprItems(a2, b2) {
      if (b2 === '""')
        return a2;
      if (a2 === '""')
        return b2;
      if (typeof a2 == "string") {
        if (b2 instanceof Name || a2[a2.length - 1] !== '"')
          return;
        if (typeof b2 != "string")
          return `${a2.slice(0, -1)}${b2}"`;
        if (b2[0] === '"')
          return a2.slice(0, -1) + b2.slice(1);
        return;
      }
      if (typeof b2 == "string" && b2[0] === '"' && !(a2 instanceof Name))
        return `"${a2}${b2.slice(1)}`;
      return;
    }
    function strConcat(c1, c2) {
      return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`;
    }
    exports.strConcat = strConcat;
    function interpolate(x2) {
      return typeof x2 == "number" || typeof x2 == "boolean" || x2 === null ? x2 : safeStringify(Array.isArray(x2) ? x2.join(",") : x2);
    }
    function stringify(x2) {
      return new _Code(safeStringify(x2));
    }
    exports.stringify = stringify;
    function safeStringify(x2) {
      return JSON.stringify(x2).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
    }
    exports.safeStringify = safeStringify;
    function getProperty(key) {
      return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _2`[${key}]`;
    }
    exports.getProperty = getProperty;
    function getEsmExportName(key) {
      if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
        return new _Code(`${key}`);
      }
      throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
    }
    exports.getEsmExportName = getEsmExportName;
    function regexpCode(rx) {
      return new _Code(rx.toString());
    }
    exports.regexpCode = regexpCode;
  })(code$3);
  return code$3;
}
var scope$1 = {};
var hasRequiredScope$1;
function requireScope$1() {
  if (hasRequiredScope$1) return scope$1;
  hasRequiredScope$1 = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
    const code_1 = /* @__PURE__ */ requireCode$3();
    class ValueError extends Error {
      constructor(name2) {
        super(`CodeGen: "code" for ${name2} not defined`);
        this.value = name2.value;
      }
    }
    var UsedValueState;
    (function(UsedValueState2) {
      UsedValueState2[UsedValueState2["Started"] = 0] = "Started";
      UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed";
    })(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
    exports.varKinds = {
      const: new code_1.Name("const"),
      let: new code_1.Name("let"),
      var: new code_1.Name("var")
    };
    class Scope {
      constructor({ prefixes, parent } = {}) {
        this._names = {};
        this._prefixes = prefixes;
        this._parent = parent;
      }
      toName(nameOrPrefix) {
        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
      }
      name(prefix) {
        return new code_1.Name(this._newName(prefix));
      }
      _newName(prefix) {
        const ng = this._names[prefix] || this._nameGroup(prefix);
        return `${prefix}${ng.index++}`;
      }
      _nameGroup(prefix) {
        var _a2, _b;
        if (((_b = (_a2 = this._parent) === null || _a2 === void 0 ? void 0 : _a2._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) {
          throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
        }
        return this._names[prefix] = { prefix, index: 0 };
      }
    }
    exports.Scope = Scope;
    class ValueScopeName extends code_1.Name {
      constructor(prefix, nameStr) {
        super(nameStr);
        this.prefix = prefix;
      }
      setValue(value, { property, itemIndex }) {
        this.value = value;
        this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`;
      }
    }
    exports.ValueScopeName = ValueScopeName;
    const line = (0, code_1._)`\n`;
    class ValueScope extends Scope {
      constructor(opts) {
        super(opts);
        this._values = {};
        this._scope = opts.scope;
        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
      }
      get() {
        return this._scope;
      }
      name(prefix) {
        return new ValueScopeName(prefix, this._newName(prefix));
      }
      value(nameOrPrefix, value) {
        var _a2;
        if (value.ref === void 0)
          throw new Error("CodeGen: ref must be passed in value");
        const name2 = this.toName(nameOrPrefix);
        const { prefix } = name2;
        const valueKey = (_a2 = value.key) !== null && _a2 !== void 0 ? _a2 : value.ref;
        let vs2 = this._values[prefix];
        if (vs2) {
          const _name = vs2.get(valueKey);
          if (_name)
            return _name;
        } else {
          vs2 = this._values[prefix] = /* @__PURE__ */ new Map();
        }
        vs2.set(valueKey, name2);
        const s2 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s2.length;
        s2[itemIndex] = value.ref;
        name2.setValue(value, { property: prefix, itemIndex });
        return name2;
      }
      getValue(prefix, keyOrRef) {
        const vs2 = this._values[prefix];
        if (!vs2)
          return;
        return vs2.get(keyOrRef);
      }
      scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name2) => {
          if (name2.scopePath === void 0)
            throw new Error(`CodeGen: name "${name2}" has no value`);
          return (0, code_1._)`${scopeName}${name2.scopePath}`;
        });
      }
      scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name2) => {
          if (name2.value === void 0)
            throw new Error(`CodeGen: name "${name2}" has no value`);
          return name2.value.code;
        }, usedValues, getCode);
      }
      _reduceValues(values, valueCode, usedValues = {}, getCode) {
        let code2 = code_1.nil;
        for (const prefix in values) {
          const vs2 = values[prefix];
          if (!vs2)
            continue;
          const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map();
          vs2.forEach((name2) => {
            if (nameSet.has(name2))
              return;
            nameSet.set(name2, UsedValueState.Started);
            let c = valueCode(name2);
            if (c) {
              const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
              code2 = (0, code_1._)`${code2}${def} ${name2} = ${c};${this.opts._n}`;
            } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name2)) {
              code2 = (0, code_1._)`${code2}${c}${this.opts._n}`;
            } else {
              throw new ValueError(name2);
            }
            nameSet.set(name2, UsedValueState.Completed);
          });
        }
        return code2;
      }
    }
    exports.ValueScope = ValueScope;
  })(scope$1);
  return scope$1;
}
var hasRequiredCodegen$1;
function requireCodegen$1() {
  if (hasRequiredCodegen$1) return codegen$1;
  hasRequiredCodegen$1 = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
    const code_1 = /* @__PURE__ */ requireCode$3();
    const scope_1 = /* @__PURE__ */ requireScope$1();
    var code_2 = /* @__PURE__ */ requireCode$3();
    Object.defineProperty(exports, "_", { enumerable: true, get: function() {
      return code_2._;
    } });
    Object.defineProperty(exports, "str", { enumerable: true, get: function() {
      return code_2.str;
    } });
    Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() {
      return code_2.strConcat;
    } });
    Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
      return code_2.nil;
    } });
    Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() {
      return code_2.getProperty;
    } });
    Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
      return code_2.stringify;
    } });
    Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() {
      return code_2.regexpCode;
    } });
    Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
      return code_2.Name;
    } });
    var scope_2 = /* @__PURE__ */ requireScope$1();
    Object.defineProperty(exports, "Scope", { enumerable: true, get: function() {
      return scope_2.Scope;
    } });
    Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() {
      return scope_2.ValueScope;
    } });
    Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() {
      return scope_2.ValueScopeName;
    } });
    Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() {
      return scope_2.varKinds;
    } });
    exports.operators = {
      GT: new code_1._Code(">"),
      GTE: new code_1._Code(">="),
      LT: new code_1._Code("<"),
      LTE: new code_1._Code("<="),
      EQ: new code_1._Code("==="),
      NEQ: new code_1._Code("!=="),
      NOT: new code_1._Code("!"),
      OR: new code_1._Code("||"),
      AND: new code_1._Code("&&"),
      ADD: new code_1._Code("+")
    };
    class Node2 {
      optimizeNodes() {
        return this;
      }
      optimizeNames(_names, _constants) {
        return this;
      }
    }
    class Def extends Node2 {
      constructor(varKind, name2, rhs) {
        super();
        this.varKind = varKind;
        this.name = name2;
        this.rhs = rhs;
      }
      render({ es5, _n: _n2 }) {
        const varKind = es5 ? scope_1.varKinds.var : this.varKind;
        const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
        return `${varKind} ${this.name}${rhs};` + _n2;
      }
      optimizeNames(names2, constants) {
        if (!names2[this.name.str])
          return;
        if (this.rhs)
          this.rhs = optimizeExpr(this.rhs, names2, constants);
        return this;
      }
      get names() {
        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
      }
    }
    class Assign extends Node2 {
      constructor(lhs, rhs, sideEffects) {
        super();
        this.lhs = lhs;
        this.rhs = rhs;
        this.sideEffects = sideEffects;
      }
      render({ _n: _n2 }) {
        return `${this.lhs} = ${this.rhs};` + _n2;
      }
      optimizeNames(names2, constants) {
        if (this.lhs instanceof code_1.Name && !names2[this.lhs.str] && !this.sideEffects)
          return;
        this.rhs = optimizeExpr(this.rhs, names2, constants);
        return this;
      }
      get names() {
        const names2 = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
        return addExprNames(names2, this.rhs);
      }
    }
    class AssignOp extends Assign {
      constructor(lhs, op2, rhs, sideEffects) {
        super(lhs, rhs, sideEffects);
        this.op = op2;
      }
      render({ _n: _n2 }) {
        return `${this.lhs} ${this.op}= ${this.rhs};` + _n2;
      }
    }
    class Label2 extends Node2 {
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n: _n2 }) {
        return `${this.label}:` + _n2;
      }
    }
    class Break extends Node2 {
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n: _n2 }) {
        const label = this.label ? ` ${this.label}` : "";
        return `break${label};` + _n2;
      }
    }
    class Throw extends Node2 {
      constructor(error) {
        super();
        this.error = error;
      }
      render({ _n: _n2 }) {
        return `throw ${this.error};` + _n2;
      }
      get names() {
        return this.error.names;
      }
    }
    class AnyCode extends Node2 {
      constructor(code2) {
        super();
        this.code = code2;
      }
      render({ _n: _n2 }) {
        return `${this.code};` + _n2;
      }
      optimizeNodes() {
        return `${this.code}` ? this : void 0;
      }
      optimizeNames(names2, constants) {
        this.code = optimizeExpr(this.code, names2, constants);
        return this;
      }
      get names() {
        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
      }
    }
    class ParentNode extends Node2 {
      constructor(nodes = []) {
        super();
        this.nodes = nodes;
      }
      render(opts) {
        return this.nodes.reduce((code2, n) => code2 + n.render(opts), "");
      }
      optimizeNodes() {
        const { nodes } = this;
        let i2 = nodes.length;
        while (i2--) {
          const n = nodes[i2].optimizeNodes();
          if (Array.isArray(n))
            nodes.splice(i2, 1, ...n);
          else if (n)
            nodes[i2] = n;
          else
            nodes.splice(i2, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names2, constants) {
        const { nodes } = this;
        let i2 = nodes.length;
        while (i2--) {
          const n = nodes[i2];
          if (n.optimizeNames(names2, constants))
            continue;
          subtractNames(names2, n.names);
          nodes.splice(i2, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      get names() {
        return this.nodes.reduce((names2, n) => addNames(names2, n.names), {});
      }
    }
    class BlockNode extends ParentNode {
      render(opts) {
        return "{" + opts._n + super.render(opts) + "}" + opts._n;
      }
    }
    class Root4 extends ParentNode {
    }
    class Else extends BlockNode {
    }
    Else.kind = "else";
    class If2 extends BlockNode {
      constructor(condition, nodes) {
        super(nodes);
        this.condition = condition;
      }
      render(opts) {
        let code2 = `if(${this.condition})` + super.render(opts);
        if (this.else)
          code2 += "else " + this.else.render(opts);
        return code2;
      }
      optimizeNodes() {
        super.optimizeNodes();
        const cond = this.condition;
        if (cond === true)
          return this.nodes;
        let e2 = this.else;
        if (e2) {
          const ns2 = e2.optimizeNodes();
          e2 = this.else = Array.isArray(ns2) ? new Else(ns2) : ns2;
        }
        if (e2) {
          if (cond === false)
            return e2 instanceof If2 ? e2 : e2.nodes;
          if (this.nodes.length)
            return this;
          return new If2(not2(cond), e2 instanceof If2 ? [e2] : e2.nodes);
        }
        if (cond === false || !this.nodes.length)
          return void 0;
        return this;
      }
      optimizeNames(names2, constants) {
        var _a2;
        this.else = (_a2 = this.else) === null || _a2 === void 0 ? void 0 : _a2.optimizeNames(names2, constants);
        if (!(super.optimizeNames(names2, constants) || this.else))
          return;
        this.condition = optimizeExpr(this.condition, names2, constants);
        return this;
      }
      get names() {
        const names2 = super.names;
        addExprNames(names2, this.condition);
        if (this.else)
          addNames(names2, this.else.names);
        return names2;
      }
    }
    If2.kind = "if";
    class For extends BlockNode {
    }
    For.kind = "for";
    class ForLoop extends For {
      constructor(iteration) {
        super();
        this.iteration = iteration;
      }
      render(opts) {
        return `for(${this.iteration})` + super.render(opts);
      }
      optimizeNames(names2, constants) {
        if (!super.optimizeNames(names2, constants))
          return;
        this.iteration = optimizeExpr(this.iteration, names2, constants);
        return this;
      }
      get names() {
        return addNames(super.names, this.iteration.names);
      }
    }
    class ForRange extends For {
      constructor(varKind, name2, from, to2) {
        super();
        this.varKind = varKind;
        this.name = name2;
        this.from = from;
        this.to = to2;
      }
      render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name: name2, from, to: to2 } = this;
        return `for(${varKind} ${name2}=${from}; ${name2}<${to2}; ${name2}++)` + super.render(opts);
      }
      get names() {
        const names2 = addExprNames(super.names, this.from);
        return addExprNames(names2, this.to);
      }
    }
    class ForIter extends For {
      constructor(loop, varKind, name2, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name2;
        this.iterable = iterable;
      }
      render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
      }
      optimizeNames(names2, constants) {
        if (!super.optimizeNames(names2, constants))
          return;
        this.iterable = optimizeExpr(this.iterable, names2, constants);
        return this;
      }
      get names() {
        return addNames(super.names, this.iterable.names);
      }
    }
    class Func extends BlockNode {
      constructor(name2, args, async2) {
        super();
        this.name = name2;
        this.args = args;
        this.async = async2;
      }
      render(opts) {
        const _async = this.async ? "async " : "";
        return `${_async}function ${this.name}(${this.args})` + super.render(opts);
      }
    }
    Func.kind = "func";
    class Return extends ParentNode {
      render(opts) {
        return "return " + super.render(opts);
      }
    }
    Return.kind = "return";
    class Try extends BlockNode {
      render(opts) {
        let code2 = "try" + super.render(opts);
        if (this.catch)
          code2 += this.catch.render(opts);
        if (this.finally)
          code2 += this.finally.render(opts);
        return code2;
      }
      optimizeNodes() {
        var _a2, _b;
        super.optimizeNodes();
        (_a2 = this.catch) === null || _a2 === void 0 ? void 0 : _a2.optimizeNodes();
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
        return this;
      }
      optimizeNames(names2, constants) {
        var _a2, _b;
        super.optimizeNames(names2, constants);
        (_a2 = this.catch) === null || _a2 === void 0 ? void 0 : _a2.optimizeNames(names2, constants);
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names2, constants);
        return this;
      }
      get names() {
        const names2 = super.names;
        if (this.catch)
          addNames(names2, this.catch.names);
        if (this.finally)
          addNames(names2, this.finally.names);
        return names2;
      }
    }
    class Catch extends BlockNode {
      constructor(error) {
        super();
        this.error = error;
      }
      render(opts) {
        return `catch(${this.error})` + super.render(opts);
      }
    }
    Catch.kind = "catch";
    class Finally extends BlockNode {
      render(opts) {
        return "finally" + super.render(opts);
      }
    }
    Finally.kind = "finally";
    class CodeGen {
      constructor(extScope, opts = {}) {
        this._values = {};
        this._blockStarts = [];
        this._constants = {};
        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
        this._extScope = extScope;
        this._scope = new scope_1.Scope({ parent: extScope });
        this._nodes = [new Root4()];
      }
      toString() {
        return this._root.render(this.opts);
      }
      // returns unique name in the internal scope
      name(prefix) {
        return this._scope.name(prefix);
      }
      // reserves unique name in the external scope
      scopeName(prefix) {
        return this._extScope.name(prefix);
      }
      // reserves unique name in the external scope and assigns value to it
      scopeValue(prefixOrName, value) {
        const name2 = this._extScope.value(prefixOrName, value);
        const vs2 = this._values[name2.prefix] || (this._values[name2.prefix] = /* @__PURE__ */ new Set());
        vs2.add(name2);
        return name2;
      }
      getScopeValue(prefix, keyOrRef) {
        return this._extScope.getValue(prefix, keyOrRef);
      }
      // return code that assigns values in the external scope to the names that are used internally
      // (same names that were returned by gen.scopeName or gen.scopeValue)
      scopeRefs(scopeName) {
        return this._extScope.scopeRefs(scopeName, this._values);
      }
      scopeCode() {
        return this._extScope.scopeCode(this._values);
      }
      _def(varKind, nameOrPrefix, rhs, constant) {
        const name2 = this._scope.toName(nameOrPrefix);
        if (rhs !== void 0 && constant)
          this._constants[name2.str] = rhs;
        this._leafNode(new Def(varKind, name2, rhs));
        return name2;
      }
      // `const` declaration (`var` in es5 mode)
      const(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
      }
      // `let` declaration with optional assignment (`var` in es5 mode)
      let(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
      }
      // `var` declaration with optional assignment
      var(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
      }
      // assignment code
      assign(lhs, rhs, sideEffects) {
        return this._leafNode(new Assign(lhs, rhs, sideEffects));
      }
      // `+=` code
      add(lhs, rhs) {
        return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
      }
      // appends passed SafeExpr to code or executes Block
      code(c) {
        if (typeof c == "function")
          c();
        else if (c !== code_1.nil)
          this._leafNode(new AnyCode(c));
        return this;
      }
      // returns code for object literal for the passed argument list of key-value pairs
      object(...keyValues) {
        const code2 = ["{"];
        for (const [key, value] of keyValues) {
          if (code2.length > 1)
            code2.push(",");
          code2.push(key);
          if (key !== value || this.opts.es5) {
            code2.push(":");
            (0, code_1.addCodeArg)(code2, value);
          }
        }
        code2.push("}");
        return new code_1._Code(code2);
      }
      // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
      if(condition, thenBody, elseBody) {
        this._blockNode(new If2(condition));
        if (thenBody && elseBody) {
          this.code(thenBody).else().code(elseBody).endIf();
        } else if (thenBody) {
          this.code(thenBody).endIf();
        } else if (elseBody) {
          throw new Error('CodeGen: "else" body without "then" body');
        }
        return this;
      }
      // `else if` clause - invalid without `if` or after `else` clauses
      elseIf(condition) {
        return this._elseNode(new If2(condition));
      }
      // `else` clause - only valid after `if` or `else if` clauses
      else() {
        return this._elseNode(new Else());
      }
      // end `if` statement (needed if gen.if was used only with condition)
      endIf() {
        return this._endBlockNode(If2, Else);
      }
      _for(node, forBody) {
        this._blockNode(node);
        if (forBody)
          this.code(forBody).endFor();
        return this;
      }
      // a generic `for` clause (or statement if `forBody` is passed)
      for(iteration, forBody) {
        return this._for(new ForLoop(iteration), forBody);
      }
      // `for` statement for a range of values
      forRange(nameOrPrefix, from, to2, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
        const name2 = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name2, from, to2), () => forBody(name2));
      }
      // `for-of` statement (in es5 mode replace with a normal for loop)
      forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name2 = this._scope.toName(nameOrPrefix);
        if (this.opts.es5) {
          const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
          return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i2) => {
            this.var(name2, (0, code_1._)`${arr}[${i2}]`);
            forBody(name2);
          });
        }
        return this._for(new ForIter("of", varKind, name2, iterable), () => forBody(name2));
      }
      // `for-in` statement.
      // With option `ownProperties` replaced with a `for-of` loop for object keys
      forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
        if (this.opts.ownProperties) {
          return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody);
        }
        const name2 = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name2, obj), () => forBody(name2));
      }
      // end `for` loop
      endFor() {
        return this._endBlockNode(For);
      }
      // `label` statement
      label(label) {
        return this._leafNode(new Label2(label));
      }
      // `break` statement
      break(label) {
        return this._leafNode(new Break(label));
      }
      // `return` statement
      return(value) {
        const node = new Return();
        this._blockNode(node);
        this.code(value);
        if (node.nodes.length !== 1)
          throw new Error('CodeGen: "return" should have one node');
        return this._endBlockNode(Return);
      }
      // `try` statement
      try(tryBody, catchCode, finallyCode) {
        if (!catchCode && !finallyCode)
          throw new Error('CodeGen: "try" without "catch" and "finally"');
        const node = new Try();
        this._blockNode(node);
        this.code(tryBody);
        if (catchCode) {
          const error = this.name("e");
          this._currNode = node.catch = new Catch(error);
          catchCode(error);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error) {
        return this._leafNode(new Throw(error));
      }
      // start self-balancing block
      block(body, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body)
          this.code(body).endBlock(nodeCount);
        return this;
      }
      // end the current self-balancing block
      endBlock(nodeCount) {
        const len = this._blockStarts.pop();
        if (len === void 0)
          throw new Error("CodeGen: not in self-balancing block");
        const toClose = this._nodes.length - len;
        if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) {
          throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
        }
        this._nodes.length = len;
        return this;
      }
      // `function` heading (or definition if funcBody is passed)
      func(name2, args = code_1.nil, async2, funcBody) {
        this._blockNode(new Func(name2, args, async2));
        if (funcBody)
          this.code(funcBody).endFunc();
        return this;
      }
      // end function definition
      endFunc() {
        return this._endBlockNode(Func);
      }
      optimize(n = 1) {
        while (n-- > 0) {
          this._root.optimizeNodes();
          this._root.optimizeNames(this._root.names, this._constants);
        }
      }
      _leafNode(node) {
        this._currNode.nodes.push(node);
        return this;
      }
      _blockNode(node) {
        this._currNode.nodes.push(node);
        this._nodes.push(node);
      }
      _endBlockNode(N1, N2) {
        const n = this._currNode;
        if (n instanceof N1 || N2 && n instanceof N2) {
          this._nodes.pop();
          return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
      }
      _elseNode(node) {
        const n = this._currNode;
        if (!(n instanceof If2)) {
          throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n.else = node;
        return this;
      }
      get _root() {
        return this._nodes[0];
      }
      get _currNode() {
        const ns2 = this._nodes;
        return ns2[ns2.length - 1];
      }
      set _currNode(node) {
        const ns2 = this._nodes;
        ns2[ns2.length - 1] = node;
      }
    }
    exports.CodeGen = CodeGen;
    function addNames(names2, from) {
      for (const n in from)
        names2[n] = (names2[n] || 0) + (from[n] || 0);
      return names2;
    }
    function addExprNames(names2, from) {
      return from instanceof code_1._CodeOrName ? addNames(names2, from.names) : names2;
    }
    function optimizeExpr(expr, names2, constants) {
      if (expr instanceof code_1.Name)
        return replaceName(expr);
      if (!canOptimize(expr))
        return expr;
      return new code_1._Code(expr._items.reduce((items2, c) => {
        if (c instanceof code_1.Name)
          c = replaceName(c);
        if (c instanceof code_1._Code)
          items2.push(...c._items);
        else
          items2.push(c);
        return items2;
      }, []));
      function replaceName(n) {
        const c = constants[n.str];
        if (c === void 0 || names2[n.str] !== 1)
          return n;
        delete names2[n.str];
        return c;
      }
      function canOptimize(e2) {
        return e2 instanceof code_1._Code && e2._items.some((c) => c instanceof code_1.Name && names2[c.str] === 1 && constants[c.str] !== void 0);
      }
    }
    function subtractNames(names2, from) {
      for (const n in from)
        names2[n] = (names2[n] || 0) - (from[n] || 0);
    }
    function not2(x2) {
      return typeof x2 == "boolean" || typeof x2 == "number" || x2 === null ? !x2 : (0, code_1._)`!${par(x2)}`;
    }
    exports.not = not2;
    const andCode = mappend(exports.operators.AND);
    function and(...args) {
      return args.reduce(andCode);
    }
    exports.and = and;
    const orCode = mappend(exports.operators.OR);
    function or2(...args) {
      return args.reduce(orCode);
    }
    exports.or = or2;
    function mappend(op2) {
      return (x2, y) => x2 === code_1.nil ? y : y === code_1.nil ? x2 : (0, code_1._)`${par(x2)} ${op2} ${par(y)}`;
    }
    function par(x2) {
      return x2 instanceof code_1.Name ? x2 : (0, code_1._)`(${x2})`;
    }
  })(codegen$1);
  return codegen$1;
}
var util$1 = {};
var hasRequiredUtil$1;
function requireUtil$1() {
  if (hasRequiredUtil$1) return util$1;
  hasRequiredUtil$1 = 1;
  Object.defineProperty(util$1, "__esModule", { value: true });
  util$1.checkStrictMode = util$1.getErrorPath = util$1.Type = util$1.useFunc = util$1.setEvaluated = util$1.evaluatedPropsToName = util$1.mergeEvaluated = util$1.eachItem = util$1.unescapeJsonPointer = util$1.escapeJsonPointer = util$1.escapeFragment = util$1.unescapeFragment = util$1.schemaRefOrVal = util$1.schemaHasRulesButRef = util$1.schemaHasRules = util$1.checkUnknownRules = util$1.alwaysValidSchema = util$1.toHash = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const code_1 = /* @__PURE__ */ requireCode$3();
  function toHash(arr) {
    const hash = {};
    for (const item of arr)
      hash[item] = true;
    return hash;
  }
  util$1.toHash = toHash;
  function alwaysValidSchema(it2, schema) {
    if (typeof schema == "boolean")
      return schema;
    if (Object.keys(schema).length === 0)
      return true;
    checkUnknownRules(it2, schema);
    return !schemaHasRules(schema, it2.self.RULES.all);
  }
  util$1.alwaysValidSchema = alwaysValidSchema;
  function checkUnknownRules(it2, schema = it2.schema) {
    const { opts, self: self2 } = it2;
    if (!opts.strictSchema)
      return;
    if (typeof schema === "boolean")
      return;
    const rules2 = self2.RULES.keywords;
    for (const key in schema) {
      if (!rules2[key])
        checkStrictMode(it2, `unknown keyword: "${key}"`);
    }
  }
  util$1.checkUnknownRules = checkUnknownRules;
  function schemaHasRules(schema, rules2) {
    if (typeof schema == "boolean")
      return !schema;
    for (const key in schema)
      if (rules2[key])
        return true;
    return false;
  }
  util$1.schemaHasRules = schemaHasRules;
  function schemaHasRulesButRef(schema, RULES) {
    if (typeof schema == "boolean")
      return !schema;
    for (const key in schema)
      if (key !== "$ref" && RULES.all[key])
        return true;
    return false;
  }
  util$1.schemaHasRulesButRef = schemaHasRulesButRef;
  function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword2, $data) {
    if (!$data) {
      if (typeof schema == "number" || typeof schema == "boolean")
        return schema;
      if (typeof schema == "string")
        return (0, codegen_1._)`${schema}`;
    }
    return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword2)}`;
  }
  util$1.schemaRefOrVal = schemaRefOrVal;
  function unescapeFragment(str) {
    return unescapeJsonPointer(decodeURIComponent(str));
  }
  util$1.unescapeFragment = unescapeFragment;
  function escapeFragment(str) {
    return encodeURIComponent(escapeJsonPointer(str));
  }
  util$1.escapeFragment = escapeFragment;
  function escapeJsonPointer(str) {
    if (typeof str == "number")
      return `${str}`;
    return str.replace(/~/g, "~0").replace(/\//g, "~1");
  }
  util$1.escapeJsonPointer = escapeJsonPointer;
  function unescapeJsonPointer(str) {
    return str.replace(/~1/g, "/").replace(/~0/g, "~");
  }
  util$1.unescapeJsonPointer = unescapeJsonPointer;
  function eachItem(xs2, f2) {
    if (Array.isArray(xs2)) {
      for (const x2 of xs2)
        f2(x2);
    } else {
      f2(xs2);
    }
  }
  util$1.eachItem = eachItem;
  function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues2, resultToName }) {
    return (gen, from, to2, toName) => {
      const res = to2 === void 0 ? from : to2 instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to2) : mergeToName(gen, from, to2), to2) : from instanceof codegen_1.Name ? (mergeToName(gen, to2, from), from) : mergeValues2(from, to2);
      return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
    };
  }
  util$1.mergeEvaluated = {
    props: makeMergeEvaluated({
      mergeNames: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true && ${from} !== undefined`, () => {
        gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to2, true), () => gen.assign(to2, (0, codegen_1._)`${to2} || {}`).code((0, codegen_1._)`Object.assign(${to2}, ${from})`));
      }),
      mergeToName: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true`, () => {
        if (from === true) {
          gen.assign(to2, true);
        } else {
          gen.assign(to2, (0, codegen_1._)`${to2} || {}`);
          setEvaluated(gen, to2, from);
        }
      }),
      mergeValues: (from, to2) => from === true ? true : { ...from, ...to2 },
      resultToName: evaluatedPropsToName
    }),
    items: makeMergeEvaluated({
      mergeNames: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true && ${from} !== undefined`, () => gen.assign(to2, (0, codegen_1._)`${from} === true ? true : ${to2} > ${from} ? ${to2} : ${from}`)),
      mergeToName: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true`, () => gen.assign(to2, from === true ? true : (0, codegen_1._)`${to2} > ${from} ? ${to2} : ${from}`)),
      mergeValues: (from, to2) => from === true ? true : Math.max(from, to2),
      resultToName: (gen, items2) => gen.var("items", items2)
    })
  };
  function evaluatedPropsToName(gen, ps2) {
    if (ps2 === true)
      return gen.var("props", true);
    const props = gen.var("props", (0, codegen_1._)`{}`);
    if (ps2 !== void 0)
      setEvaluated(gen, props, ps2);
    return props;
  }
  util$1.evaluatedPropsToName = evaluatedPropsToName;
  function setEvaluated(gen, props, ps2) {
    Object.keys(ps2).forEach((p2) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p2)}`, true));
  }
  util$1.setEvaluated = setEvaluated;
  const snippets = {};
  function useFunc(gen, f2) {
    return gen.scopeValue("func", {
      ref: f2,
      code: snippets[f2.code] || (snippets[f2.code] = new code_1._Code(f2.code))
    });
  }
  util$1.useFunc = useFunc;
  var Type;
  (function(Type2) {
    Type2[Type2["Num"] = 0] = "Num";
    Type2[Type2["Str"] = 1] = "Str";
  })(Type || (util$1.Type = Type = {}));
  function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
    if (dataProp instanceof codegen_1.Name) {
      const isNumber2 = dataPropType === Type.Num;
      return jsPropertySyntax ? isNumber2 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber2 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
    }
    return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
  }
  util$1.getErrorPath = getErrorPath;
  function checkStrictMode(it2, msg, mode = it2.opts.strictSchema) {
    if (!mode)
      return;
    msg = `strict mode: ${msg}`;
    if (mode === true)
      throw new Error(msg);
    it2.self.logger.warn(msg);
  }
  util$1.checkStrictMode = checkStrictMode;
  return util$1;
}
var names$1 = {};
var hasRequiredNames$1;
function requireNames$1() {
  if (hasRequiredNames$1) return names$1;
  hasRequiredNames$1 = 1;
  Object.defineProperty(names$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const names2 = {
    // validation function arguments
    data: new codegen_1.Name("data"),
    // data passed to validation function
    // args passed from referencing schema
    valCxt: new codegen_1.Name("valCxt"),
    // validation/data context - should not be used directly, it is destructured to the names below
    instancePath: new codegen_1.Name("instancePath"),
    parentData: new codegen_1.Name("parentData"),
    parentDataProperty: new codegen_1.Name("parentDataProperty"),
    rootData: new codegen_1.Name("rootData"),
    // root data - same as the data passed to the first/top validation function
    dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
    // used to support recursiveRef and dynamicRef
    // function scoped variables
    vErrors: new codegen_1.Name("vErrors"),
    // null or array of validation errors
    errors: new codegen_1.Name("errors"),
    // counter of validation errors
    this: new codegen_1.Name("this"),
    // "globals"
    self: new codegen_1.Name("self"),
    scope: new codegen_1.Name("scope"),
    // JTD serialize/parse name for JSON string and position
    json: new codegen_1.Name("json"),
    jsonPos: new codegen_1.Name("jsonPos"),
    jsonLen: new codegen_1.Name("jsonLen"),
    jsonPart: new codegen_1.Name("jsonPart")
  };
  names$1.default = names2;
  return names$1;
}
var hasRequiredErrors$1;
function requireErrors$1() {
  if (hasRequiredErrors$1) return errors$1;
  hasRequiredErrors$1 = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
    const codegen_1 = /* @__PURE__ */ requireCodegen$1();
    const util_1 = /* @__PURE__ */ requireUtil$1();
    const names_1 = /* @__PURE__ */ requireNames$1();
    exports.keywordError = {
      message: ({ keyword: keyword2 }) => (0, codegen_1.str)`must pass "${keyword2}" keyword validation`
    };
    exports.keyword$DataError = {
      message: ({ keyword: keyword2, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword2}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword2}" keyword is invalid ($data)`
    };
    function reportError2(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
      const { it: it2 } = cxt;
      const { gen, compositeRule, allErrors } = it2;
      const errObj = errorObjectCode(cxt, error, errorPaths);
      if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
        addError(gen, errObj);
      } else {
        returnErrors(it2, (0, codegen_1._)`[${errObj}]`);
      }
    }
    exports.reportError = reportError2;
    function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
      const { it: it2 } = cxt;
      const { gen, compositeRule, allErrors } = it2;
      const errObj = errorObjectCode(cxt, error, errorPaths);
      addError(gen, errObj);
      if (!(compositeRule || allErrors)) {
        returnErrors(it2, names_1.default.vErrors);
      }
    }
    exports.reportExtraError = reportExtraError;
    function resetErrorsCount(gen, errsCount) {
      gen.assign(names_1.default.errors, errsCount);
      gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
    }
    exports.resetErrorsCount = resetErrorsCount;
    function extendErrors({ gen, keyword: keyword2, schemaValue, data: data2, errsCount, it: it2 }) {
      if (errsCount === void 0)
        throw new Error("ajv implementation error");
      const err = gen.name("err");
      gen.forRange("i", errsCount, names_1.default.errors, (i2) => {
        gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i2}]`);
        gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it2.errorPath)));
        gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it2.errSchemaPath}/${keyword2}`);
        if (it2.opts.verbose) {
          gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);
          gen.assign((0, codegen_1._)`${err}.data`, data2);
        }
      });
    }
    exports.extendErrors = extendErrors;
    function addError(gen, errObj) {
      const err = gen.const("err", errObj);
      gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`);
      gen.code((0, codegen_1._)`${names_1.default.errors}++`);
    }
    function returnErrors(it2, errs) {
      const { gen, validateName, schemaEnv } = it2;
      if (schemaEnv.$async) {
        gen.throw((0, codegen_1._)`new ${it2.ValidationError}(${errs})`);
      } else {
        gen.assign((0, codegen_1._)`${validateName}.errors`, errs);
        gen.return(false);
      }
    }
    const E2 = {
      keyword: new codegen_1.Name("keyword"),
      schemaPath: new codegen_1.Name("schemaPath"),
      // also used in JTD errors
      params: new codegen_1.Name("params"),
      propertyName: new codegen_1.Name("propertyName"),
      message: new codegen_1.Name("message"),
      schema: new codegen_1.Name("schema"),
      parentSchema: new codegen_1.Name("parentSchema")
    };
    function errorObjectCode(cxt, error, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error, errorPaths);
    }
    function errorObject(cxt, error, errorPaths = {}) {
      const { gen, it: it2 } = cxt;
      const keyValues = [
        errorInstancePath(it2, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error, keyValues);
      return gen.object(...keyValues);
    }
    function errorInstancePath({ errorPath }, { instancePath }) {
      const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath;
      return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
    }
    function errorSchemaPath({ keyword: keyword2, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
      let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword2}`;
      if (schemaPath) {
        schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
      }
      return [E2.schemaPath, schPath];
    }
    function extraErrorProps(cxt, { params, message }, keyValues) {
      const { keyword: keyword2, data: data2, schemaValue, it: it2 } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it2;
      keyValues.push([E2.keyword, keyword2], [E2.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
      if (opts.messages) {
        keyValues.push([E2.message, typeof message == "function" ? message(cxt) : message]);
      }
      if (opts.verbose) {
        keyValues.push([E2.schema, schemaValue], [E2.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data2]);
      }
      if (propertyName)
        keyValues.push([E2.propertyName, propertyName]);
    }
  })(errors$1);
  return errors$1;
}
var hasRequiredBoolSchema$1;
function requireBoolSchema$1() {
  if (hasRequiredBoolSchema$1) return boolSchema$1;
  hasRequiredBoolSchema$1 = 1;
  Object.defineProperty(boolSchema$1, "__esModule", { value: true });
  boolSchema$1.boolOrEmptySchema = boolSchema$1.topBoolOrEmptySchema = void 0;
  const errors_1 = /* @__PURE__ */ requireErrors$1();
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const names_1 = /* @__PURE__ */ requireNames$1();
  const boolError = {
    message: "boolean schema is false"
  };
  function topBoolOrEmptySchema(it2) {
    const { gen, schema, validateName } = it2;
    if (schema === false) {
      falseSchemaError(it2, false);
    } else if (typeof schema == "object" && schema.$async === true) {
      gen.return(names_1.default.data);
    } else {
      gen.assign((0, codegen_1._)`${validateName}.errors`, null);
      gen.return(true);
    }
  }
  boolSchema$1.topBoolOrEmptySchema = topBoolOrEmptySchema;
  function boolOrEmptySchema(it2, valid) {
    const { gen, schema } = it2;
    if (schema === false) {
      gen.var(valid, false);
      falseSchemaError(it2);
    } else {
      gen.var(valid, true);
    }
  }
  boolSchema$1.boolOrEmptySchema = boolOrEmptySchema;
  function falseSchemaError(it2, overrideAllErrors) {
    const { gen, data: data2 } = it2;
    const cxt = {
      gen,
      keyword: "false schema",
      data: data2,
      schema: false,
      schemaCode: false,
      schemaValue: false,
      params: {},
      it: it2
    };
    (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
  }
  return boolSchema$1;
}
var dataType$1 = {};
var rules$1 = {};
var hasRequiredRules$1;
function requireRules$1() {
  if (hasRequiredRules$1) return rules$1;
  hasRequiredRules$1 = 1;
  Object.defineProperty(rules$1, "__esModule", { value: true });
  rules$1.getRules = rules$1.isJSONType = void 0;
  const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
  const jsonTypes = new Set(_jsonTypes);
  function isJSONType(x2) {
    return typeof x2 == "string" && jsonTypes.has(x2);
  }
  rules$1.isJSONType = isJSONType;
  function getRules() {
    const groups = {
      number: { type: "number", rules: [] },
      string: { type: "string", rules: [] },
      array: { type: "array", rules: [] },
      object: { type: "object", rules: [] }
    };
    return {
      types: { ...groups, integer: true, boolean: true, null: true },
      rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
      post: { rules: [] },
      all: {},
      keywords: {}
    };
  }
  rules$1.getRules = getRules;
  return rules$1;
}
var applicability$1 = {};
var hasRequiredApplicability$1;
function requireApplicability$1() {
  if (hasRequiredApplicability$1) return applicability$1;
  hasRequiredApplicability$1 = 1;
  Object.defineProperty(applicability$1, "__esModule", { value: true });
  applicability$1.shouldUseRule = applicability$1.shouldUseGroup = applicability$1.schemaHasRulesForType = void 0;
  function schemaHasRulesForType({ schema, self: self2 }, type2) {
    const group = self2.RULES.types[type2];
    return group && group !== true && shouldUseGroup(schema, group);
  }
  applicability$1.schemaHasRulesForType = schemaHasRulesForType;
  function shouldUseGroup(schema, group) {
    return group.rules.some((rule) => shouldUseRule(schema, rule));
  }
  applicability$1.shouldUseGroup = shouldUseGroup;
  function shouldUseRule(schema, rule) {
    var _a2;
    return schema[rule.keyword] !== void 0 || ((_a2 = rule.definition.implements) === null || _a2 === void 0 ? void 0 : _a2.some((kwd) => schema[kwd] !== void 0));
  }
  applicability$1.shouldUseRule = shouldUseRule;
  return applicability$1;
}
var hasRequiredDataType$1;
function requireDataType$1() {
  if (hasRequiredDataType$1) return dataType$1;
  hasRequiredDataType$1 = 1;
  Object.defineProperty(dataType$1, "__esModule", { value: true });
  dataType$1.reportTypeError = dataType$1.checkDataTypes = dataType$1.checkDataType = dataType$1.coerceAndCheckDataType = dataType$1.getJSONTypes = dataType$1.getSchemaTypes = dataType$1.DataType = void 0;
  const rules_1 = /* @__PURE__ */ requireRules$1();
  const applicability_1 = /* @__PURE__ */ requireApplicability$1();
  const errors_1 = /* @__PURE__ */ requireErrors$1();
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  var DataType;
  (function(DataType2) {
    DataType2[DataType2["Correct"] = 0] = "Correct";
    DataType2[DataType2["Wrong"] = 1] = "Wrong";
  })(DataType || (dataType$1.DataType = DataType = {}));
  function getSchemaTypes(schema) {
    const types2 = getJSONTypes(schema.type);
    const hasNull = types2.includes("null");
    if (hasNull) {
      if (schema.nullable === false)
        throw new Error("type: null contradicts nullable: false");
    } else {
      if (!types2.length && schema.nullable !== void 0) {
        throw new Error('"nullable" cannot be used without "type"');
      }
      if (schema.nullable === true)
        types2.push("null");
    }
    return types2;
  }
  dataType$1.getSchemaTypes = getSchemaTypes;
  function getJSONTypes(ts2) {
    const types2 = Array.isArray(ts2) ? ts2 : ts2 ? [ts2] : [];
    if (types2.every(rules_1.isJSONType))
      return types2;
    throw new Error("type must be JSONType or JSONType[]: " + types2.join(","));
  }
  dataType$1.getJSONTypes = getJSONTypes;
  function coerceAndCheckDataType(it2, types2) {
    const { gen, data: data2, opts } = it2;
    const coerceTo = coerceToTypes(types2, opts.coerceTypes);
    const checkTypes = types2.length > 0 && !(coerceTo.length === 0 && types2.length === 1 && (0, applicability_1.schemaHasRulesForType)(it2, types2[0]));
    if (checkTypes) {
      const wrongType = checkDataTypes(types2, data2, opts.strictNumbers, DataType.Wrong);
      gen.if(wrongType, () => {
        if (coerceTo.length)
          coerceData(it2, types2, coerceTo);
        else
          reportTypeError(it2);
      });
    }
    return checkTypes;
  }
  dataType$1.coerceAndCheckDataType = coerceAndCheckDataType;
  const COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
  function coerceToTypes(types2, coerceTypes) {
    return coerceTypes ? types2.filter((t2) => COERCIBLE.has(t2) || coerceTypes === "array" && t2 === "array") : [];
  }
  function coerceData(it2, types2, coerceTo) {
    const { gen, data: data2, opts } = it2;
    const dataType2 = gen.let("dataType", (0, codegen_1._)`typeof ${data2}`);
    const coerced = gen.let("coerced", (0, codegen_1._)`undefined`);
    if (opts.coerceTypes === "array") {
      gen.if((0, codegen_1._)`${dataType2} == 'object' && Array.isArray(${data2}) && ${data2}.length == 1`, () => gen.assign(data2, (0, codegen_1._)`${data2}[0]`).assign(dataType2, (0, codegen_1._)`typeof ${data2}`).if(checkDataTypes(types2, data2, opts.strictNumbers), () => gen.assign(coerced, data2)));
    }
    gen.if((0, codegen_1._)`${coerced} !== undefined`);
    for (const t2 of coerceTo) {
      if (COERCIBLE.has(t2) || t2 === "array" && opts.coerceTypes === "array") {
        coerceSpecificType(t2);
      }
    }
    gen.else();
    reportTypeError(it2);
    gen.endIf();
    gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
      gen.assign(data2, coerced);
      assignParentData(it2, coerced);
    });
    function coerceSpecificType(t2) {
      switch (t2) {
        case "string":
          gen.elseIf((0, codegen_1._)`${dataType2} == "number" || ${dataType2} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data2}`).elseIf((0, codegen_1._)`${data2} === null`).assign(coerced, (0, codegen_1._)`""`);
          return;
        case "number":
          gen.elseIf((0, codegen_1._)`${dataType2} == "boolean" || ${data2} === null
              || (${dataType2} == "string" && ${data2} && ${data2} == +${data2})`).assign(coerced, (0, codegen_1._)`+${data2}`);
          return;
        case "integer":
          gen.elseIf((0, codegen_1._)`${dataType2} === "boolean" || ${data2} === null
              || (${dataType2} === "string" && ${data2} && ${data2} == +${data2} && !(${data2} % 1))`).assign(coerced, (0, codegen_1._)`+${data2}`);
          return;
        case "boolean":
          gen.elseIf((0, codegen_1._)`${data2} === "false" || ${data2} === 0 || ${data2} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data2} === "true" || ${data2} === 1`).assign(coerced, true);
          return;
        case "null":
          gen.elseIf((0, codegen_1._)`${data2} === "" || ${data2} === 0 || ${data2} === false`);
          gen.assign(coerced, null);
          return;
        case "array":
          gen.elseIf((0, codegen_1._)`${dataType2} === "string" || ${dataType2} === "number"
              || ${dataType2} === "boolean" || ${data2} === null`).assign(coerced, (0, codegen_1._)`[${data2}]`);
      }
    }
  }
  function assignParentData({ gen, parentData, parentDataProperty }, expr) {
    gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));
  }
  function checkDataType(dataType2, data2, strictNums, correct = DataType.Correct) {
    const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
    let cond;
    switch (dataType2) {
      case "null":
        return (0, codegen_1._)`${data2} ${EQ} null`;
      case "array":
        cond = (0, codegen_1._)`Array.isArray(${data2})`;
        break;
      case "object":
        cond = (0, codegen_1._)`${data2} && typeof ${data2} == "object" && !Array.isArray(${data2})`;
        break;
      case "integer":
        cond = numCond((0, codegen_1._)`!(${data2} % 1) && !isNaN(${data2})`);
        break;
      case "number":
        cond = numCond();
        break;
      default:
        return (0, codegen_1._)`typeof ${data2} ${EQ} ${dataType2}`;
    }
    return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
    function numCond(_cond = codegen_1.nil) {
      return (0, codegen_1.and)((0, codegen_1._)`typeof ${data2} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data2})` : codegen_1.nil);
    }
  }
  dataType$1.checkDataType = checkDataType;
  function checkDataTypes(dataTypes, data2, strictNums, correct) {
    if (dataTypes.length === 1) {
      return checkDataType(dataTypes[0], data2, strictNums, correct);
    }
    let cond;
    const types2 = (0, util_1.toHash)(dataTypes);
    if (types2.array && types2.object) {
      const notObj = (0, codegen_1._)`typeof ${data2} != "object"`;
      cond = types2.null ? notObj : (0, codegen_1._)`!${data2} || ${notObj}`;
      delete types2.null;
      delete types2.array;
      delete types2.object;
    } else {
      cond = codegen_1.nil;
    }
    if (types2.number)
      delete types2.integer;
    for (const t2 in types2)
      cond = (0, codegen_1.and)(cond, checkDataType(t2, data2, strictNums, correct));
    return cond;
  }
  dataType$1.checkDataTypes = checkDataTypes;
  const typeError = {
    message: ({ schema }) => `must be ${schema}`,
    params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`
  };
  function reportTypeError(it2) {
    const cxt = getTypeErrorContext(it2);
    (0, errors_1.reportError)(cxt, typeError);
  }
  dataType$1.reportTypeError = reportTypeError;
  function getTypeErrorContext(it2) {
    const { gen, data: data2, schema } = it2;
    const schemaCode = (0, util_1.schemaRefOrVal)(it2, schema, "type");
    return {
      gen,
      keyword: "type",
      data: data2,
      schema: schema.type,
      schemaCode,
      schemaValue: schemaCode,
      parentSchema: schema,
      params: {},
      it: it2
    };
  }
  return dataType$1;
}
var defaults$1 = {};
var hasRequiredDefaults$1;
function requireDefaults$1() {
  if (hasRequiredDefaults$1) return defaults$1;
  hasRequiredDefaults$1 = 1;
  Object.defineProperty(defaults$1, "__esModule", { value: true });
  defaults$1.assignDefaults = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  function assignDefaults(it2, ty) {
    const { properties: properties2, items: items2 } = it2.schema;
    if (ty === "object" && properties2) {
      for (const key in properties2) {
        assignDefault(it2, key, properties2[key].default);
      }
    } else if (ty === "array" && Array.isArray(items2)) {
      items2.forEach((sch, i2) => assignDefault(it2, i2, sch.default));
    }
  }
  defaults$1.assignDefaults = assignDefaults;
  function assignDefault(it2, prop, defaultValue) {
    const { gen, compositeRule, data: data2, opts } = it2;
    if (defaultValue === void 0)
      return;
    const childData = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(prop)}`;
    if (compositeRule) {
      (0, util_1.checkStrictMode)(it2, `default is ignored for: ${childData}`);
      return;
    }
    let condition = (0, codegen_1._)`${childData} === undefined`;
    if (opts.useDefaults === "empty") {
      condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
    }
    gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
  }
  return defaults$1;
}
var keyword$1 = {};
var code$2 = {};
var hasRequiredCode$2;
function requireCode$2() {
  if (hasRequiredCode$2) return code$2;
  hasRequiredCode$2 = 1;
  Object.defineProperty(code$2, "__esModule", { value: true });
  code$2.validateUnion = code$2.validateArray = code$2.usePattern = code$2.callValidateCode = code$2.schemaProperties = code$2.allSchemaProperties = code$2.noPropertyInData = code$2.propertyInData = code$2.isOwnProperty = code$2.hasPropFunc = code$2.reportMissingProp = code$2.checkMissingProp = code$2.checkReportMissingProp = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const names_1 = /* @__PURE__ */ requireNames$1();
  const util_2 = /* @__PURE__ */ requireUtil$1();
  function checkReportMissingProp(cxt, prop) {
    const { gen, data: data2, it: it2 } = cxt;
    gen.if(noPropertyInData(gen, data2, prop, it2.opts.ownProperties), () => {
      cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
      cxt.error();
    });
  }
  code$2.checkReportMissingProp = checkReportMissingProp;
  function checkMissingProp({ gen, data: data2, it: { opts } }, properties2, missing) {
    return (0, codegen_1.or)(...properties2.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data2, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
  }
  code$2.checkMissingProp = checkMissingProp;
  function reportMissingProp(cxt, missing) {
    cxt.setParams({ missingProperty: missing }, true);
    cxt.error();
  }
  code$2.reportMissingProp = reportMissingProp;
  function hasPropFunc(gen) {
    return gen.scopeValue("func", {
      // eslint-disable-next-line @typescript-eslint/unbound-method
      ref: Object.prototype.hasOwnProperty,
      code: (0, codegen_1._)`Object.prototype.hasOwnProperty`
    });
  }
  code$2.hasPropFunc = hasPropFunc;
  function isOwnProperty(gen, data2, property) {
    return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data2}, ${property})`;
  }
  code$2.isOwnProperty = isOwnProperty;
  function propertyInData(gen, data2, property, ownProperties) {
    const cond = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(property)} !== undefined`;
    return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data2, property)}` : cond;
  }
  code$2.propertyInData = propertyInData;
  function noPropertyInData(gen, data2, property, ownProperties) {
    const cond = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(property)} === undefined`;
    return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data2, property))) : cond;
  }
  code$2.noPropertyInData = noPropertyInData;
  function allSchemaProperties(schemaMap) {
    return schemaMap ? Object.keys(schemaMap).filter((p2) => p2 !== "__proto__") : [];
  }
  code$2.allSchemaProperties = allSchemaProperties;
  function schemaProperties(it2, schemaMap) {
    return allSchemaProperties(schemaMap).filter((p2) => !(0, util_1.alwaysValidSchema)(it2, schemaMap[p2]));
  }
  code$2.schemaProperties = schemaProperties;
  function callValidateCode({ schemaCode, data: data2, it: { gen, topSchemaRef, schemaPath, errorPath }, it: it2 }, func, context, passSchema) {
    const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data2}, ${topSchemaRef}${schemaPath}` : data2;
    const valCxt = [
      [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
      [names_1.default.parentData, it2.parentData],
      [names_1.default.parentDataProperty, it2.parentDataProperty],
      [names_1.default.rootData, names_1.default.rootData]
    ];
    if (it2.opts.dynamicRef)
      valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
    const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
    return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;
  }
  code$2.callValidateCode = callValidateCode;
  const newRegExp = (0, codegen_1._)`new RegExp`;
  function usePattern({ gen, it: { opts } }, pattern2) {
    const u2 = opts.unicodeRegExp ? "u" : "";
    const { regExp } = opts.code;
    const rx = regExp(pattern2, u2);
    return gen.scopeValue("pattern", {
      key: rx.toString(),
      ref: rx,
      code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern2}, ${u2})`
    });
  }
  code$2.usePattern = usePattern;
  function validateArray(cxt) {
    const { gen, data: data2, keyword: keyword2, it: it2 } = cxt;
    const valid = gen.name("valid");
    if (it2.allErrors) {
      const validArr = gen.let("valid", true);
      validateItems(() => gen.assign(validArr, false));
      return validArr;
    }
    gen.var(valid, true);
    validateItems(() => gen.break());
    return valid;
    function validateItems(notValid) {
      const len = gen.const("len", (0, codegen_1._)`${data2}.length`);
      gen.forRange("i", 0, len, (i2) => {
        cxt.subschema({
          keyword: keyword2,
          dataProp: i2,
          dataPropType: util_1.Type.Num
        }, valid);
        gen.if((0, codegen_1.not)(valid), notValid);
      });
    }
  }
  code$2.validateArray = validateArray;
  function validateUnion(cxt) {
    const { gen, schema, keyword: keyword2, it: it2 } = cxt;
    if (!Array.isArray(schema))
      throw new Error("ajv implementation error");
    const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it2, sch));
    if (alwaysValid && !it2.opts.unevaluated)
      return;
    const valid = gen.let("valid", false);
    const schValid = gen.name("_valid");
    gen.block(() => schema.forEach((_sch, i2) => {
      const schCxt = cxt.subschema({
        keyword: keyword2,
        schemaProp: i2,
        compositeRule: true
      }, schValid);
      gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`);
      const merged = cxt.mergeValidEvaluated(schCxt, schValid);
      if (!merged)
        gen.if((0, codegen_1.not)(valid));
    }));
    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
  }
  code$2.validateUnion = validateUnion;
  return code$2;
}
var hasRequiredKeyword$1;
function requireKeyword$1() {
  if (hasRequiredKeyword$1) return keyword$1;
  hasRequiredKeyword$1 = 1;
  Object.defineProperty(keyword$1, "__esModule", { value: true });
  keyword$1.validateKeywordUsage = keyword$1.validSchemaType = keyword$1.funcKeywordCode = keyword$1.macroKeywordCode = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const names_1 = /* @__PURE__ */ requireNames$1();
  const code_1 = /* @__PURE__ */ requireCode$2();
  const errors_1 = /* @__PURE__ */ requireErrors$1();
  function macroKeywordCode(cxt, def) {
    const { gen, keyword: keyword2, schema, parentSchema, it: it2 } = cxt;
    const macroSchema = def.macro.call(it2.self, schema, parentSchema, it2);
    const schemaRef = useKeyword(gen, keyword2, macroSchema);
    if (it2.opts.validateSchema !== false)
      it2.self.validateSchema(macroSchema, true);
    const valid = gen.name("valid");
    cxt.subschema({
      schema: macroSchema,
      schemaPath: codegen_1.nil,
      errSchemaPath: `${it2.errSchemaPath}/${keyword2}`,
      topSchemaRef: schemaRef,
      compositeRule: true
    }, valid);
    cxt.pass(valid, () => cxt.error(true));
  }
  keyword$1.macroKeywordCode = macroKeywordCode;
  function funcKeywordCode(cxt, def) {
    var _a2;
    const { gen, keyword: keyword2, schema, parentSchema, $data, it: it2 } = cxt;
    checkAsyncKeyword(it2, def);
    const validate2 = !$data && def.compile ? def.compile.call(it2.self, schema, parentSchema, it2) : def.validate;
    const validateRef = useKeyword(gen, keyword2, validate2);
    const valid = gen.let("valid");
    cxt.block$data(valid, validateKeyword);
    cxt.ok((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid);
    function validateKeyword() {
      if (def.errors === false) {
        assignValid();
        if (def.modifying)
          modifyData(cxt);
        reportErrs(() => cxt.error());
      } else {
        const ruleErrs = def.async ? validateAsync() : validateSync();
        if (def.modifying)
          modifyData(cxt);
        reportErrs(() => addErrs(cxt, ruleErrs));
      }
    }
    function validateAsync() {
      const ruleErrs = gen.let("ruleErrs", null);
      gen.try(() => assignValid((0, codegen_1._)`await `), (e2) => gen.assign(valid, false).if((0, codegen_1._)`${e2} instanceof ${it2.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e2}.errors`), () => gen.throw(e2)));
      return ruleErrs;
    }
    function validateSync() {
      const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
      gen.assign(validateErrs, null);
      assignValid(codegen_1.nil);
      return validateErrs;
    }
    function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) {
      const passCxt = it2.opts.passContext ? names_1.default.this : names_1.default.self;
      const passSchema = !("compile" in def && !$data || def.schema === false);
      gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
    }
    function reportErrs(errors2) {
      var _a3;
      gen.if((0, codegen_1.not)((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid), errors2);
    }
  }
  keyword$1.funcKeywordCode = funcKeywordCode;
  function modifyData(cxt) {
    const { gen, data: data2, it: it2 } = cxt;
    gen.if(it2.parentData, () => gen.assign(data2, (0, codegen_1._)`${it2.parentData}[${it2.parentDataProperty}]`));
  }
  function addErrs(cxt, errs) {
    const { gen } = cxt;
    gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => {
      gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
      (0, errors_1.extendErrors)(cxt);
    }, () => cxt.error());
  }
  function checkAsyncKeyword({ schemaEnv }, def) {
    if (def.async && !schemaEnv.$async)
      throw new Error("async keyword in sync schema");
  }
  function useKeyword(gen, keyword2, result) {
    if (result === void 0)
      throw new Error(`keyword "${keyword2}" failed to compile`);
    return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
  }
  function validSchemaType(schema, schemaType, allowUndefined = false) {
    return !schemaType.length || schemaType.some((st2) => st2 === "array" ? Array.isArray(schema) : st2 === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st2 || allowUndefined && typeof schema == "undefined");
  }
  keyword$1.validSchemaType = validSchemaType;
  function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword2) {
    if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword2) : def.keyword !== keyword2) {
      throw new Error("ajv implementation error");
    }
    const deps = def.dependencies;
    if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
      throw new Error(`parent schema must have dependencies of ${keyword2}: ${deps.join(",")}`);
    }
    if (def.validateSchema) {
      const valid = def.validateSchema(schema[keyword2]);
      if (!valid) {
        const msg = `keyword "${keyword2}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors);
        if (opts.validateSchema === "log")
          self2.logger.error(msg);
        else
          throw new Error(msg);
      }
    }
  }
  keyword$1.validateKeywordUsage = validateKeywordUsage;
  return keyword$1;
}
var subschema$1 = {};
var hasRequiredSubschema$1;
function requireSubschema$1() {
  if (hasRequiredSubschema$1) return subschema$1;
  hasRequiredSubschema$1 = 1;
  Object.defineProperty(subschema$1, "__esModule", { value: true });
  subschema$1.extendSubschemaMode = subschema$1.extendSubschemaData = subschema$1.getSubschema = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  function getSubschema(it2, { keyword: keyword2, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
    if (keyword2 !== void 0 && schema !== void 0) {
      throw new Error('both "keyword" and "schema" passed, only one allowed');
    }
    if (keyword2 !== void 0) {
      const sch = it2.schema[keyword2];
      return schemaProp === void 0 ? {
        schema: sch,
        schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword2)}`,
        errSchemaPath: `${it2.errSchemaPath}/${keyword2}`
      } : {
        schema: sch[schemaProp],
        schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword2)}${(0, codegen_1.getProperty)(schemaProp)}`,
        errSchemaPath: `${it2.errSchemaPath}/${keyword2}/${(0, util_1.escapeFragment)(schemaProp)}`
      };
    }
    if (schema !== void 0) {
      if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) {
        throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
      }
      return {
        schema,
        schemaPath,
        topSchemaRef,
        errSchemaPath
      };
    }
    throw new Error('either "keyword" or "schema" must be passed');
  }
  subschema$1.getSubschema = getSubschema;
  function extendSubschemaData(subschema2, it2, { dataProp, dataPropType: dpType, data: data2, dataTypes, propertyName }) {
    if (data2 !== void 0 && dataProp !== void 0) {
      throw new Error('both "data" and "dataProp" passed, only one allowed');
    }
    const { gen } = it2;
    if (dataProp !== void 0) {
      const { errorPath, dataPathArr, opts } = it2;
      const nextData = gen.let("data", (0, codegen_1._)`${it2.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
      dataContextProps(nextData);
      subschema2.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
      subschema2.parentDataProperty = (0, codegen_1._)`${dataProp}`;
      subschema2.dataPathArr = [...dataPathArr, subschema2.parentDataProperty];
    }
    if (data2 !== void 0) {
      const nextData = data2 instanceof codegen_1.Name ? data2 : gen.let("data", data2, true);
      dataContextProps(nextData);
      if (propertyName !== void 0)
        subschema2.propertyName = propertyName;
    }
    if (dataTypes)
      subschema2.dataTypes = dataTypes;
    function dataContextProps(_nextData) {
      subschema2.data = _nextData;
      subschema2.dataLevel = it2.dataLevel + 1;
      subschema2.dataTypes = [];
      it2.definedProperties = /* @__PURE__ */ new Set();
      subschema2.parentData = it2.data;
      subschema2.dataNames = [...it2.dataNames, _nextData];
    }
  }
  subschema$1.extendSubschemaData = extendSubschemaData;
  function extendSubschemaMode(subschema2, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
    if (compositeRule !== void 0)
      subschema2.compositeRule = compositeRule;
    if (createErrors !== void 0)
      subschema2.createErrors = createErrors;
    if (allErrors !== void 0)
      subschema2.allErrors = allErrors;
    subschema2.jtdDiscriminator = jtdDiscriminator;
    subschema2.jtdMetadata = jtdMetadata;
  }
  subschema$1.extendSubschemaMode = extendSubschemaMode;
  return subschema$1;
}
var resolve$1 = {};
var jsonSchemaTraverse$1 = { exports: {} };
var hasRequiredJsonSchemaTraverse$1;
function requireJsonSchemaTraverse$1() {
  if (hasRequiredJsonSchemaTraverse$1) return jsonSchemaTraverse$1.exports;
  hasRequiredJsonSchemaTraverse$1 = 1;
  var traverse = jsonSchemaTraverse$1.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,
    if: true,
    then: true,
    else: true
  };
  traverse.arrayKeywords = {
    items: true,
    allOf: true,
    anyOf: true,
    oneOf: true
  };
  traverse.propsKeywords = {
    $defs: true,
    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 key in schema) {
        var sch = schema[key];
        if (Array.isArray(sch)) {
          if (key in traverse.arrayKeywords) {
            for (var i2 = 0; i2 < sch.length; i2++)
              _traverse(opts, pre, post, sch[i2], jsonPtr + "/" + key + "/" + i2, rootSchema, jsonPtr, key, schema, i2);
          }
        } else if (key in traverse.propsKeywords) {
          if (sch && typeof sch == "object") {
            for (var prop in sch)
              _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
          }
        } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
          _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
        }
      }
      post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    }
  }
  function escapeJsonPtr(str) {
    return str.replace(/~/g, "~0").replace(/\//g, "~1");
  }
  return jsonSchemaTraverse$1.exports;
}
var hasRequiredResolve$1;
function requireResolve$1() {
  if (hasRequiredResolve$1) return resolve$1;
  hasRequiredResolve$1 = 1;
  Object.defineProperty(resolve$1, "__esModule", { value: true });
  resolve$1.getSchemaRefs = resolve$1.resolveUrl = resolve$1.normalizeId = resolve$1._getFullPath = resolve$1.getFullPath = resolve$1.inlineRef = void 0;
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const equal2 = requireFastDeepEqual();
  const traverse = requireJsonSchemaTraverse$1();
  const SIMPLE_INLINED = /* @__PURE__ */ new Set([
    "type",
    "format",
    "pattern",
    "maxLength",
    "minLength",
    "maxProperties",
    "minProperties",
    "maxItems",
    "minItems",
    "maximum",
    "minimum",
    "uniqueItems",
    "multipleOf",
    "required",
    "enum",
    "const"
  ]);
  function inlineRef(schema, limit2 = true) {
    if (typeof schema == "boolean")
      return true;
    if (limit2 === true)
      return !hasRef(schema);
    if (!limit2)
      return false;
    return countKeys(schema) <= limit2;
  }
  resolve$1.inlineRef = inlineRef;
  const REF_KEYWORDS = /* @__PURE__ */ new Set([
    "$ref",
    "$recursiveRef",
    "$recursiveAnchor",
    "$dynamicRef",
    "$dynamicAnchor"
  ]);
  function hasRef(schema) {
    for (const key in schema) {
      if (REF_KEYWORDS.has(key))
        return true;
      const sch = schema[key];
      if (Array.isArray(sch) && sch.some(hasRef))
        return true;
      if (typeof sch == "object" && hasRef(sch))
        return true;
    }
    return false;
  }
  function countKeys(schema) {
    let count2 = 0;
    for (const key in schema) {
      if (key === "$ref")
        return Infinity;
      count2++;
      if (SIMPLE_INLINED.has(key))
        continue;
      if (typeof schema[key] == "object") {
        (0, util_1.eachItem)(schema[key], (sch) => count2 += countKeys(sch));
      }
      if (count2 === Infinity)
        return Infinity;
    }
    return count2;
  }
  function getFullPath(resolver, id2 = "", normalize) {
    if (normalize !== false)
      id2 = normalizeId(id2);
    const p2 = resolver.parse(id2);
    return _getFullPath(resolver, p2);
  }
  resolve$1.getFullPath = getFullPath;
  function _getFullPath(resolver, p2) {
    const serialized = resolver.serialize(p2);
    return serialized.split("#")[0] + "#";
  }
  resolve$1._getFullPath = _getFullPath;
  const TRAILING_SLASH_HASH = /#\/?$/;
  function normalizeId(id2) {
    return id2 ? id2.replace(TRAILING_SLASH_HASH, "") : "";
  }
  resolve$1.normalizeId = normalizeId;
  function resolveUrl(resolver, baseId, id2) {
    id2 = normalizeId(id2);
    return resolver.resolve(baseId, id2);
  }
  resolve$1.resolveUrl = resolveUrl;
  const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
  function getSchemaRefs(schema, baseId) {
    if (typeof schema == "boolean")
      return {};
    const { schemaId, uriResolver } = this.opts;
    const schId = normalizeId(schema[schemaId] || baseId);
    const baseIds = { "": schId };
    const pathPrefix = getFullPath(uriResolver, schId, false);
    const localRefs = {};
    const schemaRefs = /* @__PURE__ */ new Set();
    traverse(schema, { allKeys: true }, (sch, jsonPtr, _2, parentJsonPtr) => {
      if (parentJsonPtr === void 0)
        return;
      const fullPath = pathPrefix + jsonPtr;
      let innerBaseId = baseIds[parentJsonPtr];
      if (typeof sch[schemaId] == "string")
        innerBaseId = addRef.call(this, sch[schemaId]);
      addAnchor.call(this, sch.$anchor);
      addAnchor.call(this, sch.$dynamicAnchor);
      baseIds[jsonPtr] = innerBaseId;
      function addRef(ref2) {
        const _resolve = this.opts.uriResolver.resolve;
        ref2 = normalizeId(innerBaseId ? _resolve(innerBaseId, ref2) : ref2);
        if (schemaRefs.has(ref2))
          throw ambiguos(ref2);
        schemaRefs.add(ref2);
        let schOrRef = this.refs[ref2];
        if (typeof schOrRef == "string")
          schOrRef = this.refs[schOrRef];
        if (typeof schOrRef == "object") {
          checkAmbiguosRef(sch, schOrRef.schema, ref2);
        } else if (ref2 !== normalizeId(fullPath)) {
          if (ref2[0] === "#") {
            checkAmbiguosRef(sch, localRefs[ref2], ref2);
            localRefs[ref2] = sch;
          } else {
            this.refs[ref2] = fullPath;
          }
        }
        return ref2;
      }
      function addAnchor(anchor) {
        if (typeof anchor == "string") {
          if (!ANCHOR.test(anchor))
            throw new Error(`invalid anchor "${anchor}"`);
          addRef.call(this, `#${anchor}`);
        }
      }
    });
    return localRefs;
    function checkAmbiguosRef(sch1, sch2, ref2) {
      if (sch2 !== void 0 && !equal2(sch1, sch2))
        throw ambiguos(ref2);
    }
    function ambiguos(ref2) {
      return new Error(`reference "${ref2}" resolves to more than one schema`);
    }
  }
  resolve$1.getSchemaRefs = getSchemaRefs;
  return resolve$1;
}
var hasRequiredValidate$1;
function requireValidate$1() {
  if (hasRequiredValidate$1) return validate$1;
  hasRequiredValidate$1 = 1;
  Object.defineProperty(validate$1, "__esModule", { value: true });
  validate$1.getData = validate$1.KeywordCxt = validate$1.validateFunctionCode = void 0;
  const boolSchema_1 = /* @__PURE__ */ requireBoolSchema$1();
  const dataType_1 = /* @__PURE__ */ requireDataType$1();
  const applicability_1 = /* @__PURE__ */ requireApplicability$1();
  const dataType_2 = /* @__PURE__ */ requireDataType$1();
  const defaults_1 = /* @__PURE__ */ requireDefaults$1();
  const keyword_1 = /* @__PURE__ */ requireKeyword$1();
  const subschema_1 = /* @__PURE__ */ requireSubschema$1();
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const names_1 = /* @__PURE__ */ requireNames$1();
  const resolve_12 = /* @__PURE__ */ requireResolve$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const errors_1 = /* @__PURE__ */ requireErrors$1();
  function validateFunctionCode(it2) {
    if (isSchemaObj(it2)) {
      checkKeywords(it2);
      if (schemaCxtHasRules(it2)) {
        topSchemaObjCode(it2);
        return;
      }
    }
    validateFunction(it2, () => (0, boolSchema_1.topBoolOrEmptySchema)(it2));
  }
  validate$1.validateFunctionCode = validateFunctionCode;
  function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
    if (opts.code.es5) {
      gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
        gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
        destructureValCxtES5(gen, opts);
        gen.code(body);
      });
    } else {
      gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
    }
  }
  function destructureValCxt(opts) {
    return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
  }
  function destructureValCxtES5(gen, opts) {
    gen.if(names_1.default.valCxt, () => {
      gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);
      gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);
      gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
      gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);
      if (opts.dynamicRef)
        gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
    }, () => {
      gen.var(names_1.default.instancePath, (0, codegen_1._)`""`);
      gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`);
      gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`);
      gen.var(names_1.default.rootData, names_1.default.data);
      if (opts.dynamicRef)
        gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`);
    });
  }
  function topSchemaObjCode(it2) {
    const { schema, opts, gen } = it2;
    validateFunction(it2, () => {
      if (opts.$comment && schema.$comment)
        commentKeyword(it2);
      checkNoDefault(it2);
      gen.let(names_1.default.vErrors, null);
      gen.let(names_1.default.errors, 0);
      if (opts.unevaluated)
        resetEvaluated(it2);
      typeAndKeywords(it2);
      returnResults(it2);
    });
    return;
  }
  function resetEvaluated(it2) {
    const { gen, validateName } = it2;
    it2.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`);
    gen.if((0, codegen_1._)`${it2.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.props`, (0, codegen_1._)`undefined`));
    gen.if((0, codegen_1._)`${it2.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.items`, (0, codegen_1._)`undefined`));
  }
  function funcSourceUrl(schema, opts) {
    const schId = typeof schema == "object" && schema[opts.schemaId];
    return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil;
  }
  function subschemaCode(it2, valid) {
    if (isSchemaObj(it2)) {
      checkKeywords(it2);
      if (schemaCxtHasRules(it2)) {
        subSchemaObjCode(it2, valid);
        return;
      }
    }
    (0, boolSchema_1.boolOrEmptySchema)(it2, valid);
  }
  function schemaCxtHasRules({ schema, self: self2 }) {
    if (typeof schema == "boolean")
      return !schema;
    for (const key in schema)
      if (self2.RULES.all[key])
        return true;
    return false;
  }
  function isSchemaObj(it2) {
    return typeof it2.schema != "boolean";
  }
  function subSchemaObjCode(it2, valid) {
    const { schema, gen, opts } = it2;
    if (opts.$comment && schema.$comment)
      commentKeyword(it2);
    updateContext(it2);
    checkAsyncSchema(it2);
    const errsCount = gen.const("_errs", names_1.default.errors);
    typeAndKeywords(it2, errsCount);
    gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
  }
  function checkKeywords(it2) {
    (0, util_1.checkUnknownRules)(it2);
    checkRefsAndKeywords(it2);
  }
  function typeAndKeywords(it2, errsCount) {
    if (it2.opts.jtd)
      return schemaKeywords(it2, [], false, errsCount);
    const types2 = (0, dataType_1.getSchemaTypes)(it2.schema);
    const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it2, types2);
    schemaKeywords(it2, types2, !checkedTypes, errsCount);
  }
  function checkRefsAndKeywords(it2) {
    const { schema, errSchemaPath, opts, self: self2 } = it2;
    if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
      self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
    }
  }
  function checkNoDefault(it2) {
    const { schema, opts } = it2;
    if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
      (0, util_1.checkStrictMode)(it2, "default is ignored in the schema root");
    }
  }
  function updateContext(it2) {
    const schId = it2.schema[it2.opts.schemaId];
    if (schId)
      it2.baseId = (0, resolve_12.resolveUrl)(it2.opts.uriResolver, it2.baseId, schId);
  }
  function checkAsyncSchema(it2) {
    if (it2.schema.$async && !it2.schemaEnv.$async)
      throw new Error("async schema in sync schema");
  }
  function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
    const msg = schema.$comment;
    if (opts.$comment === true) {
      gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`);
    } else if (typeof opts.$comment == "function") {
      const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`;
      const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
      gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
    }
  }
  function returnResults(it2) {
    const { gen, schemaEnv, validateName, ValidationError, opts } = it2;
    if (schemaEnv.$async) {
      gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
    } else {
      gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);
      if (opts.unevaluated)
        assignEvaluated(it2);
      gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);
    }
  }
  function assignEvaluated({ gen, evaluated, props, items: items2 }) {
    if (props instanceof codegen_1.Name)
      gen.assign((0, codegen_1._)`${evaluated}.props`, props);
    if (items2 instanceof codegen_1.Name)
      gen.assign((0, codegen_1._)`${evaluated}.items`, items2);
  }
  function schemaKeywords(it2, types2, typeErrors, errsCount) {
    const { gen, schema, data: data2, allErrors, opts, self: self2 } = it2;
    const { RULES } = self2;
    if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
      gen.block(() => keywordCode(it2, "$ref", RULES.all.$ref.definition));
      return;
    }
    if (!opts.jtd)
      checkStrictTypes(it2, types2);
    gen.block(() => {
      for (const group of RULES.rules)
        groupKeywords(group);
      groupKeywords(RULES.post);
    });
    function groupKeywords(group) {
      if (!(0, applicability_1.shouldUseGroup)(schema, group))
        return;
      if (group.type) {
        gen.if((0, dataType_2.checkDataType)(group.type, data2, opts.strictNumbers));
        iterateKeywords(it2, group);
        if (types2.length === 1 && types2[0] === group.type && typeErrors) {
          gen.else();
          (0, dataType_2.reportTypeError)(it2);
        }
        gen.endIf();
      } else {
        iterateKeywords(it2, group);
      }
      if (!allErrors)
        gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
    }
  }
  function iterateKeywords(it2, group) {
    const { gen, schema, opts: { useDefaults } } = it2;
    if (useDefaults)
      (0, defaults_1.assignDefaults)(it2, group.type);
    gen.block(() => {
      for (const rule of group.rules) {
        if ((0, applicability_1.shouldUseRule)(schema, rule)) {
          keywordCode(it2, rule.keyword, rule.definition, group.type);
        }
      }
    });
  }
  function checkStrictTypes(it2, types2) {
    if (it2.schemaEnv.meta || !it2.opts.strictTypes)
      return;
    checkContextTypes(it2, types2);
    if (!it2.opts.allowUnionTypes)
      checkMultipleTypes(it2, types2);
    checkKeywordTypes(it2, it2.dataTypes);
  }
  function checkContextTypes(it2, types2) {
    if (!types2.length)
      return;
    if (!it2.dataTypes.length) {
      it2.dataTypes = types2;
      return;
    }
    types2.forEach((t2) => {
      if (!includesType(it2.dataTypes, t2)) {
        strictTypesError(it2, `type "${t2}" not allowed by context "${it2.dataTypes.join(",")}"`);
      }
    });
    narrowSchemaTypes(it2, types2);
  }
  function checkMultipleTypes(it2, ts2) {
    if (ts2.length > 1 && !(ts2.length === 2 && ts2.includes("null"))) {
      strictTypesError(it2, "use allowUnionTypes to allow union type keyword");
    }
  }
  function checkKeywordTypes(it2, ts2) {
    const rules2 = it2.self.RULES.all;
    for (const keyword2 in rules2) {
      const rule = rules2[keyword2];
      if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it2.schema, rule)) {
        const { type: type2 } = rule.definition;
        if (type2.length && !type2.some((t2) => hasApplicableType(ts2, t2))) {
          strictTypesError(it2, `missing type "${type2.join(",")}" for keyword "${keyword2}"`);
        }
      }
    }
  }
  function hasApplicableType(schTs, kwdT) {
    return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
  }
  function includesType(ts2, t2) {
    return ts2.includes(t2) || t2 === "integer" && ts2.includes("number");
  }
  function narrowSchemaTypes(it2, withTypes) {
    const ts2 = [];
    for (const t2 of it2.dataTypes) {
      if (includesType(withTypes, t2))
        ts2.push(t2);
      else if (withTypes.includes("integer") && t2 === "number")
        ts2.push("integer");
    }
    it2.dataTypes = ts2;
  }
  function strictTypesError(it2, msg) {
    const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath;
    msg += ` at "${schemaPath}" (strictTypes)`;
    (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictTypes);
  }
  class KeywordCxt {
    constructor(it2, def, keyword2) {
      (0, keyword_1.validateKeywordUsage)(it2, def, keyword2);
      this.gen = it2.gen;
      this.allErrors = it2.allErrors;
      this.keyword = keyword2;
      this.data = it2.data;
      this.schema = it2.schema[keyword2];
      this.$data = def.$data && it2.opts.$data && this.schema && this.schema.$data;
      this.schemaValue = (0, util_1.schemaRefOrVal)(it2, this.schema, keyword2, this.$data);
      this.schemaType = def.schemaType;
      this.parentSchema = it2.schema;
      this.params = {};
      this.it = it2;
      this.def = def;
      if (this.$data) {
        this.schemaCode = it2.gen.const("vSchema", getData(this.$data, it2));
      } else {
        this.schemaCode = this.schemaValue;
        if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
          throw new Error(`${keyword2} value must be ${JSON.stringify(def.schemaType)}`);
        }
      }
      if ("code" in def ? def.trackErrors : def.errors !== false) {
        this.errsCount = it2.gen.const("_errs", names_1.default.errors);
      }
    }
    result(condition, successAction, failAction) {
      this.failResult((0, codegen_1.not)(condition), successAction, failAction);
    }
    failResult(condition, successAction, failAction) {
      this.gen.if(condition);
      if (failAction)
        failAction();
      else
        this.error();
      if (successAction) {
        this.gen.else();
        successAction();
        if (this.allErrors)
          this.gen.endIf();
      } else {
        if (this.allErrors)
          this.gen.endIf();
        else
          this.gen.else();
      }
    }
    pass(condition, failAction) {
      this.failResult((0, codegen_1.not)(condition), void 0, failAction);
    }
    fail(condition) {
      if (condition === void 0) {
        this.error();
        if (!this.allErrors)
          this.gen.if(false);
        return;
      }
      this.gen.if(condition);
      this.error();
      if (this.allErrors)
        this.gen.endIf();
      else
        this.gen.else();
    }
    fail$data(condition) {
      if (!this.$data)
        return this.fail(condition);
      const { schemaCode } = this;
      this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
    }
    error(append, errorParams, errorPaths) {
      if (errorParams) {
        this.setParams(errorParams);
        this._error(append, errorPaths);
        this.setParams({});
        return;
      }
      this._error(append, errorPaths);
    }
    _error(append, errorPaths) {
      (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
    }
    $dataError() {
      (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
    }
    reset() {
      if (this.errsCount === void 0)
        throw new Error('add "trackErrors" to keyword definition');
      (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
    }
    ok(cond) {
      if (!this.allErrors)
        this.gen.if(cond);
    }
    setParams(obj, assign) {
      if (assign)
        Object.assign(this.params, obj);
      else
        this.params = obj;
    }
    block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
      this.gen.block(() => {
        this.check$data(valid, $dataValid);
        codeBlock();
      });
    }
    check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
      if (!this.$data)
        return;
      const { gen, schemaCode, schemaType, def } = this;
      gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));
      if (valid !== codegen_1.nil)
        gen.assign(valid, true);
      if (schemaType.length || def.validateSchema) {
        gen.elseIf(this.invalid$data());
        this.$dataError();
        if (valid !== codegen_1.nil)
          gen.assign(valid, false);
      }
      gen.else();
    }
    invalid$data() {
      const { gen, schemaCode, schemaType, def, it: it2 } = this;
      return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
      function wrong$DataType() {
        if (schemaType.length) {
          if (!(schemaCode instanceof codegen_1.Name))
            throw new Error("ajv implementation error");
          const st2 = Array.isArray(schemaType) ? schemaType : [schemaType];
          return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st2, schemaCode, it2.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
        }
        return codegen_1.nil;
      }
      function invalid$DataSchema() {
        if (def.validateSchema) {
          const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });
          return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;
        }
        return codegen_1.nil;
      }
    }
    subschema(appl, valid) {
      const subschema2 = (0, subschema_1.getSubschema)(this.it, appl);
      (0, subschema_1.extendSubschemaData)(subschema2, this.it, appl);
      (0, subschema_1.extendSubschemaMode)(subschema2, appl);
      const nextContext = { ...this.it, ...subschema2, items: void 0, props: void 0 };
      subschemaCode(nextContext, valid);
      return nextContext;
    }
    mergeEvaluated(schemaCxt, toName) {
      const { it: it2, gen } = this;
      if (!it2.opts.unevaluated)
        return;
      if (it2.props !== true && schemaCxt.props !== void 0) {
        it2.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it2.props, toName);
      }
      if (it2.items !== true && schemaCxt.items !== void 0) {
        it2.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it2.items, toName);
      }
    }
    mergeValidEvaluated(schemaCxt, valid) {
      const { it: it2, gen } = this;
      if (it2.opts.unevaluated && (it2.props !== true || it2.items !== true)) {
        gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
        return true;
      }
    }
  }
  validate$1.KeywordCxt = KeywordCxt;
  function keywordCode(it2, keyword2, def, ruleType) {
    const cxt = new KeywordCxt(it2, def, keyword2);
    if ("code" in def) {
      def.code(cxt, ruleType);
    } else if (cxt.$data && def.validate) {
      (0, keyword_1.funcKeywordCode)(cxt, def);
    } else if ("macro" in def) {
      (0, keyword_1.macroKeywordCode)(cxt, def);
    } else if (def.compile || def.validate) {
      (0, keyword_1.funcKeywordCode)(cxt, def);
    }
  }
  const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
  const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
  function getData($data, { dataLevel, dataNames, dataPathArr }) {
    let jsonPointer;
    let data2;
    if ($data === "")
      return names_1.default.rootData;
    if ($data[0] === "/") {
      if (!JSON_POINTER.test($data))
        throw new Error(`Invalid JSON-pointer: ${$data}`);
      jsonPointer = $data;
      data2 = names_1.default.rootData;
    } else {
      const matches = RELATIVE_JSON_POINTER.exec($data);
      if (!matches)
        throw new Error(`Invalid JSON-pointer: ${$data}`);
      const up2 = +matches[1];
      jsonPointer = matches[2];
      if (jsonPointer === "#") {
        if (up2 >= dataLevel)
          throw new Error(errorMsg("property/index", up2));
        return dataPathArr[dataLevel - up2];
      }
      if (up2 > dataLevel)
        throw new Error(errorMsg("data", up2));
      data2 = dataNames[dataLevel - up2];
      if (!jsonPointer)
        return data2;
    }
    let expr = data2;
    const segments = jsonPointer.split("/");
    for (const segment of segments) {
      if (segment) {
        data2 = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
        expr = (0, codegen_1._)`${expr} && ${data2}`;
      }
    }
    return expr;
    function errorMsg(pointerType, up2) {
      return `Cannot access ${pointerType} ${up2} levels up, current level is ${dataLevel}`;
    }
  }
  validate$1.getData = getData;
  return validate$1;
}
var validation_error$1 = {};
var hasRequiredValidation_error$1;
function requireValidation_error$1() {
  if (hasRequiredValidation_error$1) return validation_error$1;
  hasRequiredValidation_error$1 = 1;
  Object.defineProperty(validation_error$1, "__esModule", { value: true });
  class ValidationError extends Error {
    constructor(errors2) {
      super("validation failed");
      this.errors = errors2;
      this.ajv = this.validation = true;
    }
  }
  validation_error$1.default = ValidationError;
  return validation_error$1;
}
var ref_error$1 = {};
var hasRequiredRef_error$1;
function requireRef_error$1() {
  if (hasRequiredRef_error$1) return ref_error$1;
  hasRequiredRef_error$1 = 1;
  Object.defineProperty(ref_error$1, "__esModule", { value: true });
  const resolve_12 = /* @__PURE__ */ requireResolve$1();
  class MissingRefError extends Error {
    constructor(resolver, baseId, ref2, msg) {
      super(msg || `can't resolve reference ${ref2} from id ${baseId}`);
      this.missingRef = (0, resolve_12.resolveUrl)(resolver, baseId, ref2);
      this.missingSchema = (0, resolve_12.normalizeId)((0, resolve_12.getFullPath)(resolver, this.missingRef));
    }
  }
  ref_error$1.default = MissingRefError;
  return ref_error$1;
}
var compile$1 = {};
var hasRequiredCompile$1;
function requireCompile$1() {
  if (hasRequiredCompile$1) return compile$1;
  hasRequiredCompile$1 = 1;
  Object.defineProperty(compile$1, "__esModule", { value: true });
  compile$1.resolveSchema = compile$1.getCompilingSchema = compile$1.resolveRef = compile$1.compileSchema = compile$1.SchemaEnv = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const validation_error_1 = /* @__PURE__ */ requireValidation_error$1();
  const names_1 = /* @__PURE__ */ requireNames$1();
  const resolve_12 = /* @__PURE__ */ requireResolve$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const validate_1 = /* @__PURE__ */ requireValidate$1();
  class SchemaEnv {
    constructor(env) {
      var _a2;
      this.refs = {};
      this.dynamicAnchors = {};
      let schema;
      if (typeof env.schema == "object")
        schema = env.schema;
      this.schema = env.schema;
      this.schemaId = env.schemaId;
      this.root = env.root || this;
      this.baseId = (_a2 = env.baseId) !== null && _a2 !== void 0 ? _a2 : (0, resolve_12.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
      this.schemaPath = env.schemaPath;
      this.localRefs = env.localRefs;
      this.meta = env.meta;
      this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
      this.refs = {};
    }
  }
  compile$1.SchemaEnv = SchemaEnv;
  function compileSchema(sch) {
    const _sch = getCompilingSchema.call(this, sch);
    if (_sch)
      return _sch;
    const rootId = (0, resolve_12.getFullPath)(this.opts.uriResolver, sch.root.baseId);
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    let _ValidationError;
    if (sch.$async) {
      _ValidationError = gen.scopeValue("Error", {
        ref: validation_error_1.default,
        code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default`
      });
    }
    const validateName = gen.scopeName("validate");
    sch.validateName = validateName;
    const schemaCxt = {
      gen,
      allErrors: this.opts.allErrors,
      data: names_1.default.data,
      parentData: names_1.default.parentData,
      parentDataProperty: names_1.default.parentDataProperty,
      dataNames: [names_1.default.data],
      dataPathArr: [codegen_1.nil],
      // TODO can its length be used as dataLevel if nil is removed?
      dataLevel: 0,
      dataTypes: [],
      definedProperties: /* @__PURE__ */ new Set(),
      topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }),
      validateName,
      ValidationError: _ValidationError,
      schema: sch.schema,
      schemaEnv: sch,
      rootId,
      baseId: sch.baseId || rootId,
      schemaPath: codegen_1.nil,
      errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
      errorPath: (0, codegen_1._)`""`,
      opts: this.opts,
      self: this
    };
    let sourceCode;
    try {
      this._compilations.add(sch);
      (0, validate_1.validateFunctionCode)(schemaCxt);
      gen.optimize(this.opts.code.optimize);
      const validateCode = gen.toString();
      sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
      if (this.opts.code.process)
        sourceCode = this.opts.code.process(sourceCode, sch);
      const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
      const validate2 = makeValidate(this, this.scope.get());
      this.scope.value(validateName, { ref: validate2 });
      validate2.errors = null;
      validate2.schema = sch.schema;
      validate2.schemaEnv = sch;
      if (sch.$async)
        validate2.$async = true;
      if (this.opts.code.source === true) {
        validate2.source = { validateName, validateCode, scopeValues: gen._values };
      }
      if (this.opts.unevaluated) {
        const { props, items: items2 } = schemaCxt;
        validate2.evaluated = {
          props: props instanceof codegen_1.Name ? void 0 : props,
          items: items2 instanceof codegen_1.Name ? void 0 : items2,
          dynamicProps: props instanceof codegen_1.Name,
          dynamicItems: items2 instanceof codegen_1.Name
        };
        if (validate2.source)
          validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated);
      }
      sch.validate = validate2;
      return sch;
    } catch (e2) {
      delete sch.validate;
      delete sch.validateName;
      if (sourceCode)
        this.logger.error("Error compiling schema, function code:", sourceCode);
      throw e2;
    } finally {
      this._compilations.delete(sch);
    }
  }
  compile$1.compileSchema = compileSchema;
  function resolveRef2(root, baseId, ref2) {
    var _a2;
    ref2 = (0, resolve_12.resolveUrl)(this.opts.uriResolver, baseId, ref2);
    const schOrFunc = root.refs[ref2];
    if (schOrFunc)
      return schOrFunc;
    let _sch = resolve2.call(this, root, ref2);
    if (_sch === void 0) {
      const schema = (_a2 = root.localRefs) === null || _a2 === void 0 ? void 0 : _a2[ref2];
      const { schemaId } = this.opts;
      if (schema)
        _sch = new SchemaEnv({ schema, schemaId, root, baseId });
    }
    if (_sch === void 0)
      return;
    return root.refs[ref2] = inlineOrCompile.call(this, _sch);
  }
  compile$1.resolveRef = resolveRef2;
  function inlineOrCompile(sch) {
    if ((0, resolve_12.inlineRef)(sch.schema, this.opts.inlineRefs))
      return sch.schema;
    return sch.validate ? sch : compileSchema.call(this, sch);
  }
  function getCompilingSchema(schEnv) {
    for (const sch of this._compilations) {
      if (sameSchemaEnv(sch, schEnv))
        return sch;
    }
  }
  compile$1.getCompilingSchema = getCompilingSchema;
  function sameSchemaEnv(s1, s2) {
    return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
  }
  function resolve2(root, ref2) {
    let sch;
    while (typeof (sch = this.refs[ref2]) == "string")
      ref2 = sch;
    return sch || this.schemas[ref2] || resolveSchema.call(this, root, ref2);
  }
  function resolveSchema(root, ref2) {
    const p2 = this.opts.uriResolver.parse(ref2);
    const refPath = (0, resolve_12._getFullPath)(this.opts.uriResolver, p2);
    let baseId = (0, resolve_12.getFullPath)(this.opts.uriResolver, root.baseId, void 0);
    if (Object.keys(root.schema).length > 0 && refPath === baseId) {
      return getJsonPointer.call(this, p2, root);
    }
    const id2 = (0, resolve_12.normalizeId)(refPath);
    const schOrRef = this.refs[id2] || this.schemas[id2];
    if (typeof schOrRef == "string") {
      const sch = resolveSchema.call(this, root, schOrRef);
      if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
        return;
      return getJsonPointer.call(this, p2, sch);
    }
    if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
      return;
    if (!schOrRef.validate)
      compileSchema.call(this, schOrRef);
    if (id2 === (0, resolve_12.normalizeId)(ref2)) {
      const { schema } = schOrRef;
      const { schemaId } = this.opts;
      const schId = schema[schemaId];
      if (schId)
        baseId = (0, resolve_12.resolveUrl)(this.opts.uriResolver, baseId, schId);
      return new SchemaEnv({ schema, schemaId, root, baseId });
    }
    return getJsonPointer.call(this, p2, schOrRef);
  }
  compile$1.resolveSchema = resolveSchema;
  const PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
    "properties",
    "patternProperties",
    "enum",
    "dependencies",
    "definitions"
  ]);
  function getJsonPointer(parsedRef, { baseId, schema, root }) {
    var _a2;
    if (((_a2 = parsedRef.fragment) === null || _a2 === void 0 ? void 0 : _a2[0]) !== "/")
      return;
    for (const part of parsedRef.fragment.slice(1).split("/")) {
      if (typeof schema === "boolean")
        return;
      const partSchema = schema[(0, util_1.unescapeFragment)(part)];
      if (partSchema === void 0)
        return;
      schema = partSchema;
      const schId = typeof schema === "object" && schema[this.opts.schemaId];
      if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
        baseId = (0, resolve_12.resolveUrl)(this.opts.uriResolver, baseId, schId);
      }
    }
    let env;
    if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
      const $ref = (0, resolve_12.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
      env = resolveSchema.call(this, root, $ref);
    }
    const { schemaId } = this.opts;
    env = env || new SchemaEnv({ schema, schemaId, root, baseId });
    if (env.schema !== env.root.schema)
      return env;
    return void 0;
  }
  return compile$1;
}
const $id$3 = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#";
const description$1 = "Meta-schema for $data reference (JSON AnySchema extension proposal)";
const type$3 = "object";
const required$3 = ["$data"];
const properties$5 = { "$data": { "type": "string", "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] } };
const additionalProperties$3 = false;
const require$$9$1 = {
  $id: $id$3,
  description: description$1,
  type: type$3,
  required: required$3,
  properties: properties$5,
  additionalProperties: additionalProperties$3
};
var uri$1 = {};
var fastUri = { exports: {} };
var utils;
var hasRequiredUtils;
function requireUtils() {
  if (hasRequiredUtils) return utils;
  hasRequiredUtils = 1;
  const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
  const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
  const isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
  const isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);
  const isPathCharacter = RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);
  function stringArrayToHexStripped(input) {
    let acc = "";
    let code2 = 0;
    let i2 = 0;
    for (i2 = 0; i2 < input.length; i2++) {
      code2 = input[i2].charCodeAt(0);
      if (code2 === 48) {
        continue;
      }
      if (!(code2 >= 48 && code2 <= 57 || code2 >= 65 && code2 <= 70 || code2 >= 97 && code2 <= 102)) {
        return "";
      }
      acc += input[i2];
      break;
    }
    for (i2 += 1; i2 < input.length; i2++) {
      code2 = input[i2].charCodeAt(0);
      if (!(code2 >= 48 && code2 <= 57 || code2 >= 65 && code2 <= 70 || code2 >= 97 && code2 <= 102)) {
        return "";
      }
      acc += input[i2];
    }
    return acc;
  }
  const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
  function consumeIsZone(buffer) {
    buffer.length = 0;
    return true;
  }
  function consumeHextets(buffer, address, output) {
    if (buffer.length) {
      const hex = stringArrayToHexStripped(buffer);
      if (hex !== "") {
        address.push(hex);
      } else {
        output.error = true;
        return false;
      }
      buffer.length = 0;
    }
    return true;
  }
  function getIPV6(input) {
    let tokenCount = 0;
    const output = { error: false, address: "", zone: "" };
    const address = [];
    const buffer = [];
    let endipv6Encountered = false;
    let endIpv6 = false;
    let consume = consumeHextets;
    for (let i2 = 0; i2 < input.length; i2++) {
      const cursor = input[i2];
      if (cursor === "[" || cursor === "]") {
        continue;
      }
      if (cursor === ":") {
        if (endipv6Encountered === true) {
          endIpv6 = true;
        }
        if (!consume(buffer, address, output)) {
          break;
        }
        if (++tokenCount > 7) {
          output.error = true;
          break;
        }
        if (i2 > 0 && input[i2 - 1] === ":") {
          endipv6Encountered = true;
        }
        address.push(":");
        continue;
      } else if (cursor === "%") {
        if (!consume(buffer, address, output)) {
          break;
        }
        consume = consumeIsZone;
      } else {
        buffer.push(cursor);
        continue;
      }
    }
    if (buffer.length) {
      if (consume === consumeIsZone) {
        output.zone = buffer.join("");
      } else if (endIpv6) {
        address.push(buffer.join(""));
      } else {
        address.push(stringArrayToHexStripped(buffer));
      }
    }
    output.address = address.join("");
    return output;
  }
  function normalizeIPv6(host) {
    if (findToken(host, ":") < 2) {
      return { host, isIPV6: false };
    }
    const ipv62 = getIPV6(host);
    if (!ipv62.error) {
      let newHost = ipv62.address;
      let escapedHost = ipv62.address;
      if (ipv62.zone) {
        newHost += "%" + ipv62.zone;
        escapedHost += "%25" + ipv62.zone;
      }
      return { host: newHost, isIPV6: true, escapedHost };
    } else {
      return { host, isIPV6: false };
    }
  }
  function findToken(str, token) {
    let ind = 0;
    for (let i2 = 0; i2 < str.length; i2++) {
      if (str[i2] === token) ind++;
    }
    return ind;
  }
  function removeDotSegments(path) {
    let input = path;
    const output = [];
    let nextSlash = -1;
    let len = 0;
    while (len = input.length) {
      if (len === 1) {
        if (input === ".") {
          break;
        } else if (input === "/") {
          output.push("/");
          break;
        } else {
          output.push(input);
          break;
        }
      } else if (len === 2) {
        if (input[0] === ".") {
          if (input[1] === ".") {
            break;
          } else if (input[1] === "/") {
            input = input.slice(2);
            continue;
          }
        } else if (input[0] === "/") {
          if (input[1] === "." || input[1] === "/") {
            output.push("/");
            break;
          }
        }
      } else if (len === 3) {
        if (input === "/..") {
          if (output.length !== 0) {
            output.pop();
          }
          output.push("/");
          break;
        }
      }
      if (input[0] === ".") {
        if (input[1] === ".") {
          if (input[2] === "/") {
            input = input.slice(3);
            continue;
          }
        } else if (input[1] === "/") {
          input = input.slice(2);
          continue;
        }
      } else if (input[0] === "/") {
        if (input[1] === ".") {
          if (input[2] === "/") {
            input = input.slice(2);
            continue;
          } else if (input[2] === ".") {
            if (input[3] === "/") {
              input = input.slice(3);
              if (output.length !== 0) {
                output.pop();
              }
              continue;
            }
          }
        }
      }
      if ((nextSlash = input.indexOf("/", 1)) === -1) {
        output.push(input);
        break;
      } else {
        output.push(input.slice(0, nextSlash));
        input = input.slice(nextSlash);
      }
    }
    return output.join("");
  }
  const HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" };
  const HOST_DELIM_RE = /[@/?#:]/g;
  const HOST_DELIM_NO_COLON_RE = /[@/?#]/g;
  function reescapeHostDelimiters(host, isIP) {
    const re2 = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE;
    re2.lastIndex = 0;
    return host.replace(re2, (ch) => HOST_DELIMS[ch]);
  }
  function normalizePercentEncoding(input, decodeUnreserved = false) {
    if (input.indexOf("%") === -1) {
      return input;
    }
    let output = "";
    for (let i2 = 0; i2 < input.length; i2++) {
      if (input[i2] === "%" && i2 + 2 < input.length) {
        const hex = input.slice(i2 + 1, i2 + 3);
        if (isHexPair(hex)) {
          const normalizedHex = hex.toUpperCase();
          const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
          if (decodeUnreserved && isUnreserved(decoded)) {
            output += decoded;
          } else {
            output += "%" + normalizedHex;
          }
          i2 += 2;
          continue;
        }
      }
      output += input[i2];
    }
    return output;
  }
  function normalizePathEncoding(input) {
    let output = "";
    for (let i2 = 0; i2 < input.length; i2++) {
      if (input[i2] === "%" && i2 + 2 < input.length) {
        const hex = input.slice(i2 + 1, i2 + 3);
        if (isHexPair(hex)) {
          const normalizedHex = hex.toUpperCase();
          const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
          if (decoded !== "." && isUnreserved(decoded)) {
            output += decoded;
          } else {
            output += "%" + normalizedHex;
          }
          i2 += 2;
          continue;
        }
      }
      if (isPathCharacter(input[i2])) {
        output += input[i2];
      } else {
        output += escape(input[i2]);
      }
    }
    return output;
  }
  function escapePreservingEscapes(input) {
    let output = "";
    for (let i2 = 0; i2 < input.length; i2++) {
      if (input[i2] === "%" && i2 + 2 < input.length) {
        const hex = input.slice(i2 + 1, i2 + 3);
        if (isHexPair(hex)) {
          output += "%" + hex.toUpperCase();
          i2 += 2;
          continue;
        }
      }
      output += escape(input[i2]);
    }
    return output;
  }
  function recomposeAuthority(component) {
    const uriTokens = [];
    if (component.userinfo !== void 0) {
      uriTokens.push(component.userinfo);
      uriTokens.push("@");
    }
    if (component.host !== void 0) {
      let host = unescape(component.host);
      if (!isIPv4(host)) {
        const ipV6res = normalizeIPv6(host);
        if (ipV6res.isIPV6 === true) {
          host = `[${ipV6res.escapedHost}]`;
        } else {
          host = reescapeHostDelimiters(host, false);
        }
      }
      uriTokens.push(host);
    }
    if (typeof component.port === "number" || typeof component.port === "string") {
      uriTokens.push(":");
      uriTokens.push(String(component.port));
    }
    return uriTokens.length ? uriTokens.join("") : void 0;
  }
  utils = {
    nonSimpleDomain,
    recomposeAuthority,
    reescapeHostDelimiters,
    normalizePercentEncoding,
    normalizePathEncoding,
    escapePreservingEscapes,
    removeDotSegments,
    isIPv4,
    isUUID,
    normalizeIPv6,
    stringArrayToHexStripped
  };
  return utils;
}
var schemes;
var hasRequiredSchemes;
function requireSchemes() {
  if (hasRequiredSchemes) return schemes;
  hasRequiredSchemes = 1;
  const { isUUID } = requireUtils();
  const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
  const supportedSchemeNames = (
    /** @type {const} */
    [
      "http",
      "https",
      "ws",
      "wss",
      "urn",
      "urn:uuid"
    ]
  );
  function isValidSchemeName(name2) {
    return supportedSchemeNames.indexOf(
      /** @type {*} */
      name2
    ) !== -1;
  }
  function wsIsSecure(wsComponent) {
    if (wsComponent.secure === true) {
      return true;
    } else if (wsComponent.secure === false) {
      return false;
    } else if (wsComponent.scheme) {
      return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S");
    } else {
      return false;
    }
  }
  function httpParse(component) {
    if (!component.host) {
      component.error = component.error || "HTTP URIs must have a host.";
    }
    return component;
  }
  function httpSerialize(component) {
    const secure = String(component.scheme).toLowerCase() === "https";
    if (component.port === (secure ? 443 : 80) || component.port === "") {
      component.port = void 0;
    }
    if (!component.path) {
      component.path = "/";
    }
    return component;
  }
  function wsParse(wsComponent) {
    wsComponent.secure = wsIsSecure(wsComponent);
    wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : "");
    wsComponent.path = void 0;
    wsComponent.query = void 0;
    return wsComponent;
  }
  function wsSerialize(wsComponent) {
    if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") {
      wsComponent.port = void 0;
    }
    if (typeof wsComponent.secure === "boolean") {
      wsComponent.scheme = wsComponent.secure ? "wss" : "ws";
      wsComponent.secure = void 0;
    }
    if (wsComponent.resourceName) {
      const [path, query] = wsComponent.resourceName.split("?");
      wsComponent.path = path && path !== "/" ? path : void 0;
      wsComponent.query = query;
      wsComponent.resourceName = void 0;
    }
    wsComponent.fragment = void 0;
    return wsComponent;
  }
  function urnParse(urnComponent, options) {
    if (!urnComponent.path) {
      urnComponent.error = "URN can not be parsed";
      return urnComponent;
    }
    const matches = urnComponent.path.match(URN_REG);
    if (matches) {
      const scheme = options.scheme || urnComponent.scheme || "urn";
      urnComponent.nid = matches[1].toLowerCase();
      urnComponent.nss = matches[2];
      const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`;
      const schemeHandler = getSchemeHandler(urnScheme);
      urnComponent.path = void 0;
      if (schemeHandler) {
        urnComponent = schemeHandler.parse(urnComponent, options);
      }
    } else {
      urnComponent.error = urnComponent.error || "URN can not be parsed.";
    }
    return urnComponent;
  }
  function urnSerialize(urnComponent, options) {
    if (urnComponent.nid === void 0) {
      throw new Error("URN without nid cannot be serialized");
    }
    const scheme = options.scheme || urnComponent.scheme || "urn";
    const nid = urnComponent.nid.toLowerCase();
    const urnScheme = `${scheme}:${options.nid || nid}`;
    const schemeHandler = getSchemeHandler(urnScheme);
    if (schemeHandler) {
      urnComponent = schemeHandler.serialize(urnComponent, options);
    }
    const uriComponent = urnComponent;
    const nss = urnComponent.nss;
    uriComponent.path = `${nid || options.nid}:${nss}`;
    options.skipEscape = true;
    return uriComponent;
  }
  function urnuuidParse(urnComponent, options) {
    const uuidComponent = urnComponent;
    uuidComponent.uuid = uuidComponent.nss;
    uuidComponent.nss = void 0;
    if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {
      uuidComponent.error = uuidComponent.error || "UUID is not valid.";
    }
    return uuidComponent;
  }
  function urnuuidSerialize(uuidComponent) {
    const urnComponent = uuidComponent;
    urnComponent.nss = (uuidComponent.uuid || "").toLowerCase();
    return urnComponent;
  }
  const http = (
    /** @type {SchemeHandler} */
    {
      scheme: "http",
      domainHost: true,
      parse: httpParse,
      serialize: httpSerialize
    }
  );
  const https = (
    /** @type {SchemeHandler} */
    {
      scheme: "https",
      domainHost: http.domainHost,
      parse: httpParse,
      serialize: httpSerialize
    }
  );
  const ws2 = (
    /** @type {SchemeHandler} */
    {
      scheme: "ws",
      domainHost: true,
      parse: wsParse,
      serialize: wsSerialize
    }
  );
  const wss = (
    /** @type {SchemeHandler} */
    {
      scheme: "wss",
      domainHost: ws2.domainHost,
      parse: ws2.parse,
      serialize: ws2.serialize
    }
  );
  const urn = (
    /** @type {SchemeHandler} */
    {
      scheme: "urn",
      parse: urnParse,
      serialize: urnSerialize,
      skipNormalize: true
    }
  );
  const urnuuid = (
    /** @type {SchemeHandler} */
    {
      scheme: "urn:uuid",
      parse: urnuuidParse,
      serialize: urnuuidSerialize,
      skipNormalize: true
    }
  );
  const SCHEMES = (
    /** @type {Record<SchemeName, SchemeHandler>} */
    {
      http,
      https,
      ws: ws2,
      wss,
      urn,
      "urn:uuid": urnuuid
    }
  );
  Object.setPrototypeOf(SCHEMES, null);
  function getSchemeHandler(scheme) {
    return scheme && (SCHEMES[
      /** @type {SchemeName} */
      scheme
    ] || SCHEMES[
      /** @type {SchemeName} */
      scheme.toLowerCase()
    ]) || void 0;
  }
  schemes = {
    wsIsSecure,
    SCHEMES,
    isValidSchemeName,
    getSchemeHandler
  };
  return schemes;
}
var hasRequiredFastUri;
function requireFastUri() {
  if (hasRequiredFastUri) return fastUri.exports;
  hasRequiredFastUri = 1;
  const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = requireUtils();
  const { SCHEMES, getSchemeHandler } = requireSchemes();
  function normalize(uri2, options) {
    if (typeof uri2 === "string") {
      uri2 = /** @type {T} */
      normalizeString(uri2, options);
    } else if (typeof uri2 === "object") {
      uri2 = /** @type {T} */
      parse2(serialize(uri2, options), options);
    }
    return uri2;
  }
  function resolve2(baseURI, relativeURI, options) {
    const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
    const resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true);
    schemelessOptions.skipEscape = true;
    return serialize(resolved, schemelessOptions);
  }
  function resolveComponent(base, relative, options, skipNormalization) {
    const target = {};
    if (!skipNormalization) {
      base = parse2(serialize(base, options), options);
      relative = parse2(serialize(relative, options), options);
    }
    options = options || {};
    if (!options.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 = base.path;
          if (relative.query !== void 0) {
            target.query = relative.query;
          } else {
            target.query = base.query;
          }
        } else {
          if (relative.path[0] === "/") {
            target.path = removeDotSegments(relative.path);
          } else {
            if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
              target.path = "/" + relative.path;
            } else if (!base.path) {
              target.path = relative.path;
            } else {
              target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
            }
            target.path = removeDotSegments(target.path);
          }
          target.query = relative.query;
        }
        target.userinfo = base.userinfo;
        target.host = base.host;
        target.port = base.port;
      }
      target.scheme = base.scheme;
    }
    target.fragment = relative.fragment;
    return target;
  }
  function equal2(uriA, uriB, options) {
    const normalizedA = normalizeComparableURI(uriA, options);
    const normalizedB = normalizeComparableURI(uriB, options);
    return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA.toLowerCase() === normalizedB.toLowerCase();
  }
  function serialize(cmpts, opts) {
    const component = {
      host: cmpts.host,
      scheme: cmpts.scheme,
      userinfo: cmpts.userinfo,
      port: cmpts.port,
      path: cmpts.path,
      query: cmpts.query,
      nid: cmpts.nid,
      nss: cmpts.nss,
      uuid: cmpts.uuid,
      fragment: cmpts.fragment,
      reference: cmpts.reference,
      resourceName: cmpts.resourceName,
      secure: cmpts.secure,
      error: ""
    };
    const options = Object.assign({}, opts);
    const uriTokens = [];
    const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
    if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
    if (component.path !== void 0) {
      if (!options.skipEscape) {
        component.path = escapePreservingEscapes(component.path);
        if (component.scheme !== void 0) {
          component.path = component.path.split("%3A").join(":");
        }
      } else {
        component.path = normalizePercentEncoding(component.path);
      }
    }
    if (options.reference !== "suffix" && component.scheme) {
      uriTokens.push(component.scheme, ":");
    }
    const authority = recomposeAuthority(component);
    if (authority !== void 0) {
      if (options.reference !== "suffix") {
        uriTokens.push("//");
      }
      uriTokens.push(authority);
      if (component.path && component.path[0] !== "/") {
        uriTokens.push("/");
      }
    }
    if (component.path !== void 0) {
      let s2 = component.path;
      if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
        s2 = removeDotSegments(s2);
      }
      if (authority === void 0 && s2[0] === "/" && s2[1] === "/") {
        s2 = "/%2F" + s2.slice(2);
      }
      uriTokens.push(s2);
    }
    if (component.query !== void 0) {
      uriTokens.push("?", component.query);
    }
    if (component.fragment !== void 0) {
      uriTokens.push("#", component.fragment);
    }
    return uriTokens.join("");
  }
  const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
  function getParseError(parsed, matches) {
    if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") {
      return 'URI path must start with "/" when authority is present.';
    }
    if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) {
      return "URI port is malformed.";
    }
    return void 0;
  }
  function parseWithStatus(uri2, opts) {
    const options = Object.assign({}, opts);
    const parsed = {
      scheme: void 0,
      userinfo: void 0,
      host: "",
      port: void 0,
      path: "",
      query: void 0,
      fragment: void 0
    };
    let malformedAuthorityOrPort = false;
    let isIP = false;
    if (options.reference === "suffix") {
      if (options.scheme) {
        uri2 = options.scheme + ":" + uri2;
      } else {
        uri2 = "//" + uri2;
      }
    }
    const matches = uri2.match(URI_PARSE);
    if (matches) {
      parsed.scheme = matches[1];
      parsed.userinfo = matches[3];
      parsed.host = matches[4];
      parsed.port = parseInt(matches[5], 10);
      parsed.path = matches[6] || "";
      parsed.query = matches[7];
      parsed.fragment = matches[8];
      if (isNaN(parsed.port)) {
        parsed.port = matches[5];
      }
      const parseError = getParseError(parsed, matches);
      if (parseError !== void 0) {
        parsed.error = parsed.error || parseError;
        malformedAuthorityOrPort = true;
      }
      if (parsed.host) {
        const ipv4result = isIPv4(parsed.host);
        if (ipv4result === false) {
          const ipv6result = normalizeIPv6(parsed.host);
          parsed.host = ipv6result.host.toLowerCase();
          isIP = ipv6result.isIPV6;
        } else {
          isIP = true;
        }
      }
      if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) {
        parsed.reference = "same-document";
      } else if (parsed.scheme === void 0) {
        parsed.reference = "relative";
      } else if (parsed.fragment === void 0) {
        parsed.reference = "absolute";
      } else {
        parsed.reference = "uri";
      }
      if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) {
        parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";
      }
      const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
      if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
        if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
          try {
            parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
          } catch (e2) {
            parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e2;
          }
        }
      }
      if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
        if (uri2.indexOf("%") !== -1) {
          if (parsed.scheme !== void 0) {
            parsed.scheme = unescape(parsed.scheme);
          }
          if (parsed.host !== void 0) {
            parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP);
          }
        }
        if (parsed.path) {
          parsed.path = normalizePathEncoding(parsed.path);
        }
        if (parsed.fragment) {
          try {
            parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
          } catch {
            parsed.error = parsed.error || "URI malformed";
          }
        }
      }
      if (schemeHandler && schemeHandler.parse) {
        schemeHandler.parse(parsed, options);
      }
    } else {
      parsed.error = parsed.error || "URI can not be parsed.";
    }
    return { parsed, malformedAuthorityOrPort };
  }
  function parse2(uri2, opts) {
    return parseWithStatus(uri2, opts).parsed;
  }
  function normalizeString(uri2, opts) {
    return normalizeStringWithStatus(uri2, opts).normalized;
  }
  function normalizeStringWithStatus(uri2, opts) {
    const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri2, opts);
    return {
      normalized: malformedAuthorityOrPort ? uri2 : serialize(parsed, opts),
      malformedAuthorityOrPort
    };
  }
  function normalizeComparableURI(uri2, opts) {
    if (typeof uri2 === "string") {
      const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri2, opts);
      return malformedAuthorityOrPort ? void 0 : normalized;
    }
    if (typeof uri2 === "object") {
      return serialize(uri2, opts);
    }
  }
  const fastUri$1 = {
    SCHEMES,
    normalize,
    resolve: resolve2,
    resolveComponent,
    equal: equal2,
    serialize,
    parse: parse2
  };
  fastUri.exports = fastUri$1;
  fastUri.exports.default = fastUri$1;
  fastUri.exports.fastUri = fastUri$1;
  return fastUri.exports;
}
var hasRequiredUri$1;
function requireUri$1() {
  if (hasRequiredUri$1) return uri$1;
  hasRequiredUri$1 = 1;
  Object.defineProperty(uri$1, "__esModule", { value: true });
  const uri2 = requireFastUri();
  uri2.code = 'require("ajv/dist/runtime/uri").default';
  uri$1.default = uri2;
  return uri$1;
}
var hasRequiredCore$3;
function requireCore$3() {
  if (hasRequiredCore$3) return core$3;
  hasRequiredCore$3 = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
    var validate_1 = /* @__PURE__ */ requireValidate$1();
    Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
      return validate_1.KeywordCxt;
    } });
    var codegen_1 = /* @__PURE__ */ requireCodegen$1();
    Object.defineProperty(exports, "_", { enumerable: true, get: function() {
      return codegen_1._;
    } });
    Object.defineProperty(exports, "str", { enumerable: true, get: function() {
      return codegen_1.str;
    } });
    Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
      return codegen_1.stringify;
    } });
    Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
      return codegen_1.nil;
    } });
    Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
      return codegen_1.Name;
    } });
    Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
      return codegen_1.CodeGen;
    } });
    const validation_error_1 = /* @__PURE__ */ requireValidation_error$1();
    const ref_error_1 = /* @__PURE__ */ requireRef_error$1();
    const rules_1 = /* @__PURE__ */ requireRules$1();
    const compile_12 = /* @__PURE__ */ requireCompile$1();
    const codegen_2 = /* @__PURE__ */ requireCodegen$1();
    const resolve_12 = /* @__PURE__ */ requireResolve$1();
    const dataType_1 = /* @__PURE__ */ requireDataType$1();
    const util_1 = /* @__PURE__ */ requireUtil$1();
    const $dataRefSchema = require$$9$1;
    const uri_1 = /* @__PURE__ */ requireUri$1();
    const defaultRegExp = (str, flags) => new RegExp(str, flags);
    defaultRegExp.code = "new RegExp";
    const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
    const EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
      "validate",
      "serialize",
      "parse",
      "wrapper",
      "root",
      "schema",
      "keyword",
      "pattern",
      "formats",
      "validate$data",
      "func",
      "obj",
      "Error"
    ]);
    const removedOptions = {
      errorDataPath: "",
      format: "`validateFormats: false` can be used instead.",
      nullable: '"nullable" keyword is supported by default.',
      jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
      extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
      missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
      processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
      sourceCode: "Use option `code: {source: true}`",
      strictDefaults: "It is default now, see option `strict`.",
      strictKeywords: "It is default now, see option `strict`.",
      uniqueItems: '"uniqueItems" keyword is always validated.',
      unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
      cache: "Map is used as cache, schema object as key.",
      serialize: "Map is used as cache, schema object as key.",
      ajvErrors: "It is default now."
    };
    const deprecatedOptions = {
      ignoreKeywordsWithRef: "",
      jsPropertySyntax: "",
      unicode: '"minLength"/"maxLength" account for unicode characters by default.'
    };
    const MAX_EXPRESSION = 200;
    function requiredOptions(o2) {
      var _a2, _b, _c, _d2, _e2, _f2, _g, _h, _j, _k, _l2, _m2, _o2, _p2, _q, _r2, _s2, _t2, _u2, _v2, _w, _x, _y, _z, _0;
      const s2 = o2.strict;
      const _optz = (_a2 = o2.code) === null || _a2 === void 0 ? void 0 : _a2.optimize;
      const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
      const regExp = (_c = (_b = o2.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
      const uriResolver = (_d2 = o2.uriResolver) !== null && _d2 !== void 0 ? _d2 : uri_1.default;
      return {
        strictSchema: (_f2 = (_e2 = o2.strictSchema) !== null && _e2 !== void 0 ? _e2 : s2) !== null && _f2 !== void 0 ? _f2 : true,
        strictNumbers: (_h = (_g = o2.strictNumbers) !== null && _g !== void 0 ? _g : s2) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o2.strictTypes) !== null && _j !== void 0 ? _j : s2) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m2 = (_l2 = o2.strictTuples) !== null && _l2 !== void 0 ? _l2 : s2) !== null && _m2 !== void 0 ? _m2 : "log",
        strictRequired: (_p2 = (_o2 = o2.strictRequired) !== null && _o2 !== void 0 ? _o2 : s2) !== null && _p2 !== void 0 ? _p2 : false,
        code: o2.code ? { ...o2.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o2.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r2 = o2.loopEnum) !== null && _r2 !== void 0 ? _r2 : MAX_EXPRESSION,
        meta: (_s2 = o2.meta) !== null && _s2 !== void 0 ? _s2 : true,
        messages: (_t2 = o2.messages) !== null && _t2 !== void 0 ? _t2 : true,
        inlineRefs: (_u2 = o2.inlineRefs) !== null && _u2 !== void 0 ? _u2 : true,
        schemaId: (_v2 = o2.schemaId) !== null && _v2 !== void 0 ? _v2 : "$id",
        addUsedSchema: (_w = o2.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o2.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o2.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o2.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o2.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver
      };
    }
    class Ajv2 {
      constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = /* @__PURE__ */ Object.create(null);
        this._compilations = /* @__PURE__ */ new Set();
        this._loading = {};
        this._cache = /* @__PURE__ */ new Map();
        opts = this.opts = { ...opts, ...requiredOptions(opts) };
        const { es5, lines } = this.opts.code;
        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
        this.logger = getLogger(opts.logger);
        const formatOpt = opts.validateFormats;
        opts.validateFormats = false;
        this.RULES = (0, rules_1.getRules)();
        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
        this._metaOpts = getMetaSchemaOptions.call(this);
        if (opts.formats)
          addInitialFormats.call(this);
        this._addVocabularies();
        this._addDefaultMetaSchema();
        if (opts.keywords)
          addInitialKeywords.call(this, opts.keywords);
        if (typeof opts.meta == "object")
          this.addMetaSchema(opts.meta);
        addInitialSchemas.call(this);
        opts.validateFormats = formatOpt;
      }
      _addVocabularies() {
        this.addKeyword("$async");
      }
      _addDefaultMetaSchema() {
        const { $data, meta, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
          _dataRefSchema = { ...$dataRefSchema };
          _dataRefSchema.id = _dataRefSchema.$id;
          delete _dataRefSchema.$id;
        }
        if (meta && $data)
          this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
      }
      defaultMeta() {
        const { meta, schemaId } = this.opts;
        return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0;
      }
      validate(schemaKeyRef, data2) {
        let v2;
        if (typeof schemaKeyRef == "string") {
          v2 = this.getSchema(schemaKeyRef);
          if (!v2)
            throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        } else {
          v2 = this.compile(schemaKeyRef);
        }
        const valid = v2(data2);
        if (!("$async" in v2))
          this.errors = v2.errors;
        return valid;
      }
      compile(schema, _meta) {
        const sch = this._addSchema(schema, _meta);
        return sch.validate || this._compileSchemaEnv(sch);
      }
      compileAsync(schema, meta) {
        if (typeof this.opts.loadSchema != "function") {
          throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta);
        async function runCompileAsync(_schema, _meta) {
          await loadMetaSchema.call(this, _schema.$schema);
          const sch = this._addSchema(_schema, _meta);
          return sch.validate || _compileAsync.call(this, sch);
        }
        async function loadMetaSchema($ref) {
          if ($ref && !this.getSchema($ref)) {
            await runCompileAsync.call(this, { $ref }, true);
          }
        }
        async function _compileAsync(sch) {
          try {
            return this._compileSchemaEnv(sch);
          } catch (e2) {
            if (!(e2 instanceof ref_error_1.default))
              throw e2;
            checkLoaded.call(this, e2);
            await loadMissingSchema.call(this, e2.missingSchema);
            return _compileAsync.call(this, sch);
          }
        }
        function checkLoaded({ missingSchema: ref2, missingRef }) {
          if (this.refs[ref2]) {
            throw new Error(`AnySchema ${ref2} is loaded but ${missingRef} cannot be resolved`);
          }
        }
        async function loadMissingSchema(ref2) {
          const _schema = await _loadSchema.call(this, ref2);
          if (!this.refs[ref2])
            await loadMetaSchema.call(this, _schema.$schema);
          if (!this.refs[ref2])
            this.addSchema(_schema, ref2, meta);
        }
        async function _loadSchema(ref2) {
          const p2 = this._loading[ref2];
          if (p2)
            return p2;
          try {
            return await (this._loading[ref2] = loadSchema(ref2));
          } finally {
            delete this._loading[ref2];
          }
        }
      }
      // Adds schema to the instance
      addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
        if (Array.isArray(schema)) {
          for (const sch of schema)
            this.addSchema(sch, void 0, _meta, _validateSchema);
          return this;
        }
        let id2;
        if (typeof schema === "object") {
          const { schemaId } = this.opts;
          id2 = schema[schemaId];
          if (id2 !== void 0 && typeof id2 != "string") {
            throw new Error(`schema ${schemaId} must be string`);
          }
        }
        key = (0, resolve_12.normalizeId)(key || id2);
        this._checkUnique(key);
        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
        return this;
      }
      // Add schema that will be used to validate other schemas
      // options in META_IGNORE_OPTIONS are alway set to false
      addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
        this.addSchema(schema, key, true, _validateSchema);
        return this;
      }
      //  Validate schema against its meta-schema
      validateSchema(schema, throwOrLogError) {
        if (typeof schema == "boolean")
          return true;
        let $schema2;
        $schema2 = schema.$schema;
        if ($schema2 !== void 0 && typeof $schema2 != "string") {
          throw new Error("$schema must be a string");
        }
        $schema2 = $schema2 || this.opts.defaultMeta || this.defaultMeta();
        if (!$schema2) {
          this.logger.warn("meta-schema not available");
          this.errors = null;
          return true;
        }
        const valid = this.validate($schema2, schema);
        if (!valid && throwOrLogError) {
          const message = "schema is invalid: " + this.errorsText();
          if (this.opts.validateSchema === "log")
            this.logger.error(message);
          else
            throw new Error(message);
        }
        return valid;
      }
      // Get compiled schema by `key` or `ref`.
      // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
      getSchema(keyRef) {
        let sch;
        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
          keyRef = sch;
        if (sch === void 0) {
          const { schemaId } = this.opts;
          const root = new compile_12.SchemaEnv({ schema: {}, schemaId });
          sch = compile_12.resolveSchema.call(this, root, keyRef);
          if (!sch)
            return;
          this.refs[keyRef] = sch;
        }
        return sch.validate || this._compileSchemaEnv(sch);
      }
      // Remove cached schema(s).
      // If no parameter is passed all schemas but meta-schemas are removed.
      // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
      // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
      removeSchema(schemaKeyRef) {
        if (schemaKeyRef instanceof RegExp) {
          this._removeAllSchemas(this.schemas, schemaKeyRef);
          this._removeAllSchemas(this.refs, schemaKeyRef);
          return this;
        }
        switch (typeof schemaKeyRef) {
          case "undefined":
            this._removeAllSchemas(this.schemas);
            this._removeAllSchemas(this.refs);
            this._cache.clear();
            return this;
          case "string": {
            const sch = getSchEnv.call(this, schemaKeyRef);
            if (typeof sch == "object")
              this._cache.delete(sch.schema);
            delete this.schemas[schemaKeyRef];
            delete this.refs[schemaKeyRef];
            return this;
          }
          case "object": {
            const cacheKey = schemaKeyRef;
            this._cache.delete(cacheKey);
            let id2 = schemaKeyRef[this.opts.schemaId];
            if (id2) {
              id2 = (0, resolve_12.normalizeId)(id2);
              delete this.schemas[id2];
              delete this.refs[id2];
            }
            return this;
          }
          default:
            throw new Error("ajv.removeSchema: invalid parameter");
        }
      }
      // add "vocabulary" - a collection of keywords
      addVocabulary(definitions2) {
        for (const def of definitions2)
          this.addKeyword(def);
        return this;
      }
      addKeyword(kwdOrDef, def) {
        let keyword2;
        if (typeof kwdOrDef == "string") {
          keyword2 = kwdOrDef;
          if (typeof def == "object") {
            this.logger.warn("these parameters are deprecated, see docs for addKeyword");
            def.keyword = keyword2;
          }
        } else if (typeof kwdOrDef == "object" && def === void 0) {
          def = kwdOrDef;
          keyword2 = def.keyword;
          if (Array.isArray(keyword2) && !keyword2.length) {
            throw new Error("addKeywords: keyword must be string or non-empty array");
          }
        } else {
          throw new Error("invalid addKeywords parameters");
        }
        checkKeyword.call(this, keyword2, def);
        if (!def) {
          (0, util_1.eachItem)(keyword2, (kwd) => addRule.call(this, kwd));
          return this;
        }
        keywordMetaschema.call(this, def);
        const definition = {
          ...def,
          type: (0, dataType_1.getJSONTypes)(def.type),
          schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)
        };
        (0, util_1.eachItem)(keyword2, definition.type.length === 0 ? (k2) => addRule.call(this, k2, definition) : (k2) => definition.type.forEach((t2) => addRule.call(this, k2, definition, t2)));
        return this;
      }
      getKeyword(keyword2) {
        const rule = this.RULES.all[keyword2];
        return typeof rule == "object" ? rule.definition : !!rule;
      }
      // Remove keyword
      removeKeyword(keyword2) {
        const { RULES } = this;
        delete RULES.keywords[keyword2];
        delete RULES.all[keyword2];
        for (const group of RULES.rules) {
          const i2 = group.rules.findIndex((rule) => rule.keyword === keyword2);
          if (i2 >= 0)
            group.rules.splice(i2, 1);
        }
        return this;
      }
      // Add format
      addFormat(name2, format2) {
        if (typeof format2 == "string")
          format2 = new RegExp(format2);
        this.formats[name2] = format2;
        return this;
      }
      errorsText(errors2 = this.errors, { separator = ", ", dataVar = "data" } = {}) {
        if (!errors2 || errors2.length === 0)
          return "No errors";
        return errors2.map((e2) => `${dataVar}${e2.instancePath} ${e2.message}`).reduce((text, msg) => text + separator + msg);
      }
      $dataMetaSchema(metaSchema, keywordsJsonPointers) {
        const rules2 = this.RULES.all;
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        for (const jsonPointer of keywordsJsonPointers) {
          const segments = jsonPointer.split("/").slice(1);
          let keywords = metaSchema;
          for (const seg of segments)
            keywords = keywords[seg];
          for (const key in rules2) {
            const rule = rules2[key];
            if (typeof rule != "object")
              continue;
            const { $data } = rule.definition;
            const schema = keywords[key];
            if ($data && schema)
              keywords[key] = schemaOrData(schema);
          }
        }
        return metaSchema;
      }
      _removeAllSchemas(schemas, regex) {
        for (const keyRef in schemas) {
          const sch = schemas[keyRef];
          if (!regex || regex.test(keyRef)) {
            if (typeof sch == "string") {
              delete schemas[keyRef];
            } else if (sch && !sch.meta) {
              this._cache.delete(sch.schema);
              delete schemas[keyRef];
            }
          }
        }
      }
      _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
        let id2;
        const { schemaId } = this.opts;
        if (typeof schema == "object") {
          id2 = schema[schemaId];
        } else {
          if (this.opts.jtd)
            throw new Error("schema must be object");
          else if (typeof schema != "boolean")
            throw new Error("schema must be object or boolean");
        }
        let sch = this._cache.get(schema);
        if (sch !== void 0)
          return sch;
        baseId = (0, resolve_12.normalizeId)(id2 || baseId);
        const localRefs = resolve_12.getSchemaRefs.call(this, schema, baseId);
        sch = new compile_12.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
        this._cache.set(sch.schema, sch);
        if (addSchema && !baseId.startsWith("#")) {
          if (baseId)
            this._checkUnique(baseId);
          this.refs[baseId] = sch;
        }
        if (validateSchema)
          this.validateSchema(schema, true);
        return sch;
      }
      _checkUnique(id2) {
        if (this.schemas[id2] || this.refs[id2]) {
          throw new Error(`schema with key or id "${id2}" already exists`);
        }
      }
      _compileSchemaEnv(sch) {
        if (sch.meta)
          this._compileMetaSchema(sch);
        else
          compile_12.compileSchema.call(this, sch);
        if (!sch.validate)
          throw new Error("ajv implementation error");
        return sch.validate;
      }
      _compileMetaSchema(sch) {
        const currentOpts = this.opts;
        this.opts = this._metaOpts;
        try {
          compile_12.compileSchema.call(this, sch);
        } finally {
          this.opts = currentOpts;
        }
      }
    }
    Ajv2.ValidationError = validation_error_1.default;
    Ajv2.MissingRefError = ref_error_1.default;
    exports.default = Ajv2;
    function checkOptions(checkOpts, options, msg, log = "error") {
      for (const key in checkOpts) {
        const opt = key;
        if (opt in options)
          this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
      }
    }
    function getSchEnv(keyRef) {
      keyRef = (0, resolve_12.normalizeId)(keyRef);
      return this.schemas[keyRef] || this.refs[keyRef];
    }
    function addInitialSchemas() {
      const optsSchemas = this.opts.schemas;
      if (!optsSchemas)
        return;
      if (Array.isArray(optsSchemas))
        this.addSchema(optsSchemas);
      else
        for (const key in optsSchemas)
          this.addSchema(optsSchemas[key], key);
    }
    function addInitialFormats() {
      for (const name2 in this.opts.formats) {
        const format2 = this.opts.formats[name2];
        if (format2)
          this.addFormat(name2, format2);
      }
    }
    function addInitialKeywords(defs) {
      if (Array.isArray(defs)) {
        this.addVocabulary(defs);
        return;
      }
      this.logger.warn("keywords option as map is deprecated, pass array");
      for (const keyword2 in defs) {
        const def = defs[keyword2];
        if (!def.keyword)
          def.keyword = keyword2;
        this.addKeyword(def);
      }
    }
    function getMetaSchemaOptions() {
      const metaOpts = { ...this.opts };
      for (const opt of META_IGNORE_OPTIONS)
        delete metaOpts[opt];
      return metaOpts;
    }
    const noLogs = { log() {
    }, warn() {
    }, error() {
    } };
    function getLogger(logger) {
      if (logger === false)
        return noLogs;
      if (logger === void 0)
        return console;
      if (logger.log && logger.warn && logger.error)
        return logger;
      throw new Error("logger must implement log, warn and error methods");
    }
    const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
    function checkKeyword(keyword2, def) {
      const { RULES } = this;
      (0, util_1.eachItem)(keyword2, (kwd) => {
        if (RULES.keywords[kwd])
          throw new Error(`Keyword ${kwd} is already defined`);
        if (!KEYWORD_NAME.test(kwd))
          throw new Error(`Keyword ${kwd} has invalid name`);
      });
      if (!def)
        return;
      if (def.$data && !("code" in def || "validate" in def)) {
        throw new Error('$data keyword must have "code" or "validate" function');
      }
    }
    function addRule(keyword2, definition, dataType2) {
      var _a2;
      const post = definition === null || definition === void 0 ? void 0 : definition.post;
      if (dataType2 && post)
        throw new Error('keyword with "post" flag cannot have "type"');
      const { RULES } = this;
      let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t2 }) => t2 === dataType2);
      if (!ruleGroup) {
        ruleGroup = { type: dataType2, rules: [] };
        RULES.rules.push(ruleGroup);
      }
      RULES.keywords[keyword2] = true;
      if (!definition)
        return;
      const rule = {
        keyword: keyword2,
        definition: {
          ...definition,
          type: (0, dataType_1.getJSONTypes)(definition.type),
          schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)
        }
      };
      if (definition.before)
        addBeforeRule.call(this, ruleGroup, rule, definition.before);
      else
        ruleGroup.rules.push(rule);
      RULES.all[keyword2] = rule;
      (_a2 = definition.implements) === null || _a2 === void 0 ? void 0 : _a2.forEach((kwd) => this.addKeyword(kwd));
    }
    function addBeforeRule(ruleGroup, rule, before) {
      const i2 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i2 >= 0) {
        ruleGroup.rules.splice(i2, 0, rule);
      } else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
      }
    }
    function keywordMetaschema(def) {
      let { metaSchema } = def;
      if (metaSchema === void 0)
        return;
      if (def.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
      def.validateSchema = this.compile(metaSchema, true);
    }
    const $dataRef = {
      $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
    };
    function schemaOrData(schema) {
      return { anyOf: [schema, $dataRef] };
    }
  })(core$3);
  return core$3;
}
var draft7$1 = {};
var core$2 = {};
var id$2 = {};
var hasRequiredId$1;
function requireId$1() {
  if (hasRequiredId$1) return id$2;
  hasRequiredId$1 = 1;
  Object.defineProperty(id$2, "__esModule", { value: true });
  const def = {
    keyword: "id",
    code() {
      throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
    }
  };
  id$2.default = def;
  return id$2;
}
var ref$1 = {};
var hasRequiredRef$1;
function requireRef$1() {
  if (hasRequiredRef$1) return ref$1;
  hasRequiredRef$1 = 1;
  Object.defineProperty(ref$1, "__esModule", { value: true });
  ref$1.callRef = ref$1.getValidate = void 0;
  const ref_error_1 = /* @__PURE__ */ requireRef_error$1();
  const code_1 = /* @__PURE__ */ requireCode$2();
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const names_1 = /* @__PURE__ */ requireNames$1();
  const compile_12 = /* @__PURE__ */ requireCompile$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const def = {
    keyword: "$ref",
    schemaType: "string",
    code(cxt) {
      const { gen, schema: $ref, it: it2 } = cxt;
      const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it2;
      const { root } = env;
      if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
        return callRootRef();
      const schOrEnv = compile_12.resolveRef.call(self2, root, baseId, $ref);
      if (schOrEnv === void 0)
        throw new ref_error_1.default(it2.opts.uriResolver, baseId, $ref);
      if (schOrEnv instanceof compile_12.SchemaEnv)
        return callValidate(schOrEnv);
      return inlineRefSchema(schOrEnv);
      function callRootRef() {
        if (env === root)
          return callRef(cxt, validateName, env, env.$async);
        const rootName = gen.scopeValue("root", { ref: root });
        return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
      }
      function callValidate(sch) {
        const v2 = getValidate(cxt, sch);
        callRef(cxt, v2, sch, sch.$async);
      }
      function inlineRefSchema(sch) {
        const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
        const valid = gen.name("valid");
        const schCxt = cxt.subschema({
          schema: sch,
          dataTypes: [],
          schemaPath: codegen_1.nil,
          topSchemaRef: schName,
          errSchemaPath: $ref
        }, valid);
        cxt.mergeEvaluated(schCxt);
        cxt.ok(valid);
      }
    }
  };
  function getValidate(cxt, sch) {
    const { gen } = cxt;
    return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
  }
  ref$1.getValidate = getValidate;
  function callRef(cxt, v2, sch, $async) {
    const { gen, it: it2 } = cxt;
    const { allErrors, schemaEnv: env, opts } = it2;
    const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
    if ($async)
      callAsyncRef();
    else
      callSyncRef();
    function callAsyncRef() {
      if (!env.$async)
        throw new Error("async schema referenced by sync schema");
      const valid = gen.let("valid");
      gen.try(() => {
        gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v2, passCxt)}`);
        addEvaluatedFrom(v2);
        if (!allErrors)
          gen.assign(valid, true);
      }, (e2) => {
        gen.if((0, codegen_1._)`!(${e2} instanceof ${it2.ValidationError})`, () => gen.throw(e2));
        addErrorsFrom(e2);
        if (!allErrors)
          gen.assign(valid, false);
      });
      cxt.ok(valid);
    }
    function callSyncRef() {
      cxt.result((0, code_1.callValidateCode)(cxt, v2, passCxt), () => addEvaluatedFrom(v2), () => addErrorsFrom(v2));
    }
    function addErrorsFrom(source) {
      const errs = (0, codegen_1._)`${source}.errors`;
      gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);
      gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
    }
    function addEvaluatedFrom(source) {
      var _a2;
      if (!it2.opts.unevaluated)
        return;
      const schEvaluated = (_a2 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a2 === void 0 ? void 0 : _a2.evaluated;
      if (it2.props !== true) {
        if (schEvaluated && !schEvaluated.dynamicProps) {
          if (schEvaluated.props !== void 0) {
            it2.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it2.props);
          }
        } else {
          const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`);
          it2.props = util_1.mergeEvaluated.props(gen, props, it2.props, codegen_1.Name);
        }
      }
      if (it2.items !== true) {
        if (schEvaluated && !schEvaluated.dynamicItems) {
          if (schEvaluated.items !== void 0) {
            it2.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it2.items);
          }
        } else {
          const items2 = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`);
          it2.items = util_1.mergeEvaluated.items(gen, items2, it2.items, codegen_1.Name);
        }
      }
    }
  }
  ref$1.callRef = callRef;
  ref$1.default = def;
  return ref$1;
}
var hasRequiredCore$2;
function requireCore$2() {
  if (hasRequiredCore$2) return core$2;
  hasRequiredCore$2 = 1;
  Object.defineProperty(core$2, "__esModule", { value: true });
  const id_1 = /* @__PURE__ */ requireId$1();
  const ref_1 = /* @__PURE__ */ requireRef$1();
  const core2 = [
    "$schema",
    "$id",
    "$defs",
    "$vocabulary",
    { keyword: "$comment" },
    "definitions",
    id_1.default,
    ref_1.default
  ];
  core$2.default = core2;
  return core$2;
}
var validation$1 = {};
var limitNumber$1 = {};
var hasRequiredLimitNumber$1;
function requireLimitNumber$1() {
  if (hasRequiredLimitNumber$1) return limitNumber$1;
  hasRequiredLimitNumber$1 = 1;
  Object.defineProperty(limitNumber$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const ops = codegen_1.operators;
  const KWDs = {
    maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
    minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
    exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
    exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
  };
  const error = {
    message: ({ keyword: keyword2, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword2].okStr} ${schemaCode}`,
    params: ({ keyword: keyword2, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword2].okStr}, limit: ${schemaCode}}`
  };
  const def = {
    keyword: Object.keys(KWDs),
    type: "number",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
      const { keyword: keyword2, data: data2, schemaCode } = cxt;
      cxt.fail$data((0, codegen_1._)`${data2} ${KWDs[keyword2].fail} ${schemaCode} || isNaN(${data2})`);
    }
  };
  limitNumber$1.default = def;
  return limitNumber$1;
}
var multipleOf$1 = {};
var hasRequiredMultipleOf$1;
function requireMultipleOf$1() {
  if (hasRequiredMultipleOf$1) return multipleOf$1;
  hasRequiredMultipleOf$1 = 1;
  Object.defineProperty(multipleOf$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const error = {
    message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,
    params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`
  };
  const def = {
    keyword: "multipleOf",
    type: "number",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
      const { gen, data: data2, schemaCode, it: it2 } = cxt;
      const prec = it2.opts.multipleOfPrecision;
      const res = gen.let("res");
      const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
      cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data2}/${schemaCode}, ${invalid}))`);
    }
  };
  multipleOf$1.default = def;
  return multipleOf$1;
}
var limitLength$1 = {};
var ucs2length$1 = {};
var hasRequiredUcs2length$1;
function requireUcs2length$1() {
  if (hasRequiredUcs2length$1) return ucs2length$1;
  hasRequiredUcs2length$1 = 1;
  Object.defineProperty(ucs2length$1, "__esModule", { value: true });
  function ucs2length2(str) {
    const len = str.length;
    let length = 0;
    let pos = 0;
    let 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;
  }
  ucs2length$1.default = ucs2length2;
  ucs2length2.code = 'require("ajv/dist/runtime/ucs2length").default';
  return ucs2length$1;
}
var hasRequiredLimitLength$1;
function requireLimitLength$1() {
  if (hasRequiredLimitLength$1) return limitLength$1;
  hasRequiredLimitLength$1 = 1;
  Object.defineProperty(limitLength$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const ucs2length_1 = /* @__PURE__ */ requireUcs2length$1();
  const error = {
    message({ keyword: keyword2, schemaCode }) {
      const comp = keyword2 === "maxLength" ? "more" : "fewer";
      return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
    },
    params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
  };
  const def = {
    keyword: ["maxLength", "minLength"],
    type: "string",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
      const { keyword: keyword2, data: data2, schemaCode, it: it2 } = cxt;
      const op2 = keyword2 === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
      const len = it2.opts.unicode === false ? (0, codegen_1._)`${data2}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data2})`;
      cxt.fail$data((0, codegen_1._)`${len} ${op2} ${schemaCode}`);
    }
  };
  limitLength$1.default = def;
  return limitLength$1;
}
var pattern$1 = {};
var hasRequiredPattern$1;
function requirePattern$1() {
  if (hasRequiredPattern$1) return pattern$1;
  hasRequiredPattern$1 = 1;
  Object.defineProperty(pattern$1, "__esModule", { value: true });
  const code_1 = /* @__PURE__ */ requireCode$2();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const error = {
    message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
    params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`
  };
  const def = {
    keyword: "pattern",
    type: "string",
    schemaType: "string",
    $data: true,
    error,
    code(cxt) {
      const { gen, data: data2, $data, schema, schemaCode, it: it2 } = cxt;
      const u2 = it2.opts.unicodeRegExp ? "u" : "";
      if ($data) {
        const { regExp } = it2.opts.code;
        const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp);
        const valid = gen.let("valid");
        gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u2}).test(${data2})`), () => gen.assign(valid, false));
        cxt.fail$data((0, codegen_1._)`!${valid}`);
      } else {
        const regExp = (0, code_1.usePattern)(cxt, schema);
        cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data2})`);
      }
    }
  };
  pattern$1.default = def;
  return pattern$1;
}
var limitProperties$1 = {};
var hasRequiredLimitProperties$1;
function requireLimitProperties$1() {
  if (hasRequiredLimitProperties$1) return limitProperties$1;
  hasRequiredLimitProperties$1 = 1;
  Object.defineProperty(limitProperties$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const error = {
    message({ keyword: keyword2, schemaCode }) {
      const comp = keyword2 === "maxProperties" ? "more" : "fewer";
      return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;
    },
    params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
  };
  const def = {
    keyword: ["maxProperties", "minProperties"],
    type: "object",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
      const { keyword: keyword2, data: data2, schemaCode } = cxt;
      const op2 = keyword2 === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
      cxt.fail$data((0, codegen_1._)`Object.keys(${data2}).length ${op2} ${schemaCode}`);
    }
  };
  limitProperties$1.default = def;
  return limitProperties$1;
}
var required$2 = {};
var hasRequiredRequired$1;
function requireRequired$1() {
  if (hasRequiredRequired$1) return required$2;
  hasRequiredRequired$1 = 1;
  Object.defineProperty(required$2, "__esModule", { value: true });
  const code_1 = /* @__PURE__ */ requireCode$2();
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const error = {
    message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,
    params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`
  };
  const def = {
    keyword: "required",
    type: "object",
    schemaType: "array",
    $data: true,
    error,
    code(cxt) {
      const { gen, schema, schemaCode, data: data2, $data, it: it2 } = cxt;
      const { opts } = it2;
      if (!$data && schema.length === 0)
        return;
      const useLoop = schema.length >= opts.loopRequired;
      if (it2.allErrors)
        allErrorsMode();
      else
        exitOnErrorMode();
      if (opts.strictRequired) {
        const props = cxt.parentSchema.properties;
        const { definedProperties } = cxt.it;
        for (const requiredKey of schema) {
          if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
            const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath;
            const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
            (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictRequired);
          }
        }
      }
      function allErrorsMode() {
        if (useLoop || $data) {
          cxt.block$data(codegen_1.nil, loopAllRequired);
        } else {
          for (const prop of schema) {
            (0, code_1.checkReportMissingProp)(cxt, prop);
          }
        }
      }
      function exitOnErrorMode() {
        const missing = gen.let("missing");
        if (useLoop || $data) {
          const valid = gen.let("valid", true);
          cxt.block$data(valid, () => loopUntilMissing(missing, valid));
          cxt.ok(valid);
        } else {
          gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
          (0, code_1.reportMissingProp)(cxt, missing);
          gen.else();
        }
      }
      function loopAllRequired() {
        gen.forOf("prop", schemaCode, (prop) => {
          cxt.setParams({ missingProperty: prop });
          gen.if((0, code_1.noPropertyInData)(gen, data2, prop, opts.ownProperties), () => cxt.error());
        });
      }
      function loopUntilMissing(missing, valid) {
        cxt.setParams({ missingProperty: missing });
        gen.forOf(missing, schemaCode, () => {
          gen.assign(valid, (0, code_1.propertyInData)(gen, data2, missing, opts.ownProperties));
          gen.if((0, codegen_1.not)(valid), () => {
            cxt.error();
            gen.break();
          });
        }, codegen_1.nil);
      }
    }
  };
  required$2.default = def;
  return required$2;
}
var limitItems$1 = {};
var hasRequiredLimitItems$1;
function requireLimitItems$1() {
  if (hasRequiredLimitItems$1) return limitItems$1;
  hasRequiredLimitItems$1 = 1;
  Object.defineProperty(limitItems$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const error = {
    message({ keyword: keyword2, schemaCode }) {
      const comp = keyword2 === "maxItems" ? "more" : "fewer";
      return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;
    },
    params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
  };
  const def = {
    keyword: ["maxItems", "minItems"],
    type: "array",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
      const { keyword: keyword2, data: data2, schemaCode } = cxt;
      const op2 = keyword2 === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
      cxt.fail$data((0, codegen_1._)`${data2}.length ${op2} ${schemaCode}`);
    }
  };
  limitItems$1.default = def;
  return limitItems$1;
}
var uniqueItems$1 = {};
var equal$1 = {};
var hasRequiredEqual$1;
function requireEqual$1() {
  if (hasRequiredEqual$1) return equal$1;
  hasRequiredEqual$1 = 1;
  Object.defineProperty(equal$1, "__esModule", { value: true });
  const equal2 = requireFastDeepEqual();
  equal2.code = 'require("ajv/dist/runtime/equal").default';
  equal$1.default = equal2;
  return equal$1;
}
var hasRequiredUniqueItems$1;
function requireUniqueItems$1() {
  if (hasRequiredUniqueItems$1) return uniqueItems$1;
  hasRequiredUniqueItems$1 = 1;
  Object.defineProperty(uniqueItems$1, "__esModule", { value: true });
  const dataType_1 = /* @__PURE__ */ requireDataType$1();
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const equal_1 = /* @__PURE__ */ requireEqual$1();
  const error = {
    message: ({ params: { i: i2, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i2} are identical)`,
    params: ({ params: { i: i2, j } }) => (0, codegen_1._)`{i: ${i2}, j: ${j}}`
  };
  const def = {
    keyword: "uniqueItems",
    type: "array",
    schemaType: "boolean",
    $data: true,
    error,
    code(cxt) {
      const { gen, data: data2, $data, schema, parentSchema, schemaCode, it: it2 } = cxt;
      if (!$data && !schema)
        return;
      const valid = gen.let("valid");
      const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
      cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);
      cxt.ok(valid);
      function validateUniqueItems() {
        const i2 = gen.let("i", (0, codegen_1._)`${data2}.length`);
        const j = gen.let("j");
        cxt.setParams({ i: i2, j });
        gen.assign(valid, true);
        gen.if((0, codegen_1._)`${i2} > 1`, () => (canOptimize() ? loopN : loopN2)(i2, j));
      }
      function canOptimize() {
        return itemTypes.length > 0 && !itemTypes.some((t2) => t2 === "object" || t2 === "array");
      }
      function loopN(i2, j) {
        const item = gen.name("item");
        const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it2.opts.strictNumbers, dataType_1.DataType.Wrong);
        const indices = gen.const("indices", (0, codegen_1._)`{}`);
        gen.for((0, codegen_1._)`;${i2}--;`, () => {
          gen.let(item, (0, codegen_1._)`${data2}[${i2}]`);
          gen.if(wrongType, (0, codegen_1._)`continue`);
          if (itemTypes.length > 1)
            gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`);
          gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => {
            gen.assign(j, (0, codegen_1._)`${indices}[${item}]`);
            cxt.error();
            gen.assign(valid, false).break();
          }).code((0, codegen_1._)`${indices}[${item}] = ${i2}`);
        });
      }
      function loopN2(i2, j) {
        const eql = (0, util_1.useFunc)(gen, equal_1.default);
        const outer = gen.name("outer");
        gen.label(outer).for((0, codegen_1._)`;${i2}--;`, () => gen.for((0, codegen_1._)`${j} = ${i2}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data2}[${i2}], ${data2}[${j}])`, () => {
          cxt.error();
          gen.assign(valid, false).break(outer);
        })));
      }
    }
  };
  uniqueItems$1.default = def;
  return uniqueItems$1;
}
var _const$1 = {};
var hasRequired_const$1;
function require_const$1() {
  if (hasRequired_const$1) return _const$1;
  hasRequired_const$1 = 1;
  Object.defineProperty(_const$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const equal_1 = /* @__PURE__ */ requireEqual$1();
  const error = {
    message: "must be equal to constant",
    params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
  };
  const def = {
    keyword: "const",
    $data: true,
    error,
    code(cxt) {
      const { gen, data: data2, $data, schemaCode, schema } = cxt;
      if ($data || schema && typeof schema == "object") {
        cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data2}, ${schemaCode})`);
      } else {
        cxt.fail((0, codegen_1._)`${schema} !== ${data2}`);
      }
    }
  };
  _const$1.default = def;
  return _const$1;
}
var _enum$1 = {};
var hasRequired_enum$1;
function require_enum$1() {
  if (hasRequired_enum$1) return _enum$1;
  hasRequired_enum$1 = 1;
  Object.defineProperty(_enum$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const equal_1 = /* @__PURE__ */ requireEqual$1();
  const error = {
    message: "must be equal to one of the allowed values",
    params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`
  };
  const def = {
    keyword: "enum",
    schemaType: "array",
    $data: true,
    error,
    code(cxt) {
      const { gen, data: data2, $data, schema, schemaCode, it: it2 } = cxt;
      if (!$data && schema.length === 0)
        throw new Error("enum must have non-empty array");
      const useLoop = schema.length >= it2.opts.loopEnum;
      let eql;
      const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default);
      let valid;
      if (useLoop || $data) {
        valid = gen.let("valid");
        cxt.block$data(valid, loopEnum);
      } else {
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        const vSchema = gen.const("vSchema", schemaCode);
        valid = (0, codegen_1.or)(...schema.map((_x, i2) => equalCode(vSchema, i2)));
      }
      cxt.pass(valid);
      function loopEnum() {
        gen.assign(valid, false);
        gen.forOf("v", schemaCode, (v2) => gen.if((0, codegen_1._)`${getEql()}(${data2}, ${v2})`, () => gen.assign(valid, true).break()));
      }
      function equalCode(vSchema, i2) {
        const sch = schema[i2];
        return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data2}, ${vSchema}[${i2}])` : (0, codegen_1._)`${data2} === ${sch}`;
      }
    }
  };
  _enum$1.default = def;
  return _enum$1;
}
var hasRequiredValidation$1;
function requireValidation$1() {
  if (hasRequiredValidation$1) return validation$1;
  hasRequiredValidation$1 = 1;
  Object.defineProperty(validation$1, "__esModule", { value: true });
  const limitNumber_1 = /* @__PURE__ */ requireLimitNumber$1();
  const multipleOf_1 = /* @__PURE__ */ requireMultipleOf$1();
  const limitLength_1 = /* @__PURE__ */ requireLimitLength$1();
  const pattern_1 = /* @__PURE__ */ requirePattern$1();
  const limitProperties_1 = /* @__PURE__ */ requireLimitProperties$1();
  const required_1 = /* @__PURE__ */ requireRequired$1();
  const limitItems_1 = /* @__PURE__ */ requireLimitItems$1();
  const uniqueItems_1 = /* @__PURE__ */ requireUniqueItems$1();
  const const_1 = /* @__PURE__ */ require_const$1();
  const enum_1 = /* @__PURE__ */ require_enum$1();
  const validation2 = [
    // number
    limitNumber_1.default,
    multipleOf_1.default,
    // string
    limitLength_1.default,
    pattern_1.default,
    // object
    limitProperties_1.default,
    required_1.default,
    // array
    limitItems_1.default,
    uniqueItems_1.default,
    // any
    { keyword: "type", schemaType: ["string", "array"] },
    { keyword: "nullable", schemaType: "boolean" },
    const_1.default,
    enum_1.default
  ];
  validation$1.default = validation2;
  return validation$1;
}
var applicator$1 = {};
var additionalItems$1 = {};
var hasRequiredAdditionalItems$1;
function requireAdditionalItems$1() {
  if (hasRequiredAdditionalItems$1) return additionalItems$1;
  hasRequiredAdditionalItems$1 = 1;
  Object.defineProperty(additionalItems$1, "__esModule", { value: true });
  additionalItems$1.validateAdditionalItems = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const error = {
    message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
  };
  const def = {
    keyword: "additionalItems",
    type: "array",
    schemaType: ["boolean", "object"],
    before: "uniqueItems",
    error,
    code(cxt) {
      const { parentSchema, it: it2 } = cxt;
      const { items: items2 } = parentSchema;
      if (!Array.isArray(items2)) {
        (0, util_1.checkStrictMode)(it2, '"additionalItems" is ignored when "items" is not an array of schemas');
        return;
      }
      validateAdditionalItems(cxt, items2);
    }
  };
  function validateAdditionalItems(cxt, items2) {
    const { gen, schema, data: data2, keyword: keyword2, it: it2 } = cxt;
    it2.items = true;
    const len = gen.const("len", (0, codegen_1._)`${data2}.length`);
    if (schema === false) {
      cxt.setParams({ len: items2.length });
      cxt.pass((0, codegen_1._)`${len} <= ${items2.length}`);
    } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it2, schema)) {
      const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items2.length}`);
      gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
      cxt.ok(valid);
    }
    function validateItems(valid) {
      gen.forRange("i", items2.length, len, (i2) => {
        cxt.subschema({ keyword: keyword2, dataProp: i2, dataPropType: util_1.Type.Num }, valid);
        if (!it2.allErrors)
          gen.if((0, codegen_1.not)(valid), () => gen.break());
      });
    }
  }
  additionalItems$1.validateAdditionalItems = validateAdditionalItems;
  additionalItems$1.default = def;
  return additionalItems$1;
}
var prefixItems$1 = {};
var items$1 = {};
var hasRequiredItems$1;
function requireItems$1() {
  if (hasRequiredItems$1) return items$1;
  hasRequiredItems$1 = 1;
  Object.defineProperty(items$1, "__esModule", { value: true });
  items$1.validateTuple = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const code_1 = /* @__PURE__ */ requireCode$2();
  const def = {
    keyword: "items",
    type: "array",
    schemaType: ["object", "array", "boolean"],
    before: "uniqueItems",
    code(cxt) {
      const { schema, it: it2 } = cxt;
      if (Array.isArray(schema))
        return validateTuple(cxt, "additionalItems", schema);
      it2.items = true;
      if ((0, util_1.alwaysValidSchema)(it2, schema))
        return;
      cxt.ok((0, code_1.validateArray)(cxt));
    }
  };
  function validateTuple(cxt, extraItems, schArr = cxt.schema) {
    const { gen, parentSchema, data: data2, keyword: keyword2, it: it2 } = cxt;
    checkStrictTuple(parentSchema);
    if (it2.opts.unevaluated && schArr.length && it2.items !== true) {
      it2.items = util_1.mergeEvaluated.items(gen, schArr.length, it2.items);
    }
    const valid = gen.name("valid");
    const len = gen.const("len", (0, codegen_1._)`${data2}.length`);
    schArr.forEach((sch, i2) => {
      if ((0, util_1.alwaysValidSchema)(it2, sch))
        return;
      gen.if((0, codegen_1._)`${len} > ${i2}`, () => cxt.subschema({
        keyword: keyword2,
        schemaProp: i2,
        dataProp: i2
      }, valid));
      cxt.ok(valid);
    });
    function checkStrictTuple(sch) {
      const { opts, errSchemaPath } = it2;
      const l2 = schArr.length;
      const fullTuple = l2 === sch.minItems && (l2 === sch.maxItems || sch[extraItems] === false);
      if (opts.strictTuples && !fullTuple) {
        const msg = `"${keyword2}" is ${l2}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
        (0, util_1.checkStrictMode)(it2, msg, opts.strictTuples);
      }
    }
  }
  items$1.validateTuple = validateTuple;
  items$1.default = def;
  return items$1;
}
var hasRequiredPrefixItems$1;
function requirePrefixItems$1() {
  if (hasRequiredPrefixItems$1) return prefixItems$1;
  hasRequiredPrefixItems$1 = 1;
  Object.defineProperty(prefixItems$1, "__esModule", { value: true });
  const items_1 = /* @__PURE__ */ requireItems$1();
  const def = {
    keyword: "prefixItems",
    type: "array",
    schemaType: ["array"],
    before: "uniqueItems",
    code: (cxt) => (0, items_1.validateTuple)(cxt, "items")
  };
  prefixItems$1.default = def;
  return prefixItems$1;
}
var items2020$1 = {};
var hasRequiredItems2020$1;
function requireItems2020$1() {
  if (hasRequiredItems2020$1) return items2020$1;
  hasRequiredItems2020$1 = 1;
  Object.defineProperty(items2020$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const code_1 = /* @__PURE__ */ requireCode$2();
  const additionalItems_1 = /* @__PURE__ */ requireAdditionalItems$1();
  const error = {
    message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
  };
  const def = {
    keyword: "items",
    type: "array",
    schemaType: ["object", "boolean"],
    before: "uniqueItems",
    error,
    code(cxt) {
      const { schema, parentSchema, it: it2 } = cxt;
      const { prefixItems: prefixItems2 } = parentSchema;
      it2.items = true;
      if ((0, util_1.alwaysValidSchema)(it2, schema))
        return;
      if (prefixItems2)
        (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems2);
      else
        cxt.ok((0, code_1.validateArray)(cxt));
    }
  };
  items2020$1.default = def;
  return items2020$1;
}
var contains$1 = {};
var hasRequiredContains$1;
function requireContains$1() {
  if (hasRequiredContains$1) return contains$1;
  hasRequiredContains$1 = 1;
  Object.defineProperty(contains$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const error = {
    message: ({ params: { min: min2, max: max2 } }) => max2 === void 0 ? (0, codegen_1.str)`must contain at least ${min2} valid item(s)` : (0, codegen_1.str)`must contain at least ${min2} and no more than ${max2} valid item(s)`,
    params: ({ params: { min: min2, max: max2 } }) => max2 === void 0 ? (0, codegen_1._)`{minContains: ${min2}}` : (0, codegen_1._)`{minContains: ${min2}, maxContains: ${max2}}`
  };
  const def = {
    keyword: "contains",
    type: "array",
    schemaType: ["object", "boolean"],
    before: "uniqueItems",
    trackErrors: true,
    error,
    code(cxt) {
      const { gen, schema, parentSchema, data: data2, it: it2 } = cxt;
      let min2;
      let max2;
      const { minContains, maxContains } = parentSchema;
      if (it2.opts.next) {
        min2 = minContains === void 0 ? 1 : minContains;
        max2 = maxContains;
      } else {
        min2 = 1;
      }
      const len = gen.const("len", (0, codegen_1._)`${data2}.length`);
      cxt.setParams({ min: min2, max: max2 });
      if (max2 === void 0 && min2 === 0) {
        (0, util_1.checkStrictMode)(it2, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
        return;
      }
      if (max2 !== void 0 && min2 > max2) {
        (0, util_1.checkStrictMode)(it2, `"minContains" > "maxContains" is always invalid`);
        cxt.fail();
        return;
      }
      if ((0, util_1.alwaysValidSchema)(it2, schema)) {
        let cond = (0, codegen_1._)`${len} >= ${min2}`;
        if (max2 !== void 0)
          cond = (0, codegen_1._)`${cond} && ${len} <= ${max2}`;
        cxt.pass(cond);
        return;
      }
      it2.items = true;
      const valid = gen.name("valid");
      if (max2 === void 0 && min2 === 1) {
        validateItems(valid, () => gen.if(valid, () => gen.break()));
      } else if (min2 === 0) {
        gen.let(valid, true);
        if (max2 !== void 0)
          gen.if((0, codegen_1._)`${data2}.length > 0`, validateItemsWithCount);
      } else {
        gen.let(valid, false);
        validateItemsWithCount();
      }
      cxt.result(valid, () => cxt.reset());
      function validateItemsWithCount() {
        const schValid = gen.name("_valid");
        const count2 = gen.let("count", 0);
        validateItems(schValid, () => gen.if(schValid, () => checkLimits(count2)));
      }
      function validateItems(_valid, block) {
        gen.forRange("i", 0, len, (i2) => {
          cxt.subschema({
            keyword: "contains",
            dataProp: i2,
            dataPropType: util_1.Type.Num,
            compositeRule: true
          }, _valid);
          block();
        });
      }
      function checkLimits(count2) {
        gen.code((0, codegen_1._)`${count2}++`);
        if (max2 === void 0) {
          gen.if((0, codegen_1._)`${count2} >= ${min2}`, () => gen.assign(valid, true).break());
        } else {
          gen.if((0, codegen_1._)`${count2} > ${max2}`, () => gen.assign(valid, false).break());
          if (min2 === 1)
            gen.assign(valid, true);
          else
            gen.if((0, codegen_1._)`${count2} >= ${min2}`, () => gen.assign(valid, true));
        }
      }
    }
  };
  contains$1.default = def;
  return contains$1;
}
var dependencies$1 = {};
var hasRequiredDependencies$1;
function requireDependencies$1() {
  if (hasRequiredDependencies$1) return dependencies$1;
  hasRequiredDependencies$1 = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
    const codegen_1 = /* @__PURE__ */ requireCodegen$1();
    const util_1 = /* @__PURE__ */ requireUtil$1();
    const code_1 = /* @__PURE__ */ requireCode$2();
    exports.error = {
      message: ({ params: { property, depsCount, deps } }) => {
        const property_ies = depsCount === 1 ? "property" : "properties";
        return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;
      },
      params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`
      // TODO change to reference
    };
    const def = {
      keyword: "dependencies",
      type: "object",
      schemaType: "object",
      error: exports.error,
      code(cxt) {
        const [propDeps, schDeps] = splitDependencies(cxt);
        validatePropertyDeps(cxt, propDeps);
        validateSchemaDeps(cxt, schDeps);
      }
    };
    function splitDependencies({ schema }) {
      const propertyDeps = {};
      const schemaDeps = {};
      for (const key in schema) {
        if (key === "__proto__")
          continue;
        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
        deps[key] = schema[key];
      }
      return [propertyDeps, schemaDeps];
    }
    function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
      const { gen, data: data2, it: it2 } = cxt;
      if (Object.keys(propertyDeps).length === 0)
        return;
      const missing = gen.let("missing");
      for (const prop in propertyDeps) {
        const deps = propertyDeps[prop];
        if (deps.length === 0)
          continue;
        const hasProperty = (0, code_1.propertyInData)(gen, data2, prop, it2.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it2.allErrors) {
          gen.if(hasProperty, () => {
            for (const depProp of deps) {
              (0, code_1.checkReportMissingProp)(cxt, depProp);
            }
          });
        } else {
          gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
          (0, code_1.reportMissingProp)(cxt, missing);
          gen.else();
        }
      }
    }
    exports.validatePropertyDeps = validatePropertyDeps;
    function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
      const { gen, data: data2, keyword: keyword2, it: it2 } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it2, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data2, prop, it2.opts.ownProperties),
          () => {
            const schCxt = cxt.subschema({ keyword: keyword2, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
          },
          () => gen.var(valid, true)
          // TODO var
        );
        cxt.ok(valid);
      }
    }
    exports.validateSchemaDeps = validateSchemaDeps;
    exports.default = def;
  })(dependencies$1);
  return dependencies$1;
}
var propertyNames$1 = {};
var hasRequiredPropertyNames$1;
function requirePropertyNames$1() {
  if (hasRequiredPropertyNames$1) return propertyNames$1;
  hasRequiredPropertyNames$1 = 1;
  Object.defineProperty(propertyNames$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const error = {
    message: "property name must be valid",
    params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
  };
  const def = {
    keyword: "propertyNames",
    type: "object",
    schemaType: ["object", "boolean"],
    error,
    code(cxt) {
      const { gen, schema, data: data2, it: it2 } = cxt;
      if ((0, util_1.alwaysValidSchema)(it2, schema))
        return;
      const valid = gen.name("valid");
      gen.forIn("key", data2, (key) => {
        cxt.setParams({ propertyName: key });
        cxt.subschema({
          keyword: "propertyNames",
          data: key,
          dataTypes: ["string"],
          propertyName: key,
          compositeRule: true
        }, valid);
        gen.if((0, codegen_1.not)(valid), () => {
          cxt.error(true);
          if (!it2.allErrors)
            gen.break();
        });
      });
      cxt.ok(valid);
    }
  };
  propertyNames$1.default = def;
  return propertyNames$1;
}
var additionalProperties$2 = {};
var hasRequiredAdditionalProperties$1;
function requireAdditionalProperties$1() {
  if (hasRequiredAdditionalProperties$1) return additionalProperties$2;
  hasRequiredAdditionalProperties$1 = 1;
  Object.defineProperty(additionalProperties$2, "__esModule", { value: true });
  const code_1 = /* @__PURE__ */ requireCode$2();
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const names_1 = /* @__PURE__ */ requireNames$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const error = {
    message: "must NOT have additional properties",
    params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`
  };
  const def = {
    keyword: "additionalProperties",
    type: ["object"],
    schemaType: ["boolean", "object"],
    allowUndefined: true,
    trackErrors: true,
    error,
    code(cxt) {
      const { gen, schema, parentSchema, data: data2, errsCount, it: it2 } = cxt;
      if (!errsCount)
        throw new Error("ajv implementation error");
      const { allErrors, opts } = it2;
      it2.props = true;
      if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it2, schema))
        return;
      const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
      const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
      checkAdditionalProperties();
      cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
      function checkAdditionalProperties() {
        gen.forIn("key", data2, (key) => {
          if (!props.length && !patProps.length)
            additionalPropertyCode(key);
          else
            gen.if(isAdditional(key), () => additionalPropertyCode(key));
        });
      }
      function isAdditional(key) {
        let definedProp;
        if (props.length > 8) {
          const propsSchema = (0, util_1.schemaRefOrVal)(it2, parentSchema.properties, "properties");
          definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
        } else if (props.length) {
          definedProp = (0, codegen_1.or)(...props.map((p2) => (0, codegen_1._)`${key} === ${p2}`));
        } else {
          definedProp = codegen_1.nil;
        }
        if (patProps.length) {
          definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p2) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p2)}.test(${key})`));
        }
        return (0, codegen_1.not)(definedProp);
      }
      function deleteAdditional(key) {
        gen.code((0, codegen_1._)`delete ${data2}[${key}]`);
      }
      function additionalPropertyCode(key) {
        if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
          deleteAdditional(key);
          return;
        }
        if (schema === false) {
          cxt.setParams({ additionalProperty: key });
          cxt.error();
          if (!allErrors)
            gen.break();
          return;
        }
        if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it2, schema)) {
          const valid = gen.name("valid");
          if (opts.removeAdditional === "failing") {
            applyAdditionalSchema(key, valid, false);
            gen.if((0, codegen_1.not)(valid), () => {
              cxt.reset();
              deleteAdditional(key);
            });
          } else {
            applyAdditionalSchema(key, valid);
            if (!allErrors)
              gen.if((0, codegen_1.not)(valid), () => gen.break());
          }
        }
      }
      function applyAdditionalSchema(key, valid, errors2) {
        const subschema2 = {
          keyword: "additionalProperties",
          dataProp: key,
          dataPropType: util_1.Type.Str
        };
        if (errors2 === false) {
          Object.assign(subschema2, {
            compositeRule: true,
            createErrors: false,
            allErrors: false
          });
        }
        cxt.subschema(subschema2, valid);
      }
    }
  };
  additionalProperties$2.default = def;
  return additionalProperties$2;
}
var properties$4 = {};
var hasRequiredProperties$1;
function requireProperties$1() {
  if (hasRequiredProperties$1) return properties$4;
  hasRequiredProperties$1 = 1;
  Object.defineProperty(properties$4, "__esModule", { value: true });
  const validate_1 = /* @__PURE__ */ requireValidate$1();
  const code_1 = /* @__PURE__ */ requireCode$2();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const additionalProperties_1 = /* @__PURE__ */ requireAdditionalProperties$1();
  const def = {
    keyword: "properties",
    type: "object",
    schemaType: "object",
    code(cxt) {
      const { gen, schema, parentSchema, data: data2, it: it2 } = cxt;
      if (it2.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
        additionalProperties_1.default.code(new validate_1.KeywordCxt(it2, additionalProperties_1.default, "additionalProperties"));
      }
      const allProps = (0, code_1.allSchemaProperties)(schema);
      for (const prop of allProps) {
        it2.definedProperties.add(prop);
      }
      if (it2.opts.unevaluated && allProps.length && it2.props !== true) {
        it2.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it2.props);
      }
      const properties2 = allProps.filter((p2) => !(0, util_1.alwaysValidSchema)(it2, schema[p2]));
      if (properties2.length === 0)
        return;
      const valid = gen.name("valid");
      for (const prop of properties2) {
        if (hasDefault(prop)) {
          applyPropertySchema(prop);
        } else {
          gen.if((0, code_1.propertyInData)(gen, data2, prop, it2.opts.ownProperties));
          applyPropertySchema(prop);
          if (!it2.allErrors)
            gen.else().var(valid, true);
          gen.endIf();
        }
        cxt.it.definedProperties.add(prop);
        cxt.ok(valid);
      }
      function hasDefault(prop) {
        return it2.opts.useDefaults && !it2.compositeRule && schema[prop].default !== void 0;
      }
      function applyPropertySchema(prop) {
        cxt.subschema({
          keyword: "properties",
          schemaProp: prop,
          dataProp: prop
        }, valid);
      }
    }
  };
  properties$4.default = def;
  return properties$4;
}
var patternProperties$1 = {};
var hasRequiredPatternProperties$1;
function requirePatternProperties$1() {
  if (hasRequiredPatternProperties$1) return patternProperties$1;
  hasRequiredPatternProperties$1 = 1;
  Object.defineProperty(patternProperties$1, "__esModule", { value: true });
  const code_1 = /* @__PURE__ */ requireCode$2();
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const util_2 = /* @__PURE__ */ requireUtil$1();
  const def = {
    keyword: "patternProperties",
    type: "object",
    schemaType: "object",
    code(cxt) {
      const { gen, schema, data: data2, parentSchema, it: it2 } = cxt;
      const { opts } = it2;
      const patterns = (0, code_1.allSchemaProperties)(schema);
      const alwaysValidPatterns = patterns.filter((p2) => (0, util_1.alwaysValidSchema)(it2, schema[p2]));
      if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it2.opts.unevaluated || it2.props === true)) {
        return;
      }
      const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
      const valid = gen.name("valid");
      if (it2.props !== true && !(it2.props instanceof codegen_1.Name)) {
        it2.props = (0, util_2.evaluatedPropsToName)(gen, it2.props);
      }
      const { props } = it2;
      validatePatternProperties();
      function validatePatternProperties() {
        for (const pat of patterns) {
          if (checkProperties)
            checkMatchingProperties(pat);
          if (it2.allErrors) {
            validateProperties(pat);
          } else {
            gen.var(valid, true);
            validateProperties(pat);
            gen.if(valid);
          }
        }
      }
      function checkMatchingProperties(pat) {
        for (const prop in checkProperties) {
          if (new RegExp(pat).test(prop)) {
            (0, util_1.checkStrictMode)(it2, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
          }
        }
      }
      function validateProperties(pat) {
        gen.forIn("key", data2, (key) => {
          gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
            const alwaysValid = alwaysValidPatterns.includes(pat);
            if (!alwaysValid) {
              cxt.subschema({
                keyword: "patternProperties",
                schemaProp: pat,
                dataProp: key,
                dataPropType: util_2.Type.Str
              }, valid);
            }
            if (it2.opts.unevaluated && props !== true) {
              gen.assign((0, codegen_1._)`${props}[${key}]`, true);
            } else if (!alwaysValid && !it2.allErrors) {
              gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
          });
        });
      }
    }
  };
  patternProperties$1.default = def;
  return patternProperties$1;
}
var not$1 = {};
var hasRequiredNot$1;
function requireNot$1() {
  if (hasRequiredNot$1) return not$1;
  hasRequiredNot$1 = 1;
  Object.defineProperty(not$1, "__esModule", { value: true });
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const def = {
    keyword: "not",
    schemaType: ["object", "boolean"],
    trackErrors: true,
    code(cxt) {
      const { gen, schema, it: it2 } = cxt;
      if ((0, util_1.alwaysValidSchema)(it2, schema)) {
        cxt.fail();
        return;
      }
      const valid = gen.name("valid");
      cxt.subschema({
        keyword: "not",
        compositeRule: true,
        createErrors: false,
        allErrors: false
      }, valid);
      cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
    },
    error: { message: "must NOT be valid" }
  };
  not$1.default = def;
  return not$1;
}
var anyOf$1 = {};
var hasRequiredAnyOf$1;
function requireAnyOf$1() {
  if (hasRequiredAnyOf$1) return anyOf$1;
  hasRequiredAnyOf$1 = 1;
  Object.defineProperty(anyOf$1, "__esModule", { value: true });
  const code_1 = /* @__PURE__ */ requireCode$2();
  const def = {
    keyword: "anyOf",
    schemaType: "array",
    trackErrors: true,
    code: code_1.validateUnion,
    error: { message: "must match a schema in anyOf" }
  };
  anyOf$1.default = def;
  return anyOf$1;
}
var oneOf$1 = {};
var hasRequiredOneOf$1;
function requireOneOf$1() {
  if (hasRequiredOneOf$1) return oneOf$1;
  hasRequiredOneOf$1 = 1;
  Object.defineProperty(oneOf$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const error = {
    message: "must match exactly one schema in oneOf",
    params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`
  };
  const def = {
    keyword: "oneOf",
    schemaType: "array",
    trackErrors: true,
    error,
    code(cxt) {
      const { gen, schema, parentSchema, it: it2 } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      if (it2.opts.discriminator && parentSchema.discriminator)
        return;
      const schArr = schema;
      const valid = gen.let("valid", false);
      const passing = gen.let("passing", null);
      const schValid = gen.name("_valid");
      cxt.setParams({ passing });
      gen.block(validateOneOf);
      cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
      function validateOneOf() {
        schArr.forEach((sch, i2) => {
          let schCxt;
          if ((0, util_1.alwaysValidSchema)(it2, sch)) {
            gen.var(schValid, true);
          } else {
            schCxt = cxt.subschema({
              keyword: "oneOf",
              schemaProp: i2,
              compositeRule: true
            }, schValid);
          }
          if (i2 > 0) {
            gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i2}]`).else();
          }
          gen.if(schValid, () => {
            gen.assign(valid, true);
            gen.assign(passing, i2);
            if (schCxt)
              cxt.mergeEvaluated(schCxt, codegen_1.Name);
          });
        });
      }
    }
  };
  oneOf$1.default = def;
  return oneOf$1;
}
var allOf$1 = {};
var hasRequiredAllOf$1;
function requireAllOf$1() {
  if (hasRequiredAllOf$1) return allOf$1;
  hasRequiredAllOf$1 = 1;
  Object.defineProperty(allOf$1, "__esModule", { value: true });
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const def = {
    keyword: "allOf",
    schemaType: "array",
    code(cxt) {
      const { gen, schema, it: it2 } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const valid = gen.name("valid");
      schema.forEach((sch, i2) => {
        if ((0, util_1.alwaysValidSchema)(it2, sch))
          return;
        const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i2 }, valid);
        cxt.ok(valid);
        cxt.mergeEvaluated(schCxt);
      });
    }
  };
  allOf$1.default = def;
  return allOf$1;
}
var _if$1 = {};
var hasRequired_if$1;
function require_if$1() {
  if (hasRequired_if$1) return _if$1;
  hasRequired_if$1 = 1;
  Object.defineProperty(_if$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const error = {
    message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,
    params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`
  };
  const def = {
    keyword: "if",
    schemaType: ["object", "boolean"],
    trackErrors: true,
    error,
    code(cxt) {
      const { gen, parentSchema, it: it2 } = cxt;
      if (parentSchema.then === void 0 && parentSchema.else === void 0) {
        (0, util_1.checkStrictMode)(it2, '"if" without "then" and "else" is ignored');
      }
      const hasThen = hasSchema(it2, "then");
      const hasElse = hasSchema(it2, "else");
      if (!hasThen && !hasElse)
        return;
      const valid = gen.let("valid", true);
      const schValid = gen.name("_valid");
      validateIf();
      cxt.reset();
      if (hasThen && hasElse) {
        const ifClause = gen.let("ifClause");
        cxt.setParams({ ifClause });
        gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
      } else if (hasThen) {
        gen.if(schValid, validateClause("then"));
      } else {
        gen.if((0, codegen_1.not)(schValid), validateClause("else"));
      }
      cxt.pass(valid, () => cxt.error(true));
      function validateIf() {
        const schCxt = cxt.subschema({
          keyword: "if",
          compositeRule: true,
          createErrors: false,
          allErrors: false
        }, schValid);
        cxt.mergeEvaluated(schCxt);
      }
      function validateClause(keyword2, ifClause) {
        return () => {
          const schCxt = cxt.subschema({ keyword: keyword2 }, schValid);
          gen.assign(valid, schValid);
          cxt.mergeValidEvaluated(schCxt, valid);
          if (ifClause)
            gen.assign(ifClause, (0, codegen_1._)`${keyword2}`);
          else
            cxt.setParams({ ifClause: keyword2 });
        };
      }
    }
  };
  function hasSchema(it2, keyword2) {
    const schema = it2.schema[keyword2];
    return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it2, schema);
  }
  _if$1.default = def;
  return _if$1;
}
var thenElse$1 = {};
var hasRequiredThenElse$1;
function requireThenElse$1() {
  if (hasRequiredThenElse$1) return thenElse$1;
  hasRequiredThenElse$1 = 1;
  Object.defineProperty(thenElse$1, "__esModule", { value: true });
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const def = {
    keyword: ["then", "else"],
    schemaType: ["object", "boolean"],
    code({ keyword: keyword2, parentSchema, it: it2 }) {
      if (parentSchema.if === void 0)
        (0, util_1.checkStrictMode)(it2, `"${keyword2}" without "if" is ignored`);
    }
  };
  thenElse$1.default = def;
  return thenElse$1;
}
var hasRequiredApplicator$1;
function requireApplicator$1() {
  if (hasRequiredApplicator$1) return applicator$1;
  hasRequiredApplicator$1 = 1;
  Object.defineProperty(applicator$1, "__esModule", { value: true });
  const additionalItems_1 = /* @__PURE__ */ requireAdditionalItems$1();
  const prefixItems_1 = /* @__PURE__ */ requirePrefixItems$1();
  const items_1 = /* @__PURE__ */ requireItems$1();
  const items2020_1 = /* @__PURE__ */ requireItems2020$1();
  const contains_1 = /* @__PURE__ */ requireContains$1();
  const dependencies_1 = /* @__PURE__ */ requireDependencies$1();
  const propertyNames_1 = /* @__PURE__ */ requirePropertyNames$1();
  const additionalProperties_1 = /* @__PURE__ */ requireAdditionalProperties$1();
  const properties_1 = /* @__PURE__ */ requireProperties$1();
  const patternProperties_1 = /* @__PURE__ */ requirePatternProperties$1();
  const not_1 = /* @__PURE__ */ requireNot$1();
  const anyOf_1 = /* @__PURE__ */ requireAnyOf$1();
  const oneOf_1 = /* @__PURE__ */ requireOneOf$1();
  const allOf_1 = /* @__PURE__ */ requireAllOf$1();
  const if_1 = /* @__PURE__ */ require_if$1();
  const thenElse_1 = /* @__PURE__ */ requireThenElse$1();
  function getApplicator(draft2020 = false) {
    const applicator2 = [
      // any
      not_1.default,
      anyOf_1.default,
      oneOf_1.default,
      allOf_1.default,
      if_1.default,
      thenElse_1.default,
      // object
      propertyNames_1.default,
      additionalProperties_1.default,
      dependencies_1.default,
      properties_1.default,
      patternProperties_1.default
    ];
    if (draft2020)
      applicator2.push(prefixItems_1.default, items2020_1.default);
    else
      applicator2.push(additionalItems_1.default, items_1.default);
    applicator2.push(contains_1.default);
    return applicator2;
  }
  applicator$1.default = getApplicator;
  return applicator$1;
}
var format$3 = {};
var format$2 = {};
var hasRequiredFormat$3;
function requireFormat$3() {
  if (hasRequiredFormat$3) return format$2;
  hasRequiredFormat$3 = 1;
  Object.defineProperty(format$2, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const error = {
    message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,
    params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`
  };
  const def = {
    keyword: "format",
    type: ["number", "string"],
    schemaType: "string",
    $data: true,
    error,
    code(cxt, ruleType) {
      const { gen, data: data2, $data, schema, schemaCode, it: it2 } = cxt;
      const { opts, errSchemaPath, schemaEnv, self: self2 } = it2;
      if (!opts.validateFormats)
        return;
      if ($data)
        validate$DataFormat();
      else
        validateFormat();
      function validate$DataFormat() {
        const fmts = gen.scopeValue("formats", {
          ref: self2.formats,
          code: opts.code.formats
        });
        const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
        const fType = gen.let("fType");
        const format2 = gen.let("format");
        gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format2, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format2, fDef));
        cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
        function unknownFmt() {
          if (opts.strictSchema === false)
            return codegen_1.nil;
          return (0, codegen_1._)`${schemaCode} && !${format2}`;
        }
        function invalidFmt() {
          const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format2}(${data2}) : ${format2}(${data2}))` : (0, codegen_1._)`${format2}(${data2})`;
          const validData = (0, codegen_1._)`(typeof ${format2} == "function" ? ${callFormat} : ${format2}.test(${data2}))`;
          return (0, codegen_1._)`${format2} && ${format2} !== true && ${fType} === ${ruleType} && !${validData}`;
        }
      }
      function validateFormat() {
        const formatDef = self2.formats[schema];
        if (!formatDef) {
          unknownFormat();
          return;
        }
        if (formatDef === true)
          return;
        const [fmtType, format2, fmtRef] = getFormat(formatDef);
        if (fmtType === ruleType)
          cxt.pass(validCondition());
        function unknownFormat() {
          if (opts.strictSchema === false) {
            self2.logger.warn(unknownMsg());
            return;
          }
          throw new Error(unknownMsg());
          function unknownMsg() {
            return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
          }
        }
        function getFormat(fmtDef) {
          const code2 = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0;
          const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code: code2 });
          if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
            return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`];
          }
          return ["string", fmtDef, fmt];
        }
        function validCondition() {
          if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
            if (!schemaEnv.$async)
              throw new Error("async format in sync schema");
            return (0, codegen_1._)`await ${fmtRef}(${data2})`;
          }
          return typeof format2 == "function" ? (0, codegen_1._)`${fmtRef}(${data2})` : (0, codegen_1._)`${fmtRef}.test(${data2})`;
        }
      }
    }
  };
  format$2.default = def;
  return format$2;
}
var hasRequiredFormat$2;
function requireFormat$2() {
  if (hasRequiredFormat$2) return format$3;
  hasRequiredFormat$2 = 1;
  Object.defineProperty(format$3, "__esModule", { value: true });
  const format_1 = /* @__PURE__ */ requireFormat$3();
  const format2 = [format_1.default];
  format$3.default = format2;
  return format$3;
}
var metadata$1 = {};
var hasRequiredMetadata$1;
function requireMetadata$1() {
  if (hasRequiredMetadata$1) return metadata$1;
  hasRequiredMetadata$1 = 1;
  Object.defineProperty(metadata$1, "__esModule", { value: true });
  metadata$1.contentVocabulary = metadata$1.metadataVocabulary = void 0;
  metadata$1.metadataVocabulary = [
    "title",
    "description",
    "default",
    "deprecated",
    "readOnly",
    "writeOnly",
    "examples"
  ];
  metadata$1.contentVocabulary = [
    "contentMediaType",
    "contentEncoding",
    "contentSchema"
  ];
  return metadata$1;
}
var hasRequiredDraft7$1;
function requireDraft7$1() {
  if (hasRequiredDraft7$1) return draft7$1;
  hasRequiredDraft7$1 = 1;
  Object.defineProperty(draft7$1, "__esModule", { value: true });
  const core_1 = /* @__PURE__ */ requireCore$2();
  const validation_1 = /* @__PURE__ */ requireValidation$1();
  const applicator_1 = /* @__PURE__ */ requireApplicator$1();
  const format_1 = /* @__PURE__ */ requireFormat$2();
  const metadata_1 = /* @__PURE__ */ requireMetadata$1();
  const draft7Vocabularies = [
    core_1.default,
    validation_1.default,
    (0, applicator_1.default)(),
    format_1.default,
    metadata_1.metadataVocabulary,
    metadata_1.contentVocabulary
  ];
  draft7$1.default = draft7Vocabularies;
  return draft7$1;
}
var discriminator$1 = {};
var types$1 = {};
var hasRequiredTypes$1;
function requireTypes$1() {
  if (hasRequiredTypes$1) return types$1;
  hasRequiredTypes$1 = 1;
  Object.defineProperty(types$1, "__esModule", { value: true });
  types$1.DiscrError = void 0;
  var DiscrError;
  (function(DiscrError2) {
    DiscrError2["Tag"] = "tag";
    DiscrError2["Mapping"] = "mapping";
  })(DiscrError || (types$1.DiscrError = DiscrError = {}));
  return types$1;
}
var hasRequiredDiscriminator$1;
function requireDiscriminator$1() {
  if (hasRequiredDiscriminator$1) return discriminator$1;
  hasRequiredDiscriminator$1 = 1;
  Object.defineProperty(discriminator$1, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen$1();
  const types_1 = /* @__PURE__ */ requireTypes$1();
  const compile_12 = /* @__PURE__ */ requireCompile$1();
  const ref_error_1 = /* @__PURE__ */ requireRef_error$1();
  const util_1 = /* @__PURE__ */ requireUtil$1();
  const error = {
    message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,
    params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`
  };
  const def = {
    keyword: "discriminator",
    type: "object",
    schemaType: "object",
    error,
    code(cxt) {
      const { gen, data: data2, schema, parentSchema, it: it2 } = cxt;
      const { oneOf: oneOf2 } = parentSchema;
      if (!it2.opts.discriminator) {
        throw new Error("discriminator: requires discriminator option");
      }
      const tagName = schema.propertyName;
      if (typeof tagName != "string")
        throw new Error("discriminator: requires propertyName");
      if (schema.mapping)
        throw new Error("discriminator: mapping is not supported");
      if (!oneOf2)
        throw new Error("discriminator: requires oneOf keyword");
      const valid = gen.let("valid", false);
      const tag = gen.const("tag", (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(tagName)}`);
      gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
      cxt.ok(valid);
      function validateMapping() {
        const mapping = getMapping();
        gen.if(false);
        for (const tagValue in mapping) {
          gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);
          gen.assign(valid, applyTagSchema(mapping[tagValue]));
        }
        gen.else();
        cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
        gen.endIf();
      }
      function applyTagSchema(schemaProp) {
        const _valid = gen.name("valid");
        const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
        cxt.mergeEvaluated(schCxt, codegen_1.Name);
        return _valid;
      }
      function getMapping() {
        var _a2;
        const oneOfMapping = {};
        const topRequired = hasRequired(parentSchema);
        let tagRequired = true;
        for (let i2 = 0; i2 < oneOf2.length; i2++) {
          let sch = oneOf2[i2];
          if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it2.self.RULES)) {
            const ref2 = sch.$ref;
            sch = compile_12.resolveRef.call(it2.self, it2.schemaEnv.root, it2.baseId, ref2);
            if (sch instanceof compile_12.SchemaEnv)
              sch = sch.schema;
            if (sch === void 0)
              throw new ref_error_1.default(it2.opts.uriResolver, it2.baseId, ref2);
          }
          const propSch = (_a2 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a2 === void 0 ? void 0 : _a2[tagName];
          if (typeof propSch != "object") {
            throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
          }
          tagRequired = tagRequired && (topRequired || hasRequired(sch));
          addMappings(propSch, i2);
        }
        if (!tagRequired)
          throw new Error(`discriminator: "${tagName}" must be required`);
        return oneOfMapping;
        function hasRequired({ required: required2 }) {
          return Array.isArray(required2) && required2.includes(tagName);
        }
        function addMappings(sch, i2) {
          if (sch.const) {
            addMapping(sch.const, i2);
          } else if (sch.enum) {
            for (const tagValue of sch.enum) {
              addMapping(tagValue, i2);
            }
          } else {
            throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
          }
        }
        function addMapping(tagValue, i2) {
          if (typeof tagValue != "string" || tagValue in oneOfMapping) {
            throw new Error(`discriminator: "${tagName}" values must be unique strings`);
          }
          oneOfMapping[tagValue] = i2;
        }
      }
    }
  };
  discriminator$1.default = def;
  return discriminator$1;
}
const $schema$1 = "http://json-schema.org/draft-07/schema#";
const $id$2 = "http://json-schema.org/draft-07/schema#";
const title$1 = "Core schema meta-schema";
const definitions$1 = { "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$2 = ["object", "boolean"];
const properties$3 = { "$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$$3$1 = {
  $schema: $schema$1,
  $id: $id$2,
  title: title$1,
  definitions: definitions$1,
  type: type$2,
  properties: properties$3,
  "default": true
};
var hasRequiredAjv$1;
function requireAjv$1() {
  if (hasRequiredAjv$1) return ajv$1.exports;
  hasRequiredAjv$1 = 1;
  (function(module, exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
    const core_1 = /* @__PURE__ */ requireCore$3();
    const draft7_1 = /* @__PURE__ */ requireDraft7$1();
    const discriminator_1 = /* @__PURE__ */ requireDiscriminator$1();
    const draft7MetaSchema = require$$3$1;
    const META_SUPPORT_DATA = ["/properties"];
    const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
    class Ajv2 extends core_1.default {
      _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v2) => this.addVocabulary(v2));
        if (this.opts.discriminator)
          this.addKeyword(discriminator_1.default);
      }
      _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
          return;
        const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema;
        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
      }
      defaultMeta() {
        return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);
      }
    }
    exports.Ajv = Ajv2;
    module.exports = exports = Ajv2;
    module.exports.Ajv = Ajv2;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = Ajv2;
    var validate_1 = /* @__PURE__ */ requireValidate$1();
    Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
      return validate_1.KeywordCxt;
    } });
    var codegen_1 = /* @__PURE__ */ requireCodegen$1();
    Object.defineProperty(exports, "_", { enumerable: true, get: function() {
      return codegen_1._;
    } });
    Object.defineProperty(exports, "str", { enumerable: true, get: function() {
      return codegen_1.str;
    } });
    Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
      return codegen_1.stringify;
    } });
    Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
      return codegen_1.nil;
    } });
    Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
      return codegen_1.Name;
    } });
    Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
      return codegen_1.CodeGen;
    } });
    var validation_error_1 = /* @__PURE__ */ requireValidation_error$1();
    Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() {
      return validation_error_1.default;
    } });
    var ref_error_1 = /* @__PURE__ */ requireRef_error$1();
    Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() {
      return ref_error_1.default;
    } });
  })(ajv$1, ajv$1.exports);
  return ajv$1.exports;
}
var ajvExports = /* @__PURE__ */ requireAjv$1();
const Ajv = /* @__PURE__ */ getDefaultExportFromCjs(ajvExports);
var dist = { exports: {} };
var formats = {};
var hasRequiredFormats;
function requireFormats() {
  if (hasRequiredFormats) return formats;
  hasRequiredFormats = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;
    function fmtDef(validate2, compare) {
      return { validate: validate2, compare };
    }
    exports.fullFormats = {
      // date: http://tools.ietf.org/html/rfc3339#section-5.6
      date: fmtDef(date2, compareDate),
      // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
      time: fmtDef(getTime(true), compareTime),
      "date-time": fmtDef(getDateTime(true), compareDateTime),
      "iso-time": fmtDef(getTime(), compareIsoTime),
      "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime),
      // duration: https://tools.ietf.org/html/rfc3339#appendix-A
      duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,
      uri: uri2,
      "uri-reference": /^(?:[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,
      // uri-template: https://tools.ietf.org/html/rfc6570
      "uri-template": /^(?:(?:[^\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,
      // For the source: https://gist.github.com/dperini/729294
      // For test cases: https://mathiasbynens.be/demo/url-regex
      url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
      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: /^(?=.{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,
      // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
      ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,
      ipv6: /^((([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}))|:)))$/i,
      regex,
      // uuid: http://tools.ietf.org/html/rfc4122
      uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
      // JSON-pointer: https://tools.ietf.org/html/rfc6901
      // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
      "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
      "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
      // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
      "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
      // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types
      // byte: https://github.com/miguelmota/is-base64
      byte,
      // signed 32 bit integer
      int32: { type: "number", validate: validateInt32 },
      // signed 64 bit integer
      int64: { type: "number", validate: validateInt64 },
      // C-type float
      float: { type: "number", validate: validateNumber },
      // C-type double
      double: { type: "number", validate: validateNumber },
      // hint to the UI to hide input strings
      password: true,
      // unchecked string payload
      binary: true
    };
    exports.fastFormats = {
      ...exports.fullFormats,
      date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
      time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime),
      "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime),
      "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime),
      "iso-date-time": fmtDef(/^\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, compareIsoDateTime),
      // 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,
      // 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 'wilful 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
    };
    exports.formatNames = Object.keys(exports.fullFormats);
    function isLeapYear(year) {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    }
    const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
    const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    function date2(str) {
      const matches = DATE.exec(str);
      if (!matches)
        return false;
      const year = +matches[1];
      const month = +matches[2];
      const day = +matches[3];
      return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
    }
    function compareDate(d1, d2) {
      if (!(d1 && d2))
        return void 0;
      if (d1 > d2)
        return 1;
      if (d1 < d2)
        return -1;
      return 0;
    }
    const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
    function getTime(strictTimeZone) {
      return function time2(str) {
        const matches = TIME.exec(str);
        if (!matches)
          return false;
        const hr2 = +matches[1];
        const min2 = +matches[2];
        const sec = +matches[3];
        const tz = matches[4];
        const tzSign = matches[5] === "-" ? -1 : 1;
        const tzH = +(matches[6] || 0);
        const tzM = +(matches[7] || 0);
        if (tzH > 23 || tzM > 59 || strictTimeZone && !tz)
          return false;
        if (hr2 <= 23 && min2 <= 59 && sec < 60)
          return true;
        const utcMin = min2 - tzM * tzSign;
        const utcHr = hr2 - tzH * tzSign - (utcMin < 0 ? 1 : 0);
        return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;
      };
    }
    function compareTime(s1, s2) {
      if (!(s1 && s2))
        return void 0;
      const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf();
      const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf();
      if (!(t1 && t2))
        return void 0;
      return t1 - t2;
    }
    function compareIsoTime(t1, t2) {
      if (!(t1 && t2))
        return void 0;
      const a1 = TIME.exec(t1);
      const a2 = TIME.exec(t2);
      if (!(a1 && a2))
        return void 0;
      t1 = a1[1] + a1[2] + a1[3];
      t2 = a2[1] + a2[2] + a2[3];
      if (t1 > t2)
        return 1;
      if (t1 < t2)
        return -1;
      return 0;
    }
    const DATE_TIME_SEPARATOR = /t|\s/i;
    function getDateTime(strictTimeZone) {
      const time2 = getTime(strictTimeZone);
      return function date_time(str) {
        const dateTime = str.split(DATE_TIME_SEPARATOR);
        return dateTime.length === 2 && date2(dateTime[0]) && time2(dateTime[1]);
      };
    }
    function compareDateTime(dt1, dt2) {
      if (!(dt1 && dt2))
        return void 0;
      const d1 = new Date(dt1).valueOf();
      const d2 = new Date(dt2).valueOf();
      if (!(d1 && d2))
        return void 0;
      return d1 - d2;
    }
    function compareIsoDateTime(dt1, dt2) {
      if (!(dt1 && dt2))
        return void 0;
      const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);
      const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);
      const res = compareDate(d1, d2);
      if (res === void 0)
        return void 0;
      return res || compareTime(t1, t2);
    }
    const NOT_URI_FRAGMENT = /\/|:/;
    const 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;
    function uri2(str) {
      return NOT_URI_FRAGMENT.test(str) && URI.test(str);
    }
    const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
    function byte(str) {
      BYTE.lastIndex = 0;
      return BYTE.test(str);
    }
    const MIN_INT32 = -2147483648;
    const MAX_INT32 = 2 ** 31 - 1;
    function validateInt32(value) {
      return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
    }
    function validateInt64(value) {
      return Number.isInteger(value);
    }
    function validateNumber() {
      return true;
    }
    const Z_ANCHOR = /[^\\]\\Z/;
    function regex(str) {
      if (Z_ANCHOR.test(str))
        return false;
      try {
        new RegExp(str);
        return true;
      } catch (e2) {
        return false;
      }
    }
  })(formats);
  return formats;
}
var limit = {};
var ajv = { exports: {} };
var core$1 = {};
var validate = {};
var boolSchema = {};
var errors = {};
var codegen = {};
var code$1 = {};
var hasRequiredCode$1;
function requireCode$1() {
  if (hasRequiredCode$1) return code$1;
  hasRequiredCode$1 = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
    class _CodeOrName {
    }
    exports._CodeOrName = _CodeOrName;
    exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
    class Name extends _CodeOrName {
      constructor(s2) {
        super();
        if (!exports.IDENTIFIER.test(s2))
          throw new Error("CodeGen: name must be a valid identifier");
        this.str = s2;
      }
      toString() {
        return this.str;
      }
      emptyStr() {
        return false;
      }
      get names() {
        return { [this.str]: 1 };
      }
    }
    exports.Name = Name;
    class _Code extends _CodeOrName {
      constructor(code2) {
        super();
        this._items = typeof code2 === "string" ? [code2] : code2;
      }
      toString() {
        return this.str;
      }
      emptyStr() {
        if (this._items.length > 1)
          return false;
        const item = this._items[0];
        return item === "" || item === '""';
      }
      get str() {
        var _a2;
        return (_a2 = this._str) !== null && _a2 !== void 0 ? _a2 : this._str = this._items.reduce((s2, c) => `${s2}${c}`, "");
      }
      get names() {
        var _a2;
        return (_a2 = this._names) !== null && _a2 !== void 0 ? _a2 : this._names = this._items.reduce((names2, c) => {
          if (c instanceof Name)
            names2[c.str] = (names2[c.str] || 0) + 1;
          return names2;
        }, {});
      }
    }
    exports._Code = _Code;
    exports.nil = new _Code("");
    function _2(strs, ...args) {
      const code2 = [strs[0]];
      let i2 = 0;
      while (i2 < args.length) {
        addCodeArg(code2, args[i2]);
        code2.push(strs[++i2]);
      }
      return new _Code(code2);
    }
    exports._ = _2;
    const plus = new _Code("+");
    function str(strs, ...args) {
      const expr = [safeStringify(strs[0])];
      let i2 = 0;
      while (i2 < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i2]);
        expr.push(plus, safeStringify(strs[++i2]));
      }
      optimize(expr);
      return new _Code(expr);
    }
    exports.str = str;
    function addCodeArg(code2, arg) {
      if (arg instanceof _Code)
        code2.push(...arg._items);
      else if (arg instanceof Name)
        code2.push(arg);
      else
        code2.push(interpolate(arg));
    }
    exports.addCodeArg = addCodeArg;
    function optimize(expr) {
      let i2 = 1;
      while (i2 < expr.length - 1) {
        if (expr[i2] === plus) {
          const res = mergeExprItems(expr[i2 - 1], expr[i2 + 1]);
          if (res !== void 0) {
            expr.splice(i2 - 1, 3, res);
            continue;
          }
          expr[i2++] = "+";
        }
        i2++;
      }
    }
    function mergeExprItems(a2, b2) {
      if (b2 === '""')
        return a2;
      if (a2 === '""')
        return b2;
      if (typeof a2 == "string") {
        if (b2 instanceof Name || a2[a2.length - 1] !== '"')
          return;
        if (typeof b2 != "string")
          return `${a2.slice(0, -1)}${b2}"`;
        if (b2[0] === '"')
          return a2.slice(0, -1) + b2.slice(1);
        return;
      }
      if (typeof b2 == "string" && b2[0] === '"' && !(a2 instanceof Name))
        return `"${a2}${b2.slice(1)}`;
      return;
    }
    function strConcat(c1, c2) {
      return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`;
    }
    exports.strConcat = strConcat;
    function interpolate(x2) {
      return typeof x2 == "number" || typeof x2 == "boolean" || x2 === null ? x2 : safeStringify(Array.isArray(x2) ? x2.join(",") : x2);
    }
    function stringify(x2) {
      return new _Code(safeStringify(x2));
    }
    exports.stringify = stringify;
    function safeStringify(x2) {
      return JSON.stringify(x2).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
    }
    exports.safeStringify = safeStringify;
    function getProperty(key) {
      return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _2`[${key}]`;
    }
    exports.getProperty = getProperty;
    function getEsmExportName(key) {
      if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
        return new _Code(`${key}`);
      }
      throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
    }
    exports.getEsmExportName = getEsmExportName;
    function regexpCode(rx) {
      return new _Code(rx.toString());
    }
    exports.regexpCode = regexpCode;
  })(code$1);
  return code$1;
}
var scope = {};
var hasRequiredScope;
function requireScope() {
  if (hasRequiredScope) return scope;
  hasRequiredScope = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
    const code_1 = /* @__PURE__ */ requireCode$1();
    class ValueError extends Error {
      constructor(name2) {
        super(`CodeGen: "code" for ${name2} not defined`);
        this.value = name2.value;
      }
    }
    var UsedValueState;
    (function(UsedValueState2) {
      UsedValueState2[UsedValueState2["Started"] = 0] = "Started";
      UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed";
    })(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
    exports.varKinds = {
      const: new code_1.Name("const"),
      let: new code_1.Name("let"),
      var: new code_1.Name("var")
    };
    class Scope {
      constructor({ prefixes, parent } = {}) {
        this._names = {};
        this._prefixes = prefixes;
        this._parent = parent;
      }
      toName(nameOrPrefix) {
        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
      }
      name(prefix) {
        return new code_1.Name(this._newName(prefix));
      }
      _newName(prefix) {
        const ng = this._names[prefix] || this._nameGroup(prefix);
        return `${prefix}${ng.index++}`;
      }
      _nameGroup(prefix) {
        var _a2, _b;
        if (((_b = (_a2 = this._parent) === null || _a2 === void 0 ? void 0 : _a2._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) {
          throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
        }
        return this._names[prefix] = { prefix, index: 0 };
      }
    }
    exports.Scope = Scope;
    class ValueScopeName extends code_1.Name {
      constructor(prefix, nameStr) {
        super(nameStr);
        this.prefix = prefix;
      }
      setValue(value, { property, itemIndex }) {
        this.value = value;
        this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`;
      }
    }
    exports.ValueScopeName = ValueScopeName;
    const line = (0, code_1._)`\n`;
    class ValueScope extends Scope {
      constructor(opts) {
        super(opts);
        this._values = {};
        this._scope = opts.scope;
        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
      }
      get() {
        return this._scope;
      }
      name(prefix) {
        return new ValueScopeName(prefix, this._newName(prefix));
      }
      value(nameOrPrefix, value) {
        var _a2;
        if (value.ref === void 0)
          throw new Error("CodeGen: ref must be passed in value");
        const name2 = this.toName(nameOrPrefix);
        const { prefix } = name2;
        const valueKey = (_a2 = value.key) !== null && _a2 !== void 0 ? _a2 : value.ref;
        let vs2 = this._values[prefix];
        if (vs2) {
          const _name = vs2.get(valueKey);
          if (_name)
            return _name;
        } else {
          vs2 = this._values[prefix] = /* @__PURE__ */ new Map();
        }
        vs2.set(valueKey, name2);
        const s2 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s2.length;
        s2[itemIndex] = value.ref;
        name2.setValue(value, { property: prefix, itemIndex });
        return name2;
      }
      getValue(prefix, keyOrRef) {
        const vs2 = this._values[prefix];
        if (!vs2)
          return;
        return vs2.get(keyOrRef);
      }
      scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name2) => {
          if (name2.scopePath === void 0)
            throw new Error(`CodeGen: name "${name2}" has no value`);
          return (0, code_1._)`${scopeName}${name2.scopePath}`;
        });
      }
      scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name2) => {
          if (name2.value === void 0)
            throw new Error(`CodeGen: name "${name2}" has no value`);
          return name2.value.code;
        }, usedValues, getCode);
      }
      _reduceValues(values, valueCode, usedValues = {}, getCode) {
        let code2 = code_1.nil;
        for (const prefix in values) {
          const vs2 = values[prefix];
          if (!vs2)
            continue;
          const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map();
          vs2.forEach((name2) => {
            if (nameSet.has(name2))
              return;
            nameSet.set(name2, UsedValueState.Started);
            let c = valueCode(name2);
            if (c) {
              const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
              code2 = (0, code_1._)`${code2}${def} ${name2} = ${c};${this.opts._n}`;
            } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name2)) {
              code2 = (0, code_1._)`${code2}${c}${this.opts._n}`;
            } else {
              throw new ValueError(name2);
            }
            nameSet.set(name2, UsedValueState.Completed);
          });
        }
        return code2;
      }
    }
    exports.ValueScope = ValueScope;
  })(scope);
  return scope;
}
var hasRequiredCodegen;
function requireCodegen() {
  if (hasRequiredCodegen) return codegen;
  hasRequiredCodegen = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
    const code_1 = /* @__PURE__ */ requireCode$1();
    const scope_1 = /* @__PURE__ */ requireScope();
    var code_2 = /* @__PURE__ */ requireCode$1();
    Object.defineProperty(exports, "_", { enumerable: true, get: function() {
      return code_2._;
    } });
    Object.defineProperty(exports, "str", { enumerable: true, get: function() {
      return code_2.str;
    } });
    Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() {
      return code_2.strConcat;
    } });
    Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
      return code_2.nil;
    } });
    Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() {
      return code_2.getProperty;
    } });
    Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
      return code_2.stringify;
    } });
    Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() {
      return code_2.regexpCode;
    } });
    Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
      return code_2.Name;
    } });
    var scope_2 = /* @__PURE__ */ requireScope();
    Object.defineProperty(exports, "Scope", { enumerable: true, get: function() {
      return scope_2.Scope;
    } });
    Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() {
      return scope_2.ValueScope;
    } });
    Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() {
      return scope_2.ValueScopeName;
    } });
    Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() {
      return scope_2.varKinds;
    } });
    exports.operators = {
      GT: new code_1._Code(">"),
      GTE: new code_1._Code(">="),
      LT: new code_1._Code("<"),
      LTE: new code_1._Code("<="),
      EQ: new code_1._Code("==="),
      NEQ: new code_1._Code("!=="),
      NOT: new code_1._Code("!"),
      OR: new code_1._Code("||"),
      AND: new code_1._Code("&&"),
      ADD: new code_1._Code("+")
    };
    class Node2 {
      optimizeNodes() {
        return this;
      }
      optimizeNames(_names, _constants) {
        return this;
      }
    }
    class Def extends Node2 {
      constructor(varKind, name2, rhs) {
        super();
        this.varKind = varKind;
        this.name = name2;
        this.rhs = rhs;
      }
      render({ es5, _n: _n2 }) {
        const varKind = es5 ? scope_1.varKinds.var : this.varKind;
        const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
        return `${varKind} ${this.name}${rhs};` + _n2;
      }
      optimizeNames(names2, constants) {
        if (!names2[this.name.str])
          return;
        if (this.rhs)
          this.rhs = optimizeExpr(this.rhs, names2, constants);
        return this;
      }
      get names() {
        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
      }
    }
    class Assign extends Node2 {
      constructor(lhs, rhs, sideEffects) {
        super();
        this.lhs = lhs;
        this.rhs = rhs;
        this.sideEffects = sideEffects;
      }
      render({ _n: _n2 }) {
        return `${this.lhs} = ${this.rhs};` + _n2;
      }
      optimizeNames(names2, constants) {
        if (this.lhs instanceof code_1.Name && !names2[this.lhs.str] && !this.sideEffects)
          return;
        this.rhs = optimizeExpr(this.rhs, names2, constants);
        return this;
      }
      get names() {
        const names2 = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
        return addExprNames(names2, this.rhs);
      }
    }
    class AssignOp extends Assign {
      constructor(lhs, op2, rhs, sideEffects) {
        super(lhs, rhs, sideEffects);
        this.op = op2;
      }
      render({ _n: _n2 }) {
        return `${this.lhs} ${this.op}= ${this.rhs};` + _n2;
      }
    }
    class Label2 extends Node2 {
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n: _n2 }) {
        return `${this.label}:` + _n2;
      }
    }
    class Break extends Node2 {
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n: _n2 }) {
        const label = this.label ? ` ${this.label}` : "";
        return `break${label};` + _n2;
      }
    }
    class Throw extends Node2 {
      constructor(error) {
        super();
        this.error = error;
      }
      render({ _n: _n2 }) {
        return `throw ${this.error};` + _n2;
      }
      get names() {
        return this.error.names;
      }
    }
    class AnyCode extends Node2 {
      constructor(code2) {
        super();
        this.code = code2;
      }
      render({ _n: _n2 }) {
        return `${this.code};` + _n2;
      }
      optimizeNodes() {
        return `${this.code}` ? this : void 0;
      }
      optimizeNames(names2, constants) {
        this.code = optimizeExpr(this.code, names2, constants);
        return this;
      }
      get names() {
        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
      }
    }
    class ParentNode extends Node2 {
      constructor(nodes = []) {
        super();
        this.nodes = nodes;
      }
      render(opts) {
        return this.nodes.reduce((code2, n) => code2 + n.render(opts), "");
      }
      optimizeNodes() {
        const { nodes } = this;
        let i2 = nodes.length;
        while (i2--) {
          const n = nodes[i2].optimizeNodes();
          if (Array.isArray(n))
            nodes.splice(i2, 1, ...n);
          else if (n)
            nodes[i2] = n;
          else
            nodes.splice(i2, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names2, constants) {
        const { nodes } = this;
        let i2 = nodes.length;
        while (i2--) {
          const n = nodes[i2];
          if (n.optimizeNames(names2, constants))
            continue;
          subtractNames(names2, n.names);
          nodes.splice(i2, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      get names() {
        return this.nodes.reduce((names2, n) => addNames(names2, n.names), {});
      }
    }
    class BlockNode extends ParentNode {
      render(opts) {
        return "{" + opts._n + super.render(opts) + "}" + opts._n;
      }
    }
    class Root4 extends ParentNode {
    }
    class Else extends BlockNode {
    }
    Else.kind = "else";
    class If2 extends BlockNode {
      constructor(condition, nodes) {
        super(nodes);
        this.condition = condition;
      }
      render(opts) {
        let code2 = `if(${this.condition})` + super.render(opts);
        if (this.else)
          code2 += "else " + this.else.render(opts);
        return code2;
      }
      optimizeNodes() {
        super.optimizeNodes();
        const cond = this.condition;
        if (cond === true)
          return this.nodes;
        let e2 = this.else;
        if (e2) {
          const ns2 = e2.optimizeNodes();
          e2 = this.else = Array.isArray(ns2) ? new Else(ns2) : ns2;
        }
        if (e2) {
          if (cond === false)
            return e2 instanceof If2 ? e2 : e2.nodes;
          if (this.nodes.length)
            return this;
          return new If2(not2(cond), e2 instanceof If2 ? [e2] : e2.nodes);
        }
        if (cond === false || !this.nodes.length)
          return void 0;
        return this;
      }
      optimizeNames(names2, constants) {
        var _a2;
        this.else = (_a2 = this.else) === null || _a2 === void 0 ? void 0 : _a2.optimizeNames(names2, constants);
        if (!(super.optimizeNames(names2, constants) || this.else))
          return;
        this.condition = optimizeExpr(this.condition, names2, constants);
        return this;
      }
      get names() {
        const names2 = super.names;
        addExprNames(names2, this.condition);
        if (this.else)
          addNames(names2, this.else.names);
        return names2;
      }
    }
    If2.kind = "if";
    class For extends BlockNode {
    }
    For.kind = "for";
    class ForLoop extends For {
      constructor(iteration) {
        super();
        this.iteration = iteration;
      }
      render(opts) {
        return `for(${this.iteration})` + super.render(opts);
      }
      optimizeNames(names2, constants) {
        if (!super.optimizeNames(names2, constants))
          return;
        this.iteration = optimizeExpr(this.iteration, names2, constants);
        return this;
      }
      get names() {
        return addNames(super.names, this.iteration.names);
      }
    }
    class ForRange extends For {
      constructor(varKind, name2, from, to2) {
        super();
        this.varKind = varKind;
        this.name = name2;
        this.from = from;
        this.to = to2;
      }
      render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name: name2, from, to: to2 } = this;
        return `for(${varKind} ${name2}=${from}; ${name2}<${to2}; ${name2}++)` + super.render(opts);
      }
      get names() {
        const names2 = addExprNames(super.names, this.from);
        return addExprNames(names2, this.to);
      }
    }
    class ForIter extends For {
      constructor(loop, varKind, name2, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name2;
        this.iterable = iterable;
      }
      render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
      }
      optimizeNames(names2, constants) {
        if (!super.optimizeNames(names2, constants))
          return;
        this.iterable = optimizeExpr(this.iterable, names2, constants);
        return this;
      }
      get names() {
        return addNames(super.names, this.iterable.names);
      }
    }
    class Func extends BlockNode {
      constructor(name2, args, async2) {
        super();
        this.name = name2;
        this.args = args;
        this.async = async2;
      }
      render(opts) {
        const _async = this.async ? "async " : "";
        return `${_async}function ${this.name}(${this.args})` + super.render(opts);
      }
    }
    Func.kind = "func";
    class Return extends ParentNode {
      render(opts) {
        return "return " + super.render(opts);
      }
    }
    Return.kind = "return";
    class Try extends BlockNode {
      render(opts) {
        let code2 = "try" + super.render(opts);
        if (this.catch)
          code2 += this.catch.render(opts);
        if (this.finally)
          code2 += this.finally.render(opts);
        return code2;
      }
      optimizeNodes() {
        var _a2, _b;
        super.optimizeNodes();
        (_a2 = this.catch) === null || _a2 === void 0 ? void 0 : _a2.optimizeNodes();
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
        return this;
      }
      optimizeNames(names2, constants) {
        var _a2, _b;
        super.optimizeNames(names2, constants);
        (_a2 = this.catch) === null || _a2 === void 0 ? void 0 : _a2.optimizeNames(names2, constants);
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names2, constants);
        return this;
      }
      get names() {
        const names2 = super.names;
        if (this.catch)
          addNames(names2, this.catch.names);
        if (this.finally)
          addNames(names2, this.finally.names);
        return names2;
      }
    }
    class Catch extends BlockNode {
      constructor(error) {
        super();
        this.error = error;
      }
      render(opts) {
        return `catch(${this.error})` + super.render(opts);
      }
    }
    Catch.kind = "catch";
    class Finally extends BlockNode {
      render(opts) {
        return "finally" + super.render(opts);
      }
    }
    Finally.kind = "finally";
    class CodeGen {
      constructor(extScope, opts = {}) {
        this._values = {};
        this._blockStarts = [];
        this._constants = {};
        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
        this._extScope = extScope;
        this._scope = new scope_1.Scope({ parent: extScope });
        this._nodes = [new Root4()];
      }
      toString() {
        return this._root.render(this.opts);
      }
      // returns unique name in the internal scope
      name(prefix) {
        return this._scope.name(prefix);
      }
      // reserves unique name in the external scope
      scopeName(prefix) {
        return this._extScope.name(prefix);
      }
      // reserves unique name in the external scope and assigns value to it
      scopeValue(prefixOrName, value) {
        const name2 = this._extScope.value(prefixOrName, value);
        const vs2 = this._values[name2.prefix] || (this._values[name2.prefix] = /* @__PURE__ */ new Set());
        vs2.add(name2);
        return name2;
      }
      getScopeValue(prefix, keyOrRef) {
        return this._extScope.getValue(prefix, keyOrRef);
      }
      // return code that assigns values in the external scope to the names that are used internally
      // (same names that were returned by gen.scopeName or gen.scopeValue)
      scopeRefs(scopeName) {
        return this._extScope.scopeRefs(scopeName, this._values);
      }
      scopeCode() {
        return this._extScope.scopeCode(this._values);
      }
      _def(varKind, nameOrPrefix, rhs, constant) {
        const name2 = this._scope.toName(nameOrPrefix);
        if (rhs !== void 0 && constant)
          this._constants[name2.str] = rhs;
        this._leafNode(new Def(varKind, name2, rhs));
        return name2;
      }
      // `const` declaration (`var` in es5 mode)
      const(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
      }
      // `let` declaration with optional assignment (`var` in es5 mode)
      let(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
      }
      // `var` declaration with optional assignment
      var(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
      }
      // assignment code
      assign(lhs, rhs, sideEffects) {
        return this._leafNode(new Assign(lhs, rhs, sideEffects));
      }
      // `+=` code
      add(lhs, rhs) {
        return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
      }
      // appends passed SafeExpr to code or executes Block
      code(c) {
        if (typeof c == "function")
          c();
        else if (c !== code_1.nil)
          this._leafNode(new AnyCode(c));
        return this;
      }
      // returns code for object literal for the passed argument list of key-value pairs
      object(...keyValues) {
        const code2 = ["{"];
        for (const [key, value] of keyValues) {
          if (code2.length > 1)
            code2.push(",");
          code2.push(key);
          if (key !== value || this.opts.es5) {
            code2.push(":");
            (0, code_1.addCodeArg)(code2, value);
          }
        }
        code2.push("}");
        return new code_1._Code(code2);
      }
      // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
      if(condition, thenBody, elseBody) {
        this._blockNode(new If2(condition));
        if (thenBody && elseBody) {
          this.code(thenBody).else().code(elseBody).endIf();
        } else if (thenBody) {
          this.code(thenBody).endIf();
        } else if (elseBody) {
          throw new Error('CodeGen: "else" body without "then" body');
        }
        return this;
      }
      // `else if` clause - invalid without `if` or after `else` clauses
      elseIf(condition) {
        return this._elseNode(new If2(condition));
      }
      // `else` clause - only valid after `if` or `else if` clauses
      else() {
        return this._elseNode(new Else());
      }
      // end `if` statement (needed if gen.if was used only with condition)
      endIf() {
        return this._endBlockNode(If2, Else);
      }
      _for(node, forBody) {
        this._blockNode(node);
        if (forBody)
          this.code(forBody).endFor();
        return this;
      }
      // a generic `for` clause (or statement if `forBody` is passed)
      for(iteration, forBody) {
        return this._for(new ForLoop(iteration), forBody);
      }
      // `for` statement for a range of values
      forRange(nameOrPrefix, from, to2, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
        const name2 = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name2, from, to2), () => forBody(name2));
      }
      // `for-of` statement (in es5 mode replace with a normal for loop)
      forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name2 = this._scope.toName(nameOrPrefix);
        if (this.opts.es5) {
          const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
          return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i2) => {
            this.var(name2, (0, code_1._)`${arr}[${i2}]`);
            forBody(name2);
          });
        }
        return this._for(new ForIter("of", varKind, name2, iterable), () => forBody(name2));
      }
      // `for-in` statement.
      // With option `ownProperties` replaced with a `for-of` loop for object keys
      forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
        if (this.opts.ownProperties) {
          return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody);
        }
        const name2 = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name2, obj), () => forBody(name2));
      }
      // end `for` loop
      endFor() {
        return this._endBlockNode(For);
      }
      // `label` statement
      label(label) {
        return this._leafNode(new Label2(label));
      }
      // `break` statement
      break(label) {
        return this._leafNode(new Break(label));
      }
      // `return` statement
      return(value) {
        const node = new Return();
        this._blockNode(node);
        this.code(value);
        if (node.nodes.length !== 1)
          throw new Error('CodeGen: "return" should have one node');
        return this._endBlockNode(Return);
      }
      // `try` statement
      try(tryBody, catchCode, finallyCode) {
        if (!catchCode && !finallyCode)
          throw new Error('CodeGen: "try" without "catch" and "finally"');
        const node = new Try();
        this._blockNode(node);
        this.code(tryBody);
        if (catchCode) {
          const error = this.name("e");
          this._currNode = node.catch = new Catch(error);
          catchCode(error);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error) {
        return this._leafNode(new Throw(error));
      }
      // start self-balancing block
      block(body, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body)
          this.code(body).endBlock(nodeCount);
        return this;
      }
      // end the current self-balancing block
      endBlock(nodeCount) {
        const len = this._blockStarts.pop();
        if (len === void 0)
          throw new Error("CodeGen: not in self-balancing block");
        const toClose = this._nodes.length - len;
        if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) {
          throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
        }
        this._nodes.length = len;
        return this;
      }
      // `function` heading (or definition if funcBody is passed)
      func(name2, args = code_1.nil, async2, funcBody) {
        this._blockNode(new Func(name2, args, async2));
        if (funcBody)
          this.code(funcBody).endFunc();
        return this;
      }
      // end function definition
      endFunc() {
        return this._endBlockNode(Func);
      }
      optimize(n = 1) {
        while (n-- > 0) {
          this._root.optimizeNodes();
          this._root.optimizeNames(this._root.names, this._constants);
        }
      }
      _leafNode(node) {
        this._currNode.nodes.push(node);
        return this;
      }
      _blockNode(node) {
        this._currNode.nodes.push(node);
        this._nodes.push(node);
      }
      _endBlockNode(N1, N2) {
        const n = this._currNode;
        if (n instanceof N1 || N2 && n instanceof N2) {
          this._nodes.pop();
          return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
      }
      _elseNode(node) {
        const n = this._currNode;
        if (!(n instanceof If2)) {
          throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n.else = node;
        return this;
      }
      get _root() {
        return this._nodes[0];
      }
      get _currNode() {
        const ns2 = this._nodes;
        return ns2[ns2.length - 1];
      }
      set _currNode(node) {
        const ns2 = this._nodes;
        ns2[ns2.length - 1] = node;
      }
    }
    exports.CodeGen = CodeGen;
    function addNames(names2, from) {
      for (const n in from)
        names2[n] = (names2[n] || 0) + (from[n] || 0);
      return names2;
    }
    function addExprNames(names2, from) {
      return from instanceof code_1._CodeOrName ? addNames(names2, from.names) : names2;
    }
    function optimizeExpr(expr, names2, constants) {
      if (expr instanceof code_1.Name)
        return replaceName(expr);
      if (!canOptimize(expr))
        return expr;
      return new code_1._Code(expr._items.reduce((items2, c) => {
        if (c instanceof code_1.Name)
          c = replaceName(c);
        if (c instanceof code_1._Code)
          items2.push(...c._items);
        else
          items2.push(c);
        return items2;
      }, []));
      function replaceName(n) {
        const c = constants[n.str];
        if (c === void 0 || names2[n.str] !== 1)
          return n;
        delete names2[n.str];
        return c;
      }
      function canOptimize(e2) {
        return e2 instanceof code_1._Code && e2._items.some((c) => c instanceof code_1.Name && names2[c.str] === 1 && constants[c.str] !== void 0);
      }
    }
    function subtractNames(names2, from) {
      for (const n in from)
        names2[n] = (names2[n] || 0) - (from[n] || 0);
    }
    function not2(x2) {
      return typeof x2 == "boolean" || typeof x2 == "number" || x2 === null ? !x2 : (0, code_1._)`!${par(x2)}`;
    }
    exports.not = not2;
    const andCode = mappend(exports.operators.AND);
    function and(...args) {
      return args.reduce(andCode);
    }
    exports.and = and;
    const orCode = mappend(exports.operators.OR);
    function or2(...args) {
      return args.reduce(orCode);
    }
    exports.or = or2;
    function mappend(op2) {
      return (x2, y) => x2 === code_1.nil ? y : y === code_1.nil ? x2 : (0, code_1._)`${par(x2)} ${op2} ${par(y)}`;
    }
    function par(x2) {
      return x2 instanceof code_1.Name ? x2 : (0, code_1._)`(${x2})`;
    }
  })(codegen);
  return codegen;
}
var util = {};
var hasRequiredUtil;
function requireUtil() {
  if (hasRequiredUtil) return util;
  hasRequiredUtil = 1;
  Object.defineProperty(util, "__esModule", { value: true });
  util.checkStrictMode = util.getErrorPath = util.Type = util.useFunc = util.setEvaluated = util.evaluatedPropsToName = util.mergeEvaluated = util.eachItem = util.unescapeJsonPointer = util.escapeJsonPointer = util.escapeFragment = util.unescapeFragment = util.schemaRefOrVal = util.schemaHasRulesButRef = util.schemaHasRules = util.checkUnknownRules = util.alwaysValidSchema = util.toHash = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const code_1 = /* @__PURE__ */ requireCode$1();
  function toHash(arr) {
    const hash = {};
    for (const item of arr)
      hash[item] = true;
    return hash;
  }
  util.toHash = toHash;
  function alwaysValidSchema(it2, schema) {
    if (typeof schema == "boolean")
      return schema;
    if (Object.keys(schema).length === 0)
      return true;
    checkUnknownRules(it2, schema);
    return !schemaHasRules(schema, it2.self.RULES.all);
  }
  util.alwaysValidSchema = alwaysValidSchema;
  function checkUnknownRules(it2, schema = it2.schema) {
    const { opts, self: self2 } = it2;
    if (!opts.strictSchema)
      return;
    if (typeof schema === "boolean")
      return;
    const rules2 = self2.RULES.keywords;
    for (const key in schema) {
      if (!rules2[key])
        checkStrictMode(it2, `unknown keyword: "${key}"`);
    }
  }
  util.checkUnknownRules = checkUnknownRules;
  function schemaHasRules(schema, rules2) {
    if (typeof schema == "boolean")
      return !schema;
    for (const key in schema)
      if (rules2[key])
        return true;
    return false;
  }
  util.schemaHasRules = schemaHasRules;
  function schemaHasRulesButRef(schema, RULES) {
    if (typeof schema == "boolean")
      return !schema;
    for (const key in schema)
      if (key !== "$ref" && RULES.all[key])
        return true;
    return false;
  }
  util.schemaHasRulesButRef = schemaHasRulesButRef;
  function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword2, $data) {
    if (!$data) {
      if (typeof schema == "number" || typeof schema == "boolean")
        return schema;
      if (typeof schema == "string")
        return (0, codegen_1._)`${schema}`;
    }
    return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword2)}`;
  }
  util.schemaRefOrVal = schemaRefOrVal;
  function unescapeFragment(str) {
    return unescapeJsonPointer(decodeURIComponent(str));
  }
  util.unescapeFragment = unescapeFragment;
  function escapeFragment(str) {
    return encodeURIComponent(escapeJsonPointer(str));
  }
  util.escapeFragment = escapeFragment;
  function escapeJsonPointer(str) {
    if (typeof str == "number")
      return `${str}`;
    return str.replace(/~/g, "~0").replace(/\//g, "~1");
  }
  util.escapeJsonPointer = escapeJsonPointer;
  function unescapeJsonPointer(str) {
    return str.replace(/~1/g, "/").replace(/~0/g, "~");
  }
  util.unescapeJsonPointer = unescapeJsonPointer;
  function eachItem(xs2, f2) {
    if (Array.isArray(xs2)) {
      for (const x2 of xs2)
        f2(x2);
    } else {
      f2(xs2);
    }
  }
  util.eachItem = eachItem;
  function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues2, resultToName }) {
    return (gen, from, to2, toName) => {
      const res = to2 === void 0 ? from : to2 instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to2) : mergeToName(gen, from, to2), to2) : from instanceof codegen_1.Name ? (mergeToName(gen, to2, from), from) : mergeValues2(from, to2);
      return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
    };
  }
  util.mergeEvaluated = {
    props: makeMergeEvaluated({
      mergeNames: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true && ${from} !== undefined`, () => {
        gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to2, true), () => gen.assign(to2, (0, codegen_1._)`${to2} || {}`).code((0, codegen_1._)`Object.assign(${to2}, ${from})`));
      }),
      mergeToName: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true`, () => {
        if (from === true) {
          gen.assign(to2, true);
        } else {
          gen.assign(to2, (0, codegen_1._)`${to2} || {}`);
          setEvaluated(gen, to2, from);
        }
      }),
      mergeValues: (from, to2) => from === true ? true : { ...from, ...to2 },
      resultToName: evaluatedPropsToName
    }),
    items: makeMergeEvaluated({
      mergeNames: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true && ${from} !== undefined`, () => gen.assign(to2, (0, codegen_1._)`${from} === true ? true : ${to2} > ${from} ? ${to2} : ${from}`)),
      mergeToName: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true`, () => gen.assign(to2, from === true ? true : (0, codegen_1._)`${to2} > ${from} ? ${to2} : ${from}`)),
      mergeValues: (from, to2) => from === true ? true : Math.max(from, to2),
      resultToName: (gen, items2) => gen.var("items", items2)
    })
  };
  function evaluatedPropsToName(gen, ps2) {
    if (ps2 === true)
      return gen.var("props", true);
    const props = gen.var("props", (0, codegen_1._)`{}`);
    if (ps2 !== void 0)
      setEvaluated(gen, props, ps2);
    return props;
  }
  util.evaluatedPropsToName = evaluatedPropsToName;
  function setEvaluated(gen, props, ps2) {
    Object.keys(ps2).forEach((p2) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p2)}`, true));
  }
  util.setEvaluated = setEvaluated;
  const snippets = {};
  function useFunc(gen, f2) {
    return gen.scopeValue("func", {
      ref: f2,
      code: snippets[f2.code] || (snippets[f2.code] = new code_1._Code(f2.code))
    });
  }
  util.useFunc = useFunc;
  var Type;
  (function(Type2) {
    Type2[Type2["Num"] = 0] = "Num";
    Type2[Type2["Str"] = 1] = "Str";
  })(Type || (util.Type = Type = {}));
  function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
    if (dataProp instanceof codegen_1.Name) {
      const isNumber2 = dataPropType === Type.Num;
      return jsPropertySyntax ? isNumber2 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber2 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
    }
    return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
  }
  util.getErrorPath = getErrorPath;
  function checkStrictMode(it2, msg, mode = it2.opts.strictSchema) {
    if (!mode)
      return;
    msg = `strict mode: ${msg}`;
    if (mode === true)
      throw new Error(msg);
    it2.self.logger.warn(msg);
  }
  util.checkStrictMode = checkStrictMode;
  return util;
}
var names = {};
var hasRequiredNames;
function requireNames() {
  if (hasRequiredNames) return names;
  hasRequiredNames = 1;
  Object.defineProperty(names, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const names$12 = {
    // validation function arguments
    data: new codegen_1.Name("data"),
    // data passed to validation function
    // args passed from referencing schema
    valCxt: new codegen_1.Name("valCxt"),
    // validation/data context - should not be used directly, it is destructured to the names below
    instancePath: new codegen_1.Name("instancePath"),
    parentData: new codegen_1.Name("parentData"),
    parentDataProperty: new codegen_1.Name("parentDataProperty"),
    rootData: new codegen_1.Name("rootData"),
    // root data - same as the data passed to the first/top validation function
    dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
    // used to support recursiveRef and dynamicRef
    // function scoped variables
    vErrors: new codegen_1.Name("vErrors"),
    // null or array of validation errors
    errors: new codegen_1.Name("errors"),
    // counter of validation errors
    this: new codegen_1.Name("this"),
    // "globals"
    self: new codegen_1.Name("self"),
    scope: new codegen_1.Name("scope"),
    // JTD serialize/parse name for JSON string and position
    json: new codegen_1.Name("json"),
    jsonPos: new codegen_1.Name("jsonPos"),
    jsonLen: new codegen_1.Name("jsonLen"),
    jsonPart: new codegen_1.Name("jsonPart")
  };
  names.default = names$12;
  return names;
}
var hasRequiredErrors;
function requireErrors() {
  if (hasRequiredErrors) return errors;
  hasRequiredErrors = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
    const codegen_1 = /* @__PURE__ */ requireCodegen();
    const util_1 = /* @__PURE__ */ requireUtil();
    const names_1 = /* @__PURE__ */ requireNames();
    exports.keywordError = {
      message: ({ keyword: keyword2 }) => (0, codegen_1.str)`must pass "${keyword2}" keyword validation`
    };
    exports.keyword$DataError = {
      message: ({ keyword: keyword2, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword2}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword2}" keyword is invalid ($data)`
    };
    function reportError2(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
      const { it: it2 } = cxt;
      const { gen, compositeRule, allErrors } = it2;
      const errObj = errorObjectCode(cxt, error, errorPaths);
      if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
        addError(gen, errObj);
      } else {
        returnErrors(it2, (0, codegen_1._)`[${errObj}]`);
      }
    }
    exports.reportError = reportError2;
    function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
      const { it: it2 } = cxt;
      const { gen, compositeRule, allErrors } = it2;
      const errObj = errorObjectCode(cxt, error, errorPaths);
      addError(gen, errObj);
      if (!(compositeRule || allErrors)) {
        returnErrors(it2, names_1.default.vErrors);
      }
    }
    exports.reportExtraError = reportExtraError;
    function resetErrorsCount(gen, errsCount) {
      gen.assign(names_1.default.errors, errsCount);
      gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
    }
    exports.resetErrorsCount = resetErrorsCount;
    function extendErrors({ gen, keyword: keyword2, schemaValue, data: data2, errsCount, it: it2 }) {
      if (errsCount === void 0)
        throw new Error("ajv implementation error");
      const err = gen.name("err");
      gen.forRange("i", errsCount, names_1.default.errors, (i2) => {
        gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i2}]`);
        gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it2.errorPath)));
        gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it2.errSchemaPath}/${keyword2}`);
        if (it2.opts.verbose) {
          gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);
          gen.assign((0, codegen_1._)`${err}.data`, data2);
        }
      });
    }
    exports.extendErrors = extendErrors;
    function addError(gen, errObj) {
      const err = gen.const("err", errObj);
      gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`);
      gen.code((0, codegen_1._)`${names_1.default.errors}++`);
    }
    function returnErrors(it2, errs) {
      const { gen, validateName, schemaEnv } = it2;
      if (schemaEnv.$async) {
        gen.throw((0, codegen_1._)`new ${it2.ValidationError}(${errs})`);
      } else {
        gen.assign((0, codegen_1._)`${validateName}.errors`, errs);
        gen.return(false);
      }
    }
    const E2 = {
      keyword: new codegen_1.Name("keyword"),
      schemaPath: new codegen_1.Name("schemaPath"),
      // also used in JTD errors
      params: new codegen_1.Name("params"),
      propertyName: new codegen_1.Name("propertyName"),
      message: new codegen_1.Name("message"),
      schema: new codegen_1.Name("schema"),
      parentSchema: new codegen_1.Name("parentSchema")
    };
    function errorObjectCode(cxt, error, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error, errorPaths);
    }
    function errorObject(cxt, error, errorPaths = {}) {
      const { gen, it: it2 } = cxt;
      const keyValues = [
        errorInstancePath(it2, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error, keyValues);
      return gen.object(...keyValues);
    }
    function errorInstancePath({ errorPath }, { instancePath }) {
      const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath;
      return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
    }
    function errorSchemaPath({ keyword: keyword2, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
      let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword2}`;
      if (schemaPath) {
        schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
      }
      return [E2.schemaPath, schPath];
    }
    function extraErrorProps(cxt, { params, message }, keyValues) {
      const { keyword: keyword2, data: data2, schemaValue, it: it2 } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it2;
      keyValues.push([E2.keyword, keyword2], [E2.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
      if (opts.messages) {
        keyValues.push([E2.message, typeof message == "function" ? message(cxt) : message]);
      }
      if (opts.verbose) {
        keyValues.push([E2.schema, schemaValue], [E2.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data2]);
      }
      if (propertyName)
        keyValues.push([E2.propertyName, propertyName]);
    }
  })(errors);
  return errors;
}
var hasRequiredBoolSchema;
function requireBoolSchema() {
  if (hasRequiredBoolSchema) return boolSchema;
  hasRequiredBoolSchema = 1;
  Object.defineProperty(boolSchema, "__esModule", { value: true });
  boolSchema.boolOrEmptySchema = boolSchema.topBoolOrEmptySchema = void 0;
  const errors_1 = /* @__PURE__ */ requireErrors();
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const names_1 = /* @__PURE__ */ requireNames();
  const boolError = {
    message: "boolean schema is false"
  };
  function topBoolOrEmptySchema(it2) {
    const { gen, schema, validateName } = it2;
    if (schema === false) {
      falseSchemaError(it2, false);
    } else if (typeof schema == "object" && schema.$async === true) {
      gen.return(names_1.default.data);
    } else {
      gen.assign((0, codegen_1._)`${validateName}.errors`, null);
      gen.return(true);
    }
  }
  boolSchema.topBoolOrEmptySchema = topBoolOrEmptySchema;
  function boolOrEmptySchema(it2, valid) {
    const { gen, schema } = it2;
    if (schema === false) {
      gen.var(valid, false);
      falseSchemaError(it2);
    } else {
      gen.var(valid, true);
    }
  }
  boolSchema.boolOrEmptySchema = boolOrEmptySchema;
  function falseSchemaError(it2, overrideAllErrors) {
    const { gen, data: data2 } = it2;
    const cxt = {
      gen,
      keyword: "false schema",
      data: data2,
      schema: false,
      schemaCode: false,
      schemaValue: false,
      params: {},
      it: it2
    };
    (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
  }
  return boolSchema;
}
var dataType = {};
var rules = {};
var hasRequiredRules;
function requireRules() {
  if (hasRequiredRules) return rules;
  hasRequiredRules = 1;
  Object.defineProperty(rules, "__esModule", { value: true });
  rules.getRules = rules.isJSONType = void 0;
  const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
  const jsonTypes = new Set(_jsonTypes);
  function isJSONType(x2) {
    return typeof x2 == "string" && jsonTypes.has(x2);
  }
  rules.isJSONType = isJSONType;
  function getRules() {
    const groups = {
      number: { type: "number", rules: [] },
      string: { type: "string", rules: [] },
      array: { type: "array", rules: [] },
      object: { type: "object", rules: [] }
    };
    return {
      types: { ...groups, integer: true, boolean: true, null: true },
      rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
      post: { rules: [] },
      all: {},
      keywords: {}
    };
  }
  rules.getRules = getRules;
  return rules;
}
var applicability = {};
var hasRequiredApplicability;
function requireApplicability() {
  if (hasRequiredApplicability) return applicability;
  hasRequiredApplicability = 1;
  Object.defineProperty(applicability, "__esModule", { value: true });
  applicability.shouldUseRule = applicability.shouldUseGroup = applicability.schemaHasRulesForType = void 0;
  function schemaHasRulesForType({ schema, self: self2 }, type2) {
    const group = self2.RULES.types[type2];
    return group && group !== true && shouldUseGroup(schema, group);
  }
  applicability.schemaHasRulesForType = schemaHasRulesForType;
  function shouldUseGroup(schema, group) {
    return group.rules.some((rule) => shouldUseRule(schema, rule));
  }
  applicability.shouldUseGroup = shouldUseGroup;
  function shouldUseRule(schema, rule) {
    var _a2;
    return schema[rule.keyword] !== void 0 || ((_a2 = rule.definition.implements) === null || _a2 === void 0 ? void 0 : _a2.some((kwd) => schema[kwd] !== void 0));
  }
  applicability.shouldUseRule = shouldUseRule;
  return applicability;
}
var hasRequiredDataType;
function requireDataType() {
  if (hasRequiredDataType) return dataType;
  hasRequiredDataType = 1;
  Object.defineProperty(dataType, "__esModule", { value: true });
  dataType.reportTypeError = dataType.checkDataTypes = dataType.checkDataType = dataType.coerceAndCheckDataType = dataType.getJSONTypes = dataType.getSchemaTypes = dataType.DataType = void 0;
  const rules_1 = /* @__PURE__ */ requireRules();
  const applicability_1 = /* @__PURE__ */ requireApplicability();
  const errors_1 = /* @__PURE__ */ requireErrors();
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  var DataType;
  (function(DataType2) {
    DataType2[DataType2["Correct"] = 0] = "Correct";
    DataType2[DataType2["Wrong"] = 1] = "Wrong";
  })(DataType || (dataType.DataType = DataType = {}));
  function getSchemaTypes(schema) {
    const types2 = getJSONTypes(schema.type);
    const hasNull = types2.includes("null");
    if (hasNull) {
      if (schema.nullable === false)
        throw new Error("type: null contradicts nullable: false");
    } else {
      if (!types2.length && schema.nullable !== void 0) {
        throw new Error('"nullable" cannot be used without "type"');
      }
      if (schema.nullable === true)
        types2.push("null");
    }
    return types2;
  }
  dataType.getSchemaTypes = getSchemaTypes;
  function getJSONTypes(ts2) {
    const types2 = Array.isArray(ts2) ? ts2 : ts2 ? [ts2] : [];
    if (types2.every(rules_1.isJSONType))
      return types2;
    throw new Error("type must be JSONType or JSONType[]: " + types2.join(","));
  }
  dataType.getJSONTypes = getJSONTypes;
  function coerceAndCheckDataType(it2, types2) {
    const { gen, data: data2, opts } = it2;
    const coerceTo = coerceToTypes(types2, opts.coerceTypes);
    const checkTypes = types2.length > 0 && !(coerceTo.length === 0 && types2.length === 1 && (0, applicability_1.schemaHasRulesForType)(it2, types2[0]));
    if (checkTypes) {
      const wrongType = checkDataTypes(types2, data2, opts.strictNumbers, DataType.Wrong);
      gen.if(wrongType, () => {
        if (coerceTo.length)
          coerceData(it2, types2, coerceTo);
        else
          reportTypeError(it2);
      });
    }
    return checkTypes;
  }
  dataType.coerceAndCheckDataType = coerceAndCheckDataType;
  const COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
  function coerceToTypes(types2, coerceTypes) {
    return coerceTypes ? types2.filter((t2) => COERCIBLE.has(t2) || coerceTypes === "array" && t2 === "array") : [];
  }
  function coerceData(it2, types2, coerceTo) {
    const { gen, data: data2, opts } = it2;
    const dataType2 = gen.let("dataType", (0, codegen_1._)`typeof ${data2}`);
    const coerced = gen.let("coerced", (0, codegen_1._)`undefined`);
    if (opts.coerceTypes === "array") {
      gen.if((0, codegen_1._)`${dataType2} == 'object' && Array.isArray(${data2}) && ${data2}.length == 1`, () => gen.assign(data2, (0, codegen_1._)`${data2}[0]`).assign(dataType2, (0, codegen_1._)`typeof ${data2}`).if(checkDataTypes(types2, data2, opts.strictNumbers), () => gen.assign(coerced, data2)));
    }
    gen.if((0, codegen_1._)`${coerced} !== undefined`);
    for (const t2 of coerceTo) {
      if (COERCIBLE.has(t2) || t2 === "array" && opts.coerceTypes === "array") {
        coerceSpecificType(t2);
      }
    }
    gen.else();
    reportTypeError(it2);
    gen.endIf();
    gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
      gen.assign(data2, coerced);
      assignParentData(it2, coerced);
    });
    function coerceSpecificType(t2) {
      switch (t2) {
        case "string":
          gen.elseIf((0, codegen_1._)`${dataType2} == "number" || ${dataType2} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data2}`).elseIf((0, codegen_1._)`${data2} === null`).assign(coerced, (0, codegen_1._)`""`);
          return;
        case "number":
          gen.elseIf((0, codegen_1._)`${dataType2} == "boolean" || ${data2} === null
              || (${dataType2} == "string" && ${data2} && ${data2} == +${data2})`).assign(coerced, (0, codegen_1._)`+${data2}`);
          return;
        case "integer":
          gen.elseIf((0, codegen_1._)`${dataType2} === "boolean" || ${data2} === null
              || (${dataType2} === "string" && ${data2} && ${data2} == +${data2} && !(${data2} % 1))`).assign(coerced, (0, codegen_1._)`+${data2}`);
          return;
        case "boolean":
          gen.elseIf((0, codegen_1._)`${data2} === "false" || ${data2} === 0 || ${data2} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data2} === "true" || ${data2} === 1`).assign(coerced, true);
          return;
        case "null":
          gen.elseIf((0, codegen_1._)`${data2} === "" || ${data2} === 0 || ${data2} === false`);
          gen.assign(coerced, null);
          return;
        case "array":
          gen.elseIf((0, codegen_1._)`${dataType2} === "string" || ${dataType2} === "number"
              || ${dataType2} === "boolean" || ${data2} === null`).assign(coerced, (0, codegen_1._)`[${data2}]`);
      }
    }
  }
  function assignParentData({ gen, parentData, parentDataProperty }, expr) {
    gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));
  }
  function checkDataType(dataType2, data2, strictNums, correct = DataType.Correct) {
    const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
    let cond;
    switch (dataType2) {
      case "null":
        return (0, codegen_1._)`${data2} ${EQ} null`;
      case "array":
        cond = (0, codegen_1._)`Array.isArray(${data2})`;
        break;
      case "object":
        cond = (0, codegen_1._)`${data2} && typeof ${data2} == "object" && !Array.isArray(${data2})`;
        break;
      case "integer":
        cond = numCond((0, codegen_1._)`!(${data2} % 1) && !isNaN(${data2})`);
        break;
      case "number":
        cond = numCond();
        break;
      default:
        return (0, codegen_1._)`typeof ${data2} ${EQ} ${dataType2}`;
    }
    return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
    function numCond(_cond = codegen_1.nil) {
      return (0, codegen_1.and)((0, codegen_1._)`typeof ${data2} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data2})` : codegen_1.nil);
    }
  }
  dataType.checkDataType = checkDataType;
  function checkDataTypes(dataTypes, data2, strictNums, correct) {
    if (dataTypes.length === 1) {
      return checkDataType(dataTypes[0], data2, strictNums, correct);
    }
    let cond;
    const types2 = (0, util_1.toHash)(dataTypes);
    if (types2.array && types2.object) {
      const notObj = (0, codegen_1._)`typeof ${data2} != "object"`;
      cond = types2.null ? notObj : (0, codegen_1._)`!${data2} || ${notObj}`;
      delete types2.null;
      delete types2.array;
      delete types2.object;
    } else {
      cond = codegen_1.nil;
    }
    if (types2.number)
      delete types2.integer;
    for (const t2 in types2)
      cond = (0, codegen_1.and)(cond, checkDataType(t2, data2, strictNums, correct));
    return cond;
  }
  dataType.checkDataTypes = checkDataTypes;
  const typeError = {
    message: ({ schema }) => `must be ${schema}`,
    params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`
  };
  function reportTypeError(it2) {
    const cxt = getTypeErrorContext(it2);
    (0, errors_1.reportError)(cxt, typeError);
  }
  dataType.reportTypeError = reportTypeError;
  function getTypeErrorContext(it2) {
    const { gen, data: data2, schema } = it2;
    const schemaCode = (0, util_1.schemaRefOrVal)(it2, schema, "type");
    return {
      gen,
      keyword: "type",
      data: data2,
      schema: schema.type,
      schemaCode,
      schemaValue: schemaCode,
      parentSchema: schema,
      params: {},
      it: it2
    };
  }
  return dataType;
}
var defaults = {};
var hasRequiredDefaults;
function requireDefaults() {
  if (hasRequiredDefaults) return defaults;
  hasRequiredDefaults = 1;
  Object.defineProperty(defaults, "__esModule", { value: true });
  defaults.assignDefaults = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  function assignDefaults(it2, ty) {
    const { properties: properties2, items: items2 } = it2.schema;
    if (ty === "object" && properties2) {
      for (const key in properties2) {
        assignDefault(it2, key, properties2[key].default);
      }
    } else if (ty === "array" && Array.isArray(items2)) {
      items2.forEach((sch, i2) => assignDefault(it2, i2, sch.default));
    }
  }
  defaults.assignDefaults = assignDefaults;
  function assignDefault(it2, prop, defaultValue) {
    const { gen, compositeRule, data: data2, opts } = it2;
    if (defaultValue === void 0)
      return;
    const childData = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(prop)}`;
    if (compositeRule) {
      (0, util_1.checkStrictMode)(it2, `default is ignored for: ${childData}`);
      return;
    }
    let condition = (0, codegen_1._)`${childData} === undefined`;
    if (opts.useDefaults === "empty") {
      condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
    }
    gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
  }
  return defaults;
}
var keyword = {};
var code = {};
var hasRequiredCode;
function requireCode() {
  if (hasRequiredCode) return code;
  hasRequiredCode = 1;
  Object.defineProperty(code, "__esModule", { value: true });
  code.validateUnion = code.validateArray = code.usePattern = code.callValidateCode = code.schemaProperties = code.allSchemaProperties = code.noPropertyInData = code.propertyInData = code.isOwnProperty = code.hasPropFunc = code.reportMissingProp = code.checkMissingProp = code.checkReportMissingProp = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const names_1 = /* @__PURE__ */ requireNames();
  const util_2 = /* @__PURE__ */ requireUtil();
  function checkReportMissingProp(cxt, prop) {
    const { gen, data: data2, it: it2 } = cxt;
    gen.if(noPropertyInData(gen, data2, prop, it2.opts.ownProperties), () => {
      cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
      cxt.error();
    });
  }
  code.checkReportMissingProp = checkReportMissingProp;
  function checkMissingProp({ gen, data: data2, it: { opts } }, properties2, missing) {
    return (0, codegen_1.or)(...properties2.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data2, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
  }
  code.checkMissingProp = checkMissingProp;
  function reportMissingProp(cxt, missing) {
    cxt.setParams({ missingProperty: missing }, true);
    cxt.error();
  }
  code.reportMissingProp = reportMissingProp;
  function hasPropFunc(gen) {
    return gen.scopeValue("func", {
      // eslint-disable-next-line @typescript-eslint/unbound-method
      ref: Object.prototype.hasOwnProperty,
      code: (0, codegen_1._)`Object.prototype.hasOwnProperty`
    });
  }
  code.hasPropFunc = hasPropFunc;
  function isOwnProperty(gen, data2, property) {
    return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data2}, ${property})`;
  }
  code.isOwnProperty = isOwnProperty;
  function propertyInData(gen, data2, property, ownProperties) {
    const cond = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(property)} !== undefined`;
    return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data2, property)}` : cond;
  }
  code.propertyInData = propertyInData;
  function noPropertyInData(gen, data2, property, ownProperties) {
    const cond = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(property)} === undefined`;
    return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data2, property))) : cond;
  }
  code.noPropertyInData = noPropertyInData;
  function allSchemaProperties(schemaMap) {
    return schemaMap ? Object.keys(schemaMap).filter((p2) => p2 !== "__proto__") : [];
  }
  code.allSchemaProperties = allSchemaProperties;
  function schemaProperties(it2, schemaMap) {
    return allSchemaProperties(schemaMap).filter((p2) => !(0, util_1.alwaysValidSchema)(it2, schemaMap[p2]));
  }
  code.schemaProperties = schemaProperties;
  function callValidateCode({ schemaCode, data: data2, it: { gen, topSchemaRef, schemaPath, errorPath }, it: it2 }, func, context, passSchema) {
    const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data2}, ${topSchemaRef}${schemaPath}` : data2;
    const valCxt = [
      [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
      [names_1.default.parentData, it2.parentData],
      [names_1.default.parentDataProperty, it2.parentDataProperty],
      [names_1.default.rootData, names_1.default.rootData]
    ];
    if (it2.opts.dynamicRef)
      valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
    const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
    return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;
  }
  code.callValidateCode = callValidateCode;
  const newRegExp = (0, codegen_1._)`new RegExp`;
  function usePattern({ gen, it: { opts } }, pattern2) {
    const u2 = opts.unicodeRegExp ? "u" : "";
    const { regExp } = opts.code;
    const rx = regExp(pattern2, u2);
    return gen.scopeValue("pattern", {
      key: rx.toString(),
      ref: rx,
      code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern2}, ${u2})`
    });
  }
  code.usePattern = usePattern;
  function validateArray(cxt) {
    const { gen, data: data2, keyword: keyword2, it: it2 } = cxt;
    const valid = gen.name("valid");
    if (it2.allErrors) {
      const validArr = gen.let("valid", true);
      validateItems(() => gen.assign(validArr, false));
      return validArr;
    }
    gen.var(valid, true);
    validateItems(() => gen.break());
    return valid;
    function validateItems(notValid) {
      const len = gen.const("len", (0, codegen_1._)`${data2}.length`);
      gen.forRange("i", 0, len, (i2) => {
        cxt.subschema({
          keyword: keyword2,
          dataProp: i2,
          dataPropType: util_1.Type.Num
        }, valid);
        gen.if((0, codegen_1.not)(valid), notValid);
      });
    }
  }
  code.validateArray = validateArray;
  function validateUnion(cxt) {
    const { gen, schema, keyword: keyword2, it: it2 } = cxt;
    if (!Array.isArray(schema))
      throw new Error("ajv implementation error");
    const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it2, sch));
    if (alwaysValid && !it2.opts.unevaluated)
      return;
    const valid = gen.let("valid", false);
    const schValid = gen.name("_valid");
    gen.block(() => schema.forEach((_sch, i2) => {
      const schCxt = cxt.subschema({
        keyword: keyword2,
        schemaProp: i2,
        compositeRule: true
      }, schValid);
      gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`);
      const merged = cxt.mergeValidEvaluated(schCxt, schValid);
      if (!merged)
        gen.if((0, codegen_1.not)(valid));
    }));
    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
  }
  code.validateUnion = validateUnion;
  return code;
}
var hasRequiredKeyword;
function requireKeyword() {
  if (hasRequiredKeyword) return keyword;
  hasRequiredKeyword = 1;
  Object.defineProperty(keyword, "__esModule", { value: true });
  keyword.validateKeywordUsage = keyword.validSchemaType = keyword.funcKeywordCode = keyword.macroKeywordCode = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const names_1 = /* @__PURE__ */ requireNames();
  const code_1 = /* @__PURE__ */ requireCode();
  const errors_1 = /* @__PURE__ */ requireErrors();
  function macroKeywordCode(cxt, def) {
    const { gen, keyword: keyword2, schema, parentSchema, it: it2 } = cxt;
    const macroSchema = def.macro.call(it2.self, schema, parentSchema, it2);
    const schemaRef = useKeyword(gen, keyword2, macroSchema);
    if (it2.opts.validateSchema !== false)
      it2.self.validateSchema(macroSchema, true);
    const valid = gen.name("valid");
    cxt.subschema({
      schema: macroSchema,
      schemaPath: codegen_1.nil,
      errSchemaPath: `${it2.errSchemaPath}/${keyword2}`,
      topSchemaRef: schemaRef,
      compositeRule: true
    }, valid);
    cxt.pass(valid, () => cxt.error(true));
  }
  keyword.macroKeywordCode = macroKeywordCode;
  function funcKeywordCode(cxt, def) {
    var _a2;
    const { gen, keyword: keyword2, schema, parentSchema, $data, it: it2 } = cxt;
    checkAsyncKeyword(it2, def);
    const validate2 = !$data && def.compile ? def.compile.call(it2.self, schema, parentSchema, it2) : def.validate;
    const validateRef = useKeyword(gen, keyword2, validate2);
    const valid = gen.let("valid");
    cxt.block$data(valid, validateKeyword);
    cxt.ok((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid);
    function validateKeyword() {
      if (def.errors === false) {
        assignValid();
        if (def.modifying)
          modifyData(cxt);
        reportErrs(() => cxt.error());
      } else {
        const ruleErrs = def.async ? validateAsync() : validateSync();
        if (def.modifying)
          modifyData(cxt);
        reportErrs(() => addErrs(cxt, ruleErrs));
      }
    }
    function validateAsync() {
      const ruleErrs = gen.let("ruleErrs", null);
      gen.try(() => assignValid((0, codegen_1._)`await `), (e2) => gen.assign(valid, false).if((0, codegen_1._)`${e2} instanceof ${it2.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e2}.errors`), () => gen.throw(e2)));
      return ruleErrs;
    }
    function validateSync() {
      const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
      gen.assign(validateErrs, null);
      assignValid(codegen_1.nil);
      return validateErrs;
    }
    function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) {
      const passCxt = it2.opts.passContext ? names_1.default.this : names_1.default.self;
      const passSchema = !("compile" in def && !$data || def.schema === false);
      gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
    }
    function reportErrs(errors2) {
      var _a3;
      gen.if((0, codegen_1.not)((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid), errors2);
    }
  }
  keyword.funcKeywordCode = funcKeywordCode;
  function modifyData(cxt) {
    const { gen, data: data2, it: it2 } = cxt;
    gen.if(it2.parentData, () => gen.assign(data2, (0, codegen_1._)`${it2.parentData}[${it2.parentDataProperty}]`));
  }
  function addErrs(cxt, errs) {
    const { gen } = cxt;
    gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => {
      gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
      (0, errors_1.extendErrors)(cxt);
    }, () => cxt.error());
  }
  function checkAsyncKeyword({ schemaEnv }, def) {
    if (def.async && !schemaEnv.$async)
      throw new Error("async keyword in sync schema");
  }
  function useKeyword(gen, keyword2, result) {
    if (result === void 0)
      throw new Error(`keyword "${keyword2}" failed to compile`);
    return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
  }
  function validSchemaType(schema, schemaType, allowUndefined = false) {
    return !schemaType.length || schemaType.some((st2) => st2 === "array" ? Array.isArray(schema) : st2 === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st2 || allowUndefined && typeof schema == "undefined");
  }
  keyword.validSchemaType = validSchemaType;
  function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword2) {
    if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword2) : def.keyword !== keyword2) {
      throw new Error("ajv implementation error");
    }
    const deps = def.dependencies;
    if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
      throw new Error(`parent schema must have dependencies of ${keyword2}: ${deps.join(",")}`);
    }
    if (def.validateSchema) {
      const valid = def.validateSchema(schema[keyword2]);
      if (!valid) {
        const msg = `keyword "${keyword2}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors);
        if (opts.validateSchema === "log")
          self2.logger.error(msg);
        else
          throw new Error(msg);
      }
    }
  }
  keyword.validateKeywordUsage = validateKeywordUsage;
  return keyword;
}
var subschema = {};
var hasRequiredSubschema;
function requireSubschema() {
  if (hasRequiredSubschema) return subschema;
  hasRequiredSubschema = 1;
  Object.defineProperty(subschema, "__esModule", { value: true });
  subschema.extendSubschemaMode = subschema.extendSubschemaData = subschema.getSubschema = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  function getSubschema(it2, { keyword: keyword2, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
    if (keyword2 !== void 0 && schema !== void 0) {
      throw new Error('both "keyword" and "schema" passed, only one allowed');
    }
    if (keyword2 !== void 0) {
      const sch = it2.schema[keyword2];
      return schemaProp === void 0 ? {
        schema: sch,
        schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword2)}`,
        errSchemaPath: `${it2.errSchemaPath}/${keyword2}`
      } : {
        schema: sch[schemaProp],
        schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword2)}${(0, codegen_1.getProperty)(schemaProp)}`,
        errSchemaPath: `${it2.errSchemaPath}/${keyword2}/${(0, util_1.escapeFragment)(schemaProp)}`
      };
    }
    if (schema !== void 0) {
      if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) {
        throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
      }
      return {
        schema,
        schemaPath,
        topSchemaRef,
        errSchemaPath
      };
    }
    throw new Error('either "keyword" or "schema" must be passed');
  }
  subschema.getSubschema = getSubschema;
  function extendSubschemaData(subschema2, it2, { dataProp, dataPropType: dpType, data: data2, dataTypes, propertyName }) {
    if (data2 !== void 0 && dataProp !== void 0) {
      throw new Error('both "data" and "dataProp" passed, only one allowed');
    }
    const { gen } = it2;
    if (dataProp !== void 0) {
      const { errorPath, dataPathArr, opts } = it2;
      const nextData = gen.let("data", (0, codegen_1._)`${it2.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
      dataContextProps(nextData);
      subschema2.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
      subschema2.parentDataProperty = (0, codegen_1._)`${dataProp}`;
      subschema2.dataPathArr = [...dataPathArr, subschema2.parentDataProperty];
    }
    if (data2 !== void 0) {
      const nextData = data2 instanceof codegen_1.Name ? data2 : gen.let("data", data2, true);
      dataContextProps(nextData);
      if (propertyName !== void 0)
        subschema2.propertyName = propertyName;
    }
    if (dataTypes)
      subschema2.dataTypes = dataTypes;
    function dataContextProps(_nextData) {
      subschema2.data = _nextData;
      subschema2.dataLevel = it2.dataLevel + 1;
      subschema2.dataTypes = [];
      it2.definedProperties = /* @__PURE__ */ new Set();
      subschema2.parentData = it2.data;
      subschema2.dataNames = [...it2.dataNames, _nextData];
    }
  }
  subschema.extendSubschemaData = extendSubschemaData;
  function extendSubschemaMode(subschema2, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
    if (compositeRule !== void 0)
      subschema2.compositeRule = compositeRule;
    if (createErrors !== void 0)
      subschema2.createErrors = createErrors;
    if (allErrors !== void 0)
      subschema2.allErrors = allErrors;
    subschema2.jtdDiscriminator = jtdDiscriminator;
    subschema2.jtdMetadata = jtdMetadata;
  }
  subschema.extendSubschemaMode = extendSubschemaMode;
  return subschema;
}
var resolve = {};
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,
    if: true,
    then: true,
    else: true
  };
  traverse.arrayKeywords = {
    items: true,
    allOf: true,
    anyOf: true,
    oneOf: true
  };
  traverse.propsKeywords = {
    $defs: true,
    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 key in schema) {
        var sch = schema[key];
        if (Array.isArray(sch)) {
          if (key in traverse.arrayKeywords) {
            for (var i2 = 0; i2 < sch.length; i2++)
              _traverse(opts, pre, post, sch[i2], jsonPtr + "/" + key + "/" + i2, rootSchema, jsonPtr, key, schema, i2);
          }
        } else if (key in traverse.propsKeywords) {
          if (sch && typeof sch == "object") {
            for (var prop in sch)
              _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
          }
        } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
          _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
        }
      }
      post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    }
  }
  function escapeJsonPtr(str) {
    return str.replace(/~/g, "~0").replace(/\//g, "~1");
  }
  return jsonSchemaTraverse.exports;
}
var hasRequiredResolve;
function requireResolve() {
  if (hasRequiredResolve) return resolve;
  hasRequiredResolve = 1;
  Object.defineProperty(resolve, "__esModule", { value: true });
  resolve.getSchemaRefs = resolve.resolveUrl = resolve.normalizeId = resolve._getFullPath = resolve.getFullPath = resolve.inlineRef = void 0;
  const util_1 = /* @__PURE__ */ requireUtil();
  const equal2 = requireFastDeepEqual();
  const traverse = requireJsonSchemaTraverse();
  const SIMPLE_INLINED = /* @__PURE__ */ new Set([
    "type",
    "format",
    "pattern",
    "maxLength",
    "minLength",
    "maxProperties",
    "minProperties",
    "maxItems",
    "minItems",
    "maximum",
    "minimum",
    "uniqueItems",
    "multipleOf",
    "required",
    "enum",
    "const"
  ]);
  function inlineRef(schema, limit2 = true) {
    if (typeof schema == "boolean")
      return true;
    if (limit2 === true)
      return !hasRef(schema);
    if (!limit2)
      return false;
    return countKeys(schema) <= limit2;
  }
  resolve.inlineRef = inlineRef;
  const REF_KEYWORDS = /* @__PURE__ */ new Set([
    "$ref",
    "$recursiveRef",
    "$recursiveAnchor",
    "$dynamicRef",
    "$dynamicAnchor"
  ]);
  function hasRef(schema) {
    for (const key in schema) {
      if (REF_KEYWORDS.has(key))
        return true;
      const sch = schema[key];
      if (Array.isArray(sch) && sch.some(hasRef))
        return true;
      if (typeof sch == "object" && hasRef(sch))
        return true;
    }
    return false;
  }
  function countKeys(schema) {
    let count2 = 0;
    for (const key in schema) {
      if (key === "$ref")
        return Infinity;
      count2++;
      if (SIMPLE_INLINED.has(key))
        continue;
      if (typeof schema[key] == "object") {
        (0, util_1.eachItem)(schema[key], (sch) => count2 += countKeys(sch));
      }
      if (count2 === Infinity)
        return Infinity;
    }
    return count2;
  }
  function getFullPath(resolver, id2 = "", normalize) {
    if (normalize !== false)
      id2 = normalizeId(id2);
    const p2 = resolver.parse(id2);
    return _getFullPath(resolver, p2);
  }
  resolve.getFullPath = getFullPath;
  function _getFullPath(resolver, p2) {
    const serialized = resolver.serialize(p2);
    return serialized.split("#")[0] + "#";
  }
  resolve._getFullPath = _getFullPath;
  const TRAILING_SLASH_HASH = /#\/?$/;
  function normalizeId(id2) {
    return id2 ? id2.replace(TRAILING_SLASH_HASH, "") : "";
  }
  resolve.normalizeId = normalizeId;
  function resolveUrl(resolver, baseId, id2) {
    id2 = normalizeId(id2);
    return resolver.resolve(baseId, id2);
  }
  resolve.resolveUrl = resolveUrl;
  const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
  function getSchemaRefs(schema, baseId) {
    if (typeof schema == "boolean")
      return {};
    const { schemaId, uriResolver } = this.opts;
    const schId = normalizeId(schema[schemaId] || baseId);
    const baseIds = { "": schId };
    const pathPrefix = getFullPath(uriResolver, schId, false);
    const localRefs = {};
    const schemaRefs = /* @__PURE__ */ new Set();
    traverse(schema, { allKeys: true }, (sch, jsonPtr, _2, parentJsonPtr) => {
      if (parentJsonPtr === void 0)
        return;
      const fullPath = pathPrefix + jsonPtr;
      let innerBaseId = baseIds[parentJsonPtr];
      if (typeof sch[schemaId] == "string")
        innerBaseId = addRef.call(this, sch[schemaId]);
      addAnchor.call(this, sch.$anchor);
      addAnchor.call(this, sch.$dynamicAnchor);
      baseIds[jsonPtr] = innerBaseId;
      function addRef(ref2) {
        const _resolve = this.opts.uriResolver.resolve;
        ref2 = normalizeId(innerBaseId ? _resolve(innerBaseId, ref2) : ref2);
        if (schemaRefs.has(ref2))
          throw ambiguos(ref2);
        schemaRefs.add(ref2);
        let schOrRef = this.refs[ref2];
        if (typeof schOrRef == "string")
          schOrRef = this.refs[schOrRef];
        if (typeof schOrRef == "object") {
          checkAmbiguosRef(sch, schOrRef.schema, ref2);
        } else if (ref2 !== normalizeId(fullPath)) {
          if (ref2[0] === "#") {
            checkAmbiguosRef(sch, localRefs[ref2], ref2);
            localRefs[ref2] = sch;
          } else {
            this.refs[ref2] = fullPath;
          }
        }
        return ref2;
      }
      function addAnchor(anchor) {
        if (typeof anchor == "string") {
          if (!ANCHOR.test(anchor))
            throw new Error(`invalid anchor "${anchor}"`);
          addRef.call(this, `#${anchor}`);
        }
      }
    });
    return localRefs;
    function checkAmbiguosRef(sch1, sch2, ref2) {
      if (sch2 !== void 0 && !equal2(sch1, sch2))
        throw ambiguos(ref2);
    }
    function ambiguos(ref2) {
      return new Error(`reference "${ref2}" resolves to more than one schema`);
    }
  }
  resolve.getSchemaRefs = getSchemaRefs;
  return resolve;
}
var hasRequiredValidate;
function requireValidate() {
  if (hasRequiredValidate) return validate;
  hasRequiredValidate = 1;
  Object.defineProperty(validate, "__esModule", { value: true });
  validate.getData = validate.KeywordCxt = validate.validateFunctionCode = void 0;
  const boolSchema_1 = /* @__PURE__ */ requireBoolSchema();
  const dataType_1 = /* @__PURE__ */ requireDataType();
  const applicability_1 = /* @__PURE__ */ requireApplicability();
  const dataType_2 = /* @__PURE__ */ requireDataType();
  const defaults_1 = /* @__PURE__ */ requireDefaults();
  const keyword_1 = /* @__PURE__ */ requireKeyword();
  const subschema_1 = /* @__PURE__ */ requireSubschema();
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const names_1 = /* @__PURE__ */ requireNames();
  const resolve_12 = /* @__PURE__ */ requireResolve();
  const util_1 = /* @__PURE__ */ requireUtil();
  const errors_1 = /* @__PURE__ */ requireErrors();
  function validateFunctionCode(it2) {
    if (isSchemaObj(it2)) {
      checkKeywords(it2);
      if (schemaCxtHasRules(it2)) {
        topSchemaObjCode(it2);
        return;
      }
    }
    validateFunction(it2, () => (0, boolSchema_1.topBoolOrEmptySchema)(it2));
  }
  validate.validateFunctionCode = validateFunctionCode;
  function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
    if (opts.code.es5) {
      gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
        gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
        destructureValCxtES5(gen, opts);
        gen.code(body);
      });
    } else {
      gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
    }
  }
  function destructureValCxt(opts) {
    return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
  }
  function destructureValCxtES5(gen, opts) {
    gen.if(names_1.default.valCxt, () => {
      gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);
      gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);
      gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
      gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);
      if (opts.dynamicRef)
        gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
    }, () => {
      gen.var(names_1.default.instancePath, (0, codegen_1._)`""`);
      gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`);
      gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`);
      gen.var(names_1.default.rootData, names_1.default.data);
      if (opts.dynamicRef)
        gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`);
    });
  }
  function topSchemaObjCode(it2) {
    const { schema, opts, gen } = it2;
    validateFunction(it2, () => {
      if (opts.$comment && schema.$comment)
        commentKeyword(it2);
      checkNoDefault(it2);
      gen.let(names_1.default.vErrors, null);
      gen.let(names_1.default.errors, 0);
      if (opts.unevaluated)
        resetEvaluated(it2);
      typeAndKeywords(it2);
      returnResults(it2);
    });
    return;
  }
  function resetEvaluated(it2) {
    const { gen, validateName } = it2;
    it2.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`);
    gen.if((0, codegen_1._)`${it2.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.props`, (0, codegen_1._)`undefined`));
    gen.if((0, codegen_1._)`${it2.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.items`, (0, codegen_1._)`undefined`));
  }
  function funcSourceUrl(schema, opts) {
    const schId = typeof schema == "object" && schema[opts.schemaId];
    return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil;
  }
  function subschemaCode(it2, valid) {
    if (isSchemaObj(it2)) {
      checkKeywords(it2);
      if (schemaCxtHasRules(it2)) {
        subSchemaObjCode(it2, valid);
        return;
      }
    }
    (0, boolSchema_1.boolOrEmptySchema)(it2, valid);
  }
  function schemaCxtHasRules({ schema, self: self2 }) {
    if (typeof schema == "boolean")
      return !schema;
    for (const key in schema)
      if (self2.RULES.all[key])
        return true;
    return false;
  }
  function isSchemaObj(it2) {
    return typeof it2.schema != "boolean";
  }
  function subSchemaObjCode(it2, valid) {
    const { schema, gen, opts } = it2;
    if (opts.$comment && schema.$comment)
      commentKeyword(it2);
    updateContext(it2);
    checkAsyncSchema(it2);
    const errsCount = gen.const("_errs", names_1.default.errors);
    typeAndKeywords(it2, errsCount);
    gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
  }
  function checkKeywords(it2) {
    (0, util_1.checkUnknownRules)(it2);
    checkRefsAndKeywords(it2);
  }
  function typeAndKeywords(it2, errsCount) {
    if (it2.opts.jtd)
      return schemaKeywords(it2, [], false, errsCount);
    const types2 = (0, dataType_1.getSchemaTypes)(it2.schema);
    const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it2, types2);
    schemaKeywords(it2, types2, !checkedTypes, errsCount);
  }
  function checkRefsAndKeywords(it2) {
    const { schema, errSchemaPath, opts, self: self2 } = it2;
    if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
      self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
    }
  }
  function checkNoDefault(it2) {
    const { schema, opts } = it2;
    if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
      (0, util_1.checkStrictMode)(it2, "default is ignored in the schema root");
    }
  }
  function updateContext(it2) {
    const schId = it2.schema[it2.opts.schemaId];
    if (schId)
      it2.baseId = (0, resolve_12.resolveUrl)(it2.opts.uriResolver, it2.baseId, schId);
  }
  function checkAsyncSchema(it2) {
    if (it2.schema.$async && !it2.schemaEnv.$async)
      throw new Error("async schema in sync schema");
  }
  function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
    const msg = schema.$comment;
    if (opts.$comment === true) {
      gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`);
    } else if (typeof opts.$comment == "function") {
      const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`;
      const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
      gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
    }
  }
  function returnResults(it2) {
    const { gen, schemaEnv, validateName, ValidationError, opts } = it2;
    if (schemaEnv.$async) {
      gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
    } else {
      gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);
      if (opts.unevaluated)
        assignEvaluated(it2);
      gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);
    }
  }
  function assignEvaluated({ gen, evaluated, props, items: items2 }) {
    if (props instanceof codegen_1.Name)
      gen.assign((0, codegen_1._)`${evaluated}.props`, props);
    if (items2 instanceof codegen_1.Name)
      gen.assign((0, codegen_1._)`${evaluated}.items`, items2);
  }
  function schemaKeywords(it2, types2, typeErrors, errsCount) {
    const { gen, schema, data: data2, allErrors, opts, self: self2 } = it2;
    const { RULES } = self2;
    if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
      gen.block(() => keywordCode(it2, "$ref", RULES.all.$ref.definition));
      return;
    }
    if (!opts.jtd)
      checkStrictTypes(it2, types2);
    gen.block(() => {
      for (const group of RULES.rules)
        groupKeywords(group);
      groupKeywords(RULES.post);
    });
    function groupKeywords(group) {
      if (!(0, applicability_1.shouldUseGroup)(schema, group))
        return;
      if (group.type) {
        gen.if((0, dataType_2.checkDataType)(group.type, data2, opts.strictNumbers));
        iterateKeywords(it2, group);
        if (types2.length === 1 && types2[0] === group.type && typeErrors) {
          gen.else();
          (0, dataType_2.reportTypeError)(it2);
        }
        gen.endIf();
      } else {
        iterateKeywords(it2, group);
      }
      if (!allErrors)
        gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
    }
  }
  function iterateKeywords(it2, group) {
    const { gen, schema, opts: { useDefaults } } = it2;
    if (useDefaults)
      (0, defaults_1.assignDefaults)(it2, group.type);
    gen.block(() => {
      for (const rule of group.rules) {
        if ((0, applicability_1.shouldUseRule)(schema, rule)) {
          keywordCode(it2, rule.keyword, rule.definition, group.type);
        }
      }
    });
  }
  function checkStrictTypes(it2, types2) {
    if (it2.schemaEnv.meta || !it2.opts.strictTypes)
      return;
    checkContextTypes(it2, types2);
    if (!it2.opts.allowUnionTypes)
      checkMultipleTypes(it2, types2);
    checkKeywordTypes(it2, it2.dataTypes);
  }
  function checkContextTypes(it2, types2) {
    if (!types2.length)
      return;
    if (!it2.dataTypes.length) {
      it2.dataTypes = types2;
      return;
    }
    types2.forEach((t2) => {
      if (!includesType(it2.dataTypes, t2)) {
        strictTypesError(it2, `type "${t2}" not allowed by context "${it2.dataTypes.join(",")}"`);
      }
    });
    narrowSchemaTypes(it2, types2);
  }
  function checkMultipleTypes(it2, ts2) {
    if (ts2.length > 1 && !(ts2.length === 2 && ts2.includes("null"))) {
      strictTypesError(it2, "use allowUnionTypes to allow union type keyword");
    }
  }
  function checkKeywordTypes(it2, ts2) {
    const rules2 = it2.self.RULES.all;
    for (const keyword2 in rules2) {
      const rule = rules2[keyword2];
      if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it2.schema, rule)) {
        const { type: type2 } = rule.definition;
        if (type2.length && !type2.some((t2) => hasApplicableType(ts2, t2))) {
          strictTypesError(it2, `missing type "${type2.join(",")}" for keyword "${keyword2}"`);
        }
      }
    }
  }
  function hasApplicableType(schTs, kwdT) {
    return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
  }
  function includesType(ts2, t2) {
    return ts2.includes(t2) || t2 === "integer" && ts2.includes("number");
  }
  function narrowSchemaTypes(it2, withTypes) {
    const ts2 = [];
    for (const t2 of it2.dataTypes) {
      if (includesType(withTypes, t2))
        ts2.push(t2);
      else if (withTypes.includes("integer") && t2 === "number")
        ts2.push("integer");
    }
    it2.dataTypes = ts2;
  }
  function strictTypesError(it2, msg) {
    const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath;
    msg += ` at "${schemaPath}" (strictTypes)`;
    (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictTypes);
  }
  class KeywordCxt {
    constructor(it2, def, keyword2) {
      (0, keyword_1.validateKeywordUsage)(it2, def, keyword2);
      this.gen = it2.gen;
      this.allErrors = it2.allErrors;
      this.keyword = keyword2;
      this.data = it2.data;
      this.schema = it2.schema[keyword2];
      this.$data = def.$data && it2.opts.$data && this.schema && this.schema.$data;
      this.schemaValue = (0, util_1.schemaRefOrVal)(it2, this.schema, keyword2, this.$data);
      this.schemaType = def.schemaType;
      this.parentSchema = it2.schema;
      this.params = {};
      this.it = it2;
      this.def = def;
      if (this.$data) {
        this.schemaCode = it2.gen.const("vSchema", getData(this.$data, it2));
      } else {
        this.schemaCode = this.schemaValue;
        if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
          throw new Error(`${keyword2} value must be ${JSON.stringify(def.schemaType)}`);
        }
      }
      if ("code" in def ? def.trackErrors : def.errors !== false) {
        this.errsCount = it2.gen.const("_errs", names_1.default.errors);
      }
    }
    result(condition, successAction, failAction) {
      this.failResult((0, codegen_1.not)(condition), successAction, failAction);
    }
    failResult(condition, successAction, failAction) {
      this.gen.if(condition);
      if (failAction)
        failAction();
      else
        this.error();
      if (successAction) {
        this.gen.else();
        successAction();
        if (this.allErrors)
          this.gen.endIf();
      } else {
        if (this.allErrors)
          this.gen.endIf();
        else
          this.gen.else();
      }
    }
    pass(condition, failAction) {
      this.failResult((0, codegen_1.not)(condition), void 0, failAction);
    }
    fail(condition) {
      if (condition === void 0) {
        this.error();
        if (!this.allErrors)
          this.gen.if(false);
        return;
      }
      this.gen.if(condition);
      this.error();
      if (this.allErrors)
        this.gen.endIf();
      else
        this.gen.else();
    }
    fail$data(condition) {
      if (!this.$data)
        return this.fail(condition);
      const { schemaCode } = this;
      this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
    }
    error(append, errorParams, errorPaths) {
      if (errorParams) {
        this.setParams(errorParams);
        this._error(append, errorPaths);
        this.setParams({});
        return;
      }
      this._error(append, errorPaths);
    }
    _error(append, errorPaths) {
      (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
    }
    $dataError() {
      (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
    }
    reset() {
      if (this.errsCount === void 0)
        throw new Error('add "trackErrors" to keyword definition');
      (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
    }
    ok(cond) {
      if (!this.allErrors)
        this.gen.if(cond);
    }
    setParams(obj, assign) {
      if (assign)
        Object.assign(this.params, obj);
      else
        this.params = obj;
    }
    block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
      this.gen.block(() => {
        this.check$data(valid, $dataValid);
        codeBlock();
      });
    }
    check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
      if (!this.$data)
        return;
      const { gen, schemaCode, schemaType, def } = this;
      gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));
      if (valid !== codegen_1.nil)
        gen.assign(valid, true);
      if (schemaType.length || def.validateSchema) {
        gen.elseIf(this.invalid$data());
        this.$dataError();
        if (valid !== codegen_1.nil)
          gen.assign(valid, false);
      }
      gen.else();
    }
    invalid$data() {
      const { gen, schemaCode, schemaType, def, it: it2 } = this;
      return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
      function wrong$DataType() {
        if (schemaType.length) {
          if (!(schemaCode instanceof codegen_1.Name))
            throw new Error("ajv implementation error");
          const st2 = Array.isArray(schemaType) ? schemaType : [schemaType];
          return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st2, schemaCode, it2.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
        }
        return codegen_1.nil;
      }
      function invalid$DataSchema() {
        if (def.validateSchema) {
          const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });
          return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;
        }
        return codegen_1.nil;
      }
    }
    subschema(appl, valid) {
      const subschema2 = (0, subschema_1.getSubschema)(this.it, appl);
      (0, subschema_1.extendSubschemaData)(subschema2, this.it, appl);
      (0, subschema_1.extendSubschemaMode)(subschema2, appl);
      const nextContext = { ...this.it, ...subschema2, items: void 0, props: void 0 };
      subschemaCode(nextContext, valid);
      return nextContext;
    }
    mergeEvaluated(schemaCxt, toName) {
      const { it: it2, gen } = this;
      if (!it2.opts.unevaluated)
        return;
      if (it2.props !== true && schemaCxt.props !== void 0) {
        it2.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it2.props, toName);
      }
      if (it2.items !== true && schemaCxt.items !== void 0) {
        it2.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it2.items, toName);
      }
    }
    mergeValidEvaluated(schemaCxt, valid) {
      const { it: it2, gen } = this;
      if (it2.opts.unevaluated && (it2.props !== true || it2.items !== true)) {
        gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
        return true;
      }
    }
  }
  validate.KeywordCxt = KeywordCxt;
  function keywordCode(it2, keyword2, def, ruleType) {
    const cxt = new KeywordCxt(it2, def, keyword2);
    if ("code" in def) {
      def.code(cxt, ruleType);
    } else if (cxt.$data && def.validate) {
      (0, keyword_1.funcKeywordCode)(cxt, def);
    } else if ("macro" in def) {
      (0, keyword_1.macroKeywordCode)(cxt, def);
    } else if (def.compile || def.validate) {
      (0, keyword_1.funcKeywordCode)(cxt, def);
    }
  }
  const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
  const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
  function getData($data, { dataLevel, dataNames, dataPathArr }) {
    let jsonPointer;
    let data2;
    if ($data === "")
      return names_1.default.rootData;
    if ($data[0] === "/") {
      if (!JSON_POINTER.test($data))
        throw new Error(`Invalid JSON-pointer: ${$data}`);
      jsonPointer = $data;
      data2 = names_1.default.rootData;
    } else {
      const matches = RELATIVE_JSON_POINTER.exec($data);
      if (!matches)
        throw new Error(`Invalid JSON-pointer: ${$data}`);
      const up2 = +matches[1];
      jsonPointer = matches[2];
      if (jsonPointer === "#") {
        if (up2 >= dataLevel)
          throw new Error(errorMsg("property/index", up2));
        return dataPathArr[dataLevel - up2];
      }
      if (up2 > dataLevel)
        throw new Error(errorMsg("data", up2));
      data2 = dataNames[dataLevel - up2];
      if (!jsonPointer)
        return data2;
    }
    let expr = data2;
    const segments = jsonPointer.split("/");
    for (const segment of segments) {
      if (segment) {
        data2 = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
        expr = (0, codegen_1._)`${expr} && ${data2}`;
      }
    }
    return expr;
    function errorMsg(pointerType, up2) {
      return `Cannot access ${pointerType} ${up2} levels up, current level is ${dataLevel}`;
    }
  }
  validate.getData = getData;
  return validate;
}
var validation_error = {};
var hasRequiredValidation_error;
function requireValidation_error() {
  if (hasRequiredValidation_error) return validation_error;
  hasRequiredValidation_error = 1;
  Object.defineProperty(validation_error, "__esModule", { value: true });
  class ValidationError extends Error {
    constructor(errors2) {
      super("validation failed");
      this.errors = errors2;
      this.ajv = this.validation = true;
    }
  }
  validation_error.default = ValidationError;
  return validation_error;
}
var ref_error = {};
var hasRequiredRef_error;
function requireRef_error() {
  if (hasRequiredRef_error) return ref_error;
  hasRequiredRef_error = 1;
  Object.defineProperty(ref_error, "__esModule", { value: true });
  const resolve_12 = /* @__PURE__ */ requireResolve();
  class MissingRefError extends Error {
    constructor(resolver, baseId, ref2, msg) {
      super(msg || `can't resolve reference ${ref2} from id ${baseId}`);
      this.missingRef = (0, resolve_12.resolveUrl)(resolver, baseId, ref2);
      this.missingSchema = (0, resolve_12.normalizeId)((0, resolve_12.getFullPath)(resolver, this.missingRef));
    }
  }
  ref_error.default = MissingRefError;
  return ref_error;
}
var compile = {};
var hasRequiredCompile;
function requireCompile() {
  if (hasRequiredCompile) return compile;
  hasRequiredCompile = 1;
  Object.defineProperty(compile, "__esModule", { value: true });
  compile.resolveSchema = compile.getCompilingSchema = compile.resolveRef = compile.compileSchema = compile.SchemaEnv = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const validation_error_1 = /* @__PURE__ */ requireValidation_error();
  const names_1 = /* @__PURE__ */ requireNames();
  const resolve_12 = /* @__PURE__ */ requireResolve();
  const util_1 = /* @__PURE__ */ requireUtil();
  const validate_1 = /* @__PURE__ */ requireValidate();
  class SchemaEnv {
    constructor(env) {
      var _a2;
      this.refs = {};
      this.dynamicAnchors = {};
      let schema;
      if (typeof env.schema == "object")
        schema = env.schema;
      this.schema = env.schema;
      this.schemaId = env.schemaId;
      this.root = env.root || this;
      this.baseId = (_a2 = env.baseId) !== null && _a2 !== void 0 ? _a2 : (0, resolve_12.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
      this.schemaPath = env.schemaPath;
      this.localRefs = env.localRefs;
      this.meta = env.meta;
      this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
      this.refs = {};
    }
  }
  compile.SchemaEnv = SchemaEnv;
  function compileSchema(sch) {
    const _sch = getCompilingSchema.call(this, sch);
    if (_sch)
      return _sch;
    const rootId = (0, resolve_12.getFullPath)(this.opts.uriResolver, sch.root.baseId);
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    let _ValidationError;
    if (sch.$async) {
      _ValidationError = gen.scopeValue("Error", {
        ref: validation_error_1.default,
        code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default`
      });
    }
    const validateName = gen.scopeName("validate");
    sch.validateName = validateName;
    const schemaCxt = {
      gen,
      allErrors: this.opts.allErrors,
      data: names_1.default.data,
      parentData: names_1.default.parentData,
      parentDataProperty: names_1.default.parentDataProperty,
      dataNames: [names_1.default.data],
      dataPathArr: [codegen_1.nil],
      // TODO can its length be used as dataLevel if nil is removed?
      dataLevel: 0,
      dataTypes: [],
      definedProperties: /* @__PURE__ */ new Set(),
      topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }),
      validateName,
      ValidationError: _ValidationError,
      schema: sch.schema,
      schemaEnv: sch,
      rootId,
      baseId: sch.baseId || rootId,
      schemaPath: codegen_1.nil,
      errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
      errorPath: (0, codegen_1._)`""`,
      opts: this.opts,
      self: this
    };
    let sourceCode;
    try {
      this._compilations.add(sch);
      (0, validate_1.validateFunctionCode)(schemaCxt);
      gen.optimize(this.opts.code.optimize);
      const validateCode = gen.toString();
      sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
      if (this.opts.code.process)
        sourceCode = this.opts.code.process(sourceCode, sch);
      const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
      const validate2 = makeValidate(this, this.scope.get());
      this.scope.value(validateName, { ref: validate2 });
      validate2.errors = null;
      validate2.schema = sch.schema;
      validate2.schemaEnv = sch;
      if (sch.$async)
        validate2.$async = true;
      if (this.opts.code.source === true) {
        validate2.source = { validateName, validateCode, scopeValues: gen._values };
      }
      if (this.opts.unevaluated) {
        const { props, items: items2 } = schemaCxt;
        validate2.evaluated = {
          props: props instanceof codegen_1.Name ? void 0 : props,
          items: items2 instanceof codegen_1.Name ? void 0 : items2,
          dynamicProps: props instanceof codegen_1.Name,
          dynamicItems: items2 instanceof codegen_1.Name
        };
        if (validate2.source)
          validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated);
      }
      sch.validate = validate2;
      return sch;
    } catch (e2) {
      delete sch.validate;
      delete sch.validateName;
      if (sourceCode)
        this.logger.error("Error compiling schema, function code:", sourceCode);
      throw e2;
    } finally {
      this._compilations.delete(sch);
    }
  }
  compile.compileSchema = compileSchema;
  function resolveRef2(root, baseId, ref2) {
    var _a2;
    ref2 = (0, resolve_12.resolveUrl)(this.opts.uriResolver, baseId, ref2);
    const schOrFunc = root.refs[ref2];
    if (schOrFunc)
      return schOrFunc;
    let _sch = resolve2.call(this, root, ref2);
    if (_sch === void 0) {
      const schema = (_a2 = root.localRefs) === null || _a2 === void 0 ? void 0 : _a2[ref2];
      const { schemaId } = this.opts;
      if (schema)
        _sch = new SchemaEnv({ schema, schemaId, root, baseId });
    }
    if (_sch === void 0)
      return;
    return root.refs[ref2] = inlineOrCompile.call(this, _sch);
  }
  compile.resolveRef = resolveRef2;
  function inlineOrCompile(sch) {
    if ((0, resolve_12.inlineRef)(sch.schema, this.opts.inlineRefs))
      return sch.schema;
    return sch.validate ? sch : compileSchema.call(this, sch);
  }
  function getCompilingSchema(schEnv) {
    for (const sch of this._compilations) {
      if (sameSchemaEnv(sch, schEnv))
        return sch;
    }
  }
  compile.getCompilingSchema = getCompilingSchema;
  function sameSchemaEnv(s1, s2) {
    return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
  }
  function resolve2(root, ref2) {
    let sch;
    while (typeof (sch = this.refs[ref2]) == "string")
      ref2 = sch;
    return sch || this.schemas[ref2] || resolveSchema.call(this, root, ref2);
  }
  function resolveSchema(root, ref2) {
    const p2 = this.opts.uriResolver.parse(ref2);
    const refPath = (0, resolve_12._getFullPath)(this.opts.uriResolver, p2);
    let baseId = (0, resolve_12.getFullPath)(this.opts.uriResolver, root.baseId, void 0);
    if (Object.keys(root.schema).length > 0 && refPath === baseId) {
      return getJsonPointer.call(this, p2, root);
    }
    const id2 = (0, resolve_12.normalizeId)(refPath);
    const schOrRef = this.refs[id2] || this.schemas[id2];
    if (typeof schOrRef == "string") {
      const sch = resolveSchema.call(this, root, schOrRef);
      if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
        return;
      return getJsonPointer.call(this, p2, sch);
    }
    if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
      return;
    if (!schOrRef.validate)
      compileSchema.call(this, schOrRef);
    if (id2 === (0, resolve_12.normalizeId)(ref2)) {
      const { schema } = schOrRef;
      const { schemaId } = this.opts;
      const schId = schema[schemaId];
      if (schId)
        baseId = (0, resolve_12.resolveUrl)(this.opts.uriResolver, baseId, schId);
      return new SchemaEnv({ schema, schemaId, root, baseId });
    }
    return getJsonPointer.call(this, p2, schOrRef);
  }
  compile.resolveSchema = resolveSchema;
  const PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
    "properties",
    "patternProperties",
    "enum",
    "dependencies",
    "definitions"
  ]);
  function getJsonPointer(parsedRef, { baseId, schema, root }) {
    var _a2;
    if (((_a2 = parsedRef.fragment) === null || _a2 === void 0 ? void 0 : _a2[0]) !== "/")
      return;
    for (const part of parsedRef.fragment.slice(1).split("/")) {
      if (typeof schema === "boolean")
        return;
      const partSchema = schema[(0, util_1.unescapeFragment)(part)];
      if (partSchema === void 0)
        return;
      schema = partSchema;
      const schId = typeof schema === "object" && schema[this.opts.schemaId];
      if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
        baseId = (0, resolve_12.resolveUrl)(this.opts.uriResolver, baseId, schId);
      }
    }
    let env;
    if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
      const $ref = (0, resolve_12.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
      env = resolveSchema.call(this, root, $ref);
    }
    const { schemaId } = this.opts;
    env = env || new SchemaEnv({ schema, schemaId, root, baseId });
    if (env.schema !== env.root.schema)
      return env;
    return void 0;
  }
  return compile;
}
const $id$1 = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#";
const description = "Meta-schema for $data reference (JSON AnySchema extension proposal)";
const type$1 = "object";
const required$1 = ["$data"];
const properties$2 = { "$data": { "type": "string", "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] } };
const additionalProperties$1 = false;
const require$$9 = {
  $id: $id$1,
  description,
  type: type$1,
  required: required$1,
  properties: properties$2,
  additionalProperties: additionalProperties$1
};
var uri = {};
var hasRequiredUri;
function requireUri() {
  if (hasRequiredUri) return uri;
  hasRequiredUri = 1;
  Object.defineProperty(uri, "__esModule", { value: true });
  const uri$12 = requireFastUri();
  uri$12.code = 'require("ajv/dist/runtime/uri").default';
  uri.default = uri$12;
  return uri;
}
var hasRequiredCore$1;
function requireCore$1() {
  if (hasRequiredCore$1) return core$1;
  hasRequiredCore$1 = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
    var validate_1 = /* @__PURE__ */ requireValidate();
    Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
      return validate_1.KeywordCxt;
    } });
    var codegen_1 = /* @__PURE__ */ requireCodegen();
    Object.defineProperty(exports, "_", { enumerable: true, get: function() {
      return codegen_1._;
    } });
    Object.defineProperty(exports, "str", { enumerable: true, get: function() {
      return codegen_1.str;
    } });
    Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
      return codegen_1.stringify;
    } });
    Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
      return codegen_1.nil;
    } });
    Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
      return codegen_1.Name;
    } });
    Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
      return codegen_1.CodeGen;
    } });
    const validation_error_1 = /* @__PURE__ */ requireValidation_error();
    const ref_error_1 = /* @__PURE__ */ requireRef_error();
    const rules_1 = /* @__PURE__ */ requireRules();
    const compile_12 = /* @__PURE__ */ requireCompile();
    const codegen_2 = /* @__PURE__ */ requireCodegen();
    const resolve_12 = /* @__PURE__ */ requireResolve();
    const dataType_1 = /* @__PURE__ */ requireDataType();
    const util_1 = /* @__PURE__ */ requireUtil();
    const $dataRefSchema = require$$9;
    const uri_1 = /* @__PURE__ */ requireUri();
    const defaultRegExp = (str, flags) => new RegExp(str, flags);
    defaultRegExp.code = "new RegExp";
    const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
    const EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
      "validate",
      "serialize",
      "parse",
      "wrapper",
      "root",
      "schema",
      "keyword",
      "pattern",
      "formats",
      "validate$data",
      "func",
      "obj",
      "Error"
    ]);
    const removedOptions = {
      errorDataPath: "",
      format: "`validateFormats: false` can be used instead.",
      nullable: '"nullable" keyword is supported by default.',
      jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
      extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
      missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
      processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
      sourceCode: "Use option `code: {source: true}`",
      strictDefaults: "It is default now, see option `strict`.",
      strictKeywords: "It is default now, see option `strict`.",
      uniqueItems: '"uniqueItems" keyword is always validated.',
      unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
      cache: "Map is used as cache, schema object as key.",
      serialize: "Map is used as cache, schema object as key.",
      ajvErrors: "It is default now."
    };
    const deprecatedOptions = {
      ignoreKeywordsWithRef: "",
      jsPropertySyntax: "",
      unicode: '"minLength"/"maxLength" account for unicode characters by default.'
    };
    const MAX_EXPRESSION = 200;
    function requiredOptions(o2) {
      var _a2, _b, _c, _d2, _e2, _f2, _g, _h, _j, _k, _l2, _m2, _o2, _p2, _q, _r2, _s2, _t2, _u2, _v2, _w, _x, _y, _z, _0;
      const s2 = o2.strict;
      const _optz = (_a2 = o2.code) === null || _a2 === void 0 ? void 0 : _a2.optimize;
      const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
      const regExp = (_c = (_b = o2.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
      const uriResolver = (_d2 = o2.uriResolver) !== null && _d2 !== void 0 ? _d2 : uri_1.default;
      return {
        strictSchema: (_f2 = (_e2 = o2.strictSchema) !== null && _e2 !== void 0 ? _e2 : s2) !== null && _f2 !== void 0 ? _f2 : true,
        strictNumbers: (_h = (_g = o2.strictNumbers) !== null && _g !== void 0 ? _g : s2) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o2.strictTypes) !== null && _j !== void 0 ? _j : s2) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m2 = (_l2 = o2.strictTuples) !== null && _l2 !== void 0 ? _l2 : s2) !== null && _m2 !== void 0 ? _m2 : "log",
        strictRequired: (_p2 = (_o2 = o2.strictRequired) !== null && _o2 !== void 0 ? _o2 : s2) !== null && _p2 !== void 0 ? _p2 : false,
        code: o2.code ? { ...o2.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o2.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r2 = o2.loopEnum) !== null && _r2 !== void 0 ? _r2 : MAX_EXPRESSION,
        meta: (_s2 = o2.meta) !== null && _s2 !== void 0 ? _s2 : true,
        messages: (_t2 = o2.messages) !== null && _t2 !== void 0 ? _t2 : true,
        inlineRefs: (_u2 = o2.inlineRefs) !== null && _u2 !== void 0 ? _u2 : true,
        schemaId: (_v2 = o2.schemaId) !== null && _v2 !== void 0 ? _v2 : "$id",
        addUsedSchema: (_w = o2.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o2.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o2.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o2.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o2.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver
      };
    }
    class Ajv2 {
      constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = /* @__PURE__ */ Object.create(null);
        this._compilations = /* @__PURE__ */ new Set();
        this._loading = {};
        this._cache = /* @__PURE__ */ new Map();
        opts = this.opts = { ...opts, ...requiredOptions(opts) };
        const { es5, lines } = this.opts.code;
        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
        this.logger = getLogger(opts.logger);
        const formatOpt = opts.validateFormats;
        opts.validateFormats = false;
        this.RULES = (0, rules_1.getRules)();
        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
        this._metaOpts = getMetaSchemaOptions.call(this);
        if (opts.formats)
          addInitialFormats.call(this);
        this._addVocabularies();
        this._addDefaultMetaSchema();
        if (opts.keywords)
          addInitialKeywords.call(this, opts.keywords);
        if (typeof opts.meta == "object")
          this.addMetaSchema(opts.meta);
        addInitialSchemas.call(this);
        opts.validateFormats = formatOpt;
      }
      _addVocabularies() {
        this.addKeyword("$async");
      }
      _addDefaultMetaSchema() {
        const { $data, meta, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
          _dataRefSchema = { ...$dataRefSchema };
          _dataRefSchema.id = _dataRefSchema.$id;
          delete _dataRefSchema.$id;
        }
        if (meta && $data)
          this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
      }
      defaultMeta() {
        const { meta, schemaId } = this.opts;
        return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0;
      }
      validate(schemaKeyRef, data2) {
        let v2;
        if (typeof schemaKeyRef == "string") {
          v2 = this.getSchema(schemaKeyRef);
          if (!v2)
            throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        } else {
          v2 = this.compile(schemaKeyRef);
        }
        const valid = v2(data2);
        if (!("$async" in v2))
          this.errors = v2.errors;
        return valid;
      }
      compile(schema, _meta) {
        const sch = this._addSchema(schema, _meta);
        return sch.validate || this._compileSchemaEnv(sch);
      }
      compileAsync(schema, meta) {
        if (typeof this.opts.loadSchema != "function") {
          throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta);
        async function runCompileAsync(_schema, _meta) {
          await loadMetaSchema.call(this, _schema.$schema);
          const sch = this._addSchema(_schema, _meta);
          return sch.validate || _compileAsync.call(this, sch);
        }
        async function loadMetaSchema($ref) {
          if ($ref && !this.getSchema($ref)) {
            await runCompileAsync.call(this, { $ref }, true);
          }
        }
        async function _compileAsync(sch) {
          try {
            return this._compileSchemaEnv(sch);
          } catch (e2) {
            if (!(e2 instanceof ref_error_1.default))
              throw e2;
            checkLoaded.call(this, e2);
            await loadMissingSchema.call(this, e2.missingSchema);
            return _compileAsync.call(this, sch);
          }
        }
        function checkLoaded({ missingSchema: ref2, missingRef }) {
          if (this.refs[ref2]) {
            throw new Error(`AnySchema ${ref2} is loaded but ${missingRef} cannot be resolved`);
          }
        }
        async function loadMissingSchema(ref2) {
          const _schema = await _loadSchema.call(this, ref2);
          if (!this.refs[ref2])
            await loadMetaSchema.call(this, _schema.$schema);
          if (!this.refs[ref2])
            this.addSchema(_schema, ref2, meta);
        }
        async function _loadSchema(ref2) {
          const p2 = this._loading[ref2];
          if (p2)
            return p2;
          try {
            return await (this._loading[ref2] = loadSchema(ref2));
          } finally {
            delete this._loading[ref2];
          }
        }
      }
      // Adds schema to the instance
      addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
        if (Array.isArray(schema)) {
          for (const sch of schema)
            this.addSchema(sch, void 0, _meta, _validateSchema);
          return this;
        }
        let id2;
        if (typeof schema === "object") {
          const { schemaId } = this.opts;
          id2 = schema[schemaId];
          if (id2 !== void 0 && typeof id2 != "string") {
            throw new Error(`schema ${schemaId} must be string`);
          }
        }
        key = (0, resolve_12.normalizeId)(key || id2);
        this._checkUnique(key);
        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
        return this;
      }
      // Add schema that will be used to validate other schemas
      // options in META_IGNORE_OPTIONS are alway set to false
      addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
        this.addSchema(schema, key, true, _validateSchema);
        return this;
      }
      //  Validate schema against its meta-schema
      validateSchema(schema, throwOrLogError) {
        if (typeof schema == "boolean")
          return true;
        let $schema2;
        $schema2 = schema.$schema;
        if ($schema2 !== void 0 && typeof $schema2 != "string") {
          throw new Error("$schema must be a string");
        }
        $schema2 = $schema2 || this.opts.defaultMeta || this.defaultMeta();
        if (!$schema2) {
          this.logger.warn("meta-schema not available");
          this.errors = null;
          return true;
        }
        const valid = this.validate($schema2, schema);
        if (!valid && throwOrLogError) {
          const message = "schema is invalid: " + this.errorsText();
          if (this.opts.validateSchema === "log")
            this.logger.error(message);
          else
            throw new Error(message);
        }
        return valid;
      }
      // Get compiled schema by `key` or `ref`.
      // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
      getSchema(keyRef) {
        let sch;
        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
          keyRef = sch;
        if (sch === void 0) {
          const { schemaId } = this.opts;
          const root = new compile_12.SchemaEnv({ schema: {}, schemaId });
          sch = compile_12.resolveSchema.call(this, root, keyRef);
          if (!sch)
            return;
          this.refs[keyRef] = sch;
        }
        return sch.validate || this._compileSchemaEnv(sch);
      }
      // Remove cached schema(s).
      // If no parameter is passed all schemas but meta-schemas are removed.
      // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
      // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
      removeSchema(schemaKeyRef) {
        if (schemaKeyRef instanceof RegExp) {
          this._removeAllSchemas(this.schemas, schemaKeyRef);
          this._removeAllSchemas(this.refs, schemaKeyRef);
          return this;
        }
        switch (typeof schemaKeyRef) {
          case "undefined":
            this._removeAllSchemas(this.schemas);
            this._removeAllSchemas(this.refs);
            this._cache.clear();
            return this;
          case "string": {
            const sch = getSchEnv.call(this, schemaKeyRef);
            if (typeof sch == "object")
              this._cache.delete(sch.schema);
            delete this.schemas[schemaKeyRef];
            delete this.refs[schemaKeyRef];
            return this;
          }
          case "object": {
            const cacheKey = schemaKeyRef;
            this._cache.delete(cacheKey);
            let id2 = schemaKeyRef[this.opts.schemaId];
            if (id2) {
              id2 = (0, resolve_12.normalizeId)(id2);
              delete this.schemas[id2];
              delete this.refs[id2];
            }
            return this;
          }
          default:
            throw new Error("ajv.removeSchema: invalid parameter");
        }
      }
      // add "vocabulary" - a collection of keywords
      addVocabulary(definitions2) {
        for (const def of definitions2)
          this.addKeyword(def);
        return this;
      }
      addKeyword(kwdOrDef, def) {
        let keyword2;
        if (typeof kwdOrDef == "string") {
          keyword2 = kwdOrDef;
          if (typeof def == "object") {
            this.logger.warn("these parameters are deprecated, see docs for addKeyword");
            def.keyword = keyword2;
          }
        } else if (typeof kwdOrDef == "object" && def === void 0) {
          def = kwdOrDef;
          keyword2 = def.keyword;
          if (Array.isArray(keyword2) && !keyword2.length) {
            throw new Error("addKeywords: keyword must be string or non-empty array");
          }
        } else {
          throw new Error("invalid addKeywords parameters");
        }
        checkKeyword.call(this, keyword2, def);
        if (!def) {
          (0, util_1.eachItem)(keyword2, (kwd) => addRule.call(this, kwd));
          return this;
        }
        keywordMetaschema.call(this, def);
        const definition = {
          ...def,
          type: (0, dataType_1.getJSONTypes)(def.type),
          schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)
        };
        (0, util_1.eachItem)(keyword2, definition.type.length === 0 ? (k2) => addRule.call(this, k2, definition) : (k2) => definition.type.forEach((t2) => addRule.call(this, k2, definition, t2)));
        return this;
      }
      getKeyword(keyword2) {
        const rule = this.RULES.all[keyword2];
        return typeof rule == "object" ? rule.definition : !!rule;
      }
      // Remove keyword
      removeKeyword(keyword2) {
        const { RULES } = this;
        delete RULES.keywords[keyword2];
        delete RULES.all[keyword2];
        for (const group of RULES.rules) {
          const i2 = group.rules.findIndex((rule) => rule.keyword === keyword2);
          if (i2 >= 0)
            group.rules.splice(i2, 1);
        }
        return this;
      }
      // Add format
      addFormat(name2, format2) {
        if (typeof format2 == "string")
          format2 = new RegExp(format2);
        this.formats[name2] = format2;
        return this;
      }
      errorsText(errors2 = this.errors, { separator = ", ", dataVar = "data" } = {}) {
        if (!errors2 || errors2.length === 0)
          return "No errors";
        return errors2.map((e2) => `${dataVar}${e2.instancePath} ${e2.message}`).reduce((text, msg) => text + separator + msg);
      }
      $dataMetaSchema(metaSchema, keywordsJsonPointers) {
        const rules2 = this.RULES.all;
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        for (const jsonPointer of keywordsJsonPointers) {
          const segments = jsonPointer.split("/").slice(1);
          let keywords = metaSchema;
          for (const seg of segments)
            keywords = keywords[seg];
          for (const key in rules2) {
            const rule = rules2[key];
            if (typeof rule != "object")
              continue;
            const { $data } = rule.definition;
            const schema = keywords[key];
            if ($data && schema)
              keywords[key] = schemaOrData(schema);
          }
        }
        return metaSchema;
      }
      _removeAllSchemas(schemas, regex) {
        for (const keyRef in schemas) {
          const sch = schemas[keyRef];
          if (!regex || regex.test(keyRef)) {
            if (typeof sch == "string") {
              delete schemas[keyRef];
            } else if (sch && !sch.meta) {
              this._cache.delete(sch.schema);
              delete schemas[keyRef];
            }
          }
        }
      }
      _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
        let id2;
        const { schemaId } = this.opts;
        if (typeof schema == "object") {
          id2 = schema[schemaId];
        } else {
          if (this.opts.jtd)
            throw new Error("schema must be object");
          else if (typeof schema != "boolean")
            throw new Error("schema must be object or boolean");
        }
        let sch = this._cache.get(schema);
        if (sch !== void 0)
          return sch;
        baseId = (0, resolve_12.normalizeId)(id2 || baseId);
        const localRefs = resolve_12.getSchemaRefs.call(this, schema, baseId);
        sch = new compile_12.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
        this._cache.set(sch.schema, sch);
        if (addSchema && !baseId.startsWith("#")) {
          if (baseId)
            this._checkUnique(baseId);
          this.refs[baseId] = sch;
        }
        if (validateSchema)
          this.validateSchema(schema, true);
        return sch;
      }
      _checkUnique(id2) {
        if (this.schemas[id2] || this.refs[id2]) {
          throw new Error(`schema with key or id "${id2}" already exists`);
        }
      }
      _compileSchemaEnv(sch) {
        if (sch.meta)
          this._compileMetaSchema(sch);
        else
          compile_12.compileSchema.call(this, sch);
        if (!sch.validate)
          throw new Error("ajv implementation error");
        return sch.validate;
      }
      _compileMetaSchema(sch) {
        const currentOpts = this.opts;
        this.opts = this._metaOpts;
        try {
          compile_12.compileSchema.call(this, sch);
        } finally {
          this.opts = currentOpts;
        }
      }
    }
    Ajv2.ValidationError = validation_error_1.default;
    Ajv2.MissingRefError = ref_error_1.default;
    exports.default = Ajv2;
    function checkOptions(checkOpts, options, msg, log = "error") {
      for (const key in checkOpts) {
        const opt = key;
        if (opt in options)
          this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
      }
    }
    function getSchEnv(keyRef) {
      keyRef = (0, resolve_12.normalizeId)(keyRef);
      return this.schemas[keyRef] || this.refs[keyRef];
    }
    function addInitialSchemas() {
      const optsSchemas = this.opts.schemas;
      if (!optsSchemas)
        return;
      if (Array.isArray(optsSchemas))
        this.addSchema(optsSchemas);
      else
        for (const key in optsSchemas)
          this.addSchema(optsSchemas[key], key);
    }
    function addInitialFormats() {
      for (const name2 in this.opts.formats) {
        const format2 = this.opts.formats[name2];
        if (format2)
          this.addFormat(name2, format2);
      }
    }
    function addInitialKeywords(defs) {
      if (Array.isArray(defs)) {
        this.addVocabulary(defs);
        return;
      }
      this.logger.warn("keywords option as map is deprecated, pass array");
      for (const keyword2 in defs) {
        const def = defs[keyword2];
        if (!def.keyword)
          def.keyword = keyword2;
        this.addKeyword(def);
      }
    }
    function getMetaSchemaOptions() {
      const metaOpts = { ...this.opts };
      for (const opt of META_IGNORE_OPTIONS)
        delete metaOpts[opt];
      return metaOpts;
    }
    const noLogs = { log() {
    }, warn() {
    }, error() {
    } };
    function getLogger(logger) {
      if (logger === false)
        return noLogs;
      if (logger === void 0)
        return console;
      if (logger.log && logger.warn && logger.error)
        return logger;
      throw new Error("logger must implement log, warn and error methods");
    }
    const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
    function checkKeyword(keyword2, def) {
      const { RULES } = this;
      (0, util_1.eachItem)(keyword2, (kwd) => {
        if (RULES.keywords[kwd])
          throw new Error(`Keyword ${kwd} is already defined`);
        if (!KEYWORD_NAME.test(kwd))
          throw new Error(`Keyword ${kwd} has invalid name`);
      });
      if (!def)
        return;
      if (def.$data && !("code" in def || "validate" in def)) {
        throw new Error('$data keyword must have "code" or "validate" function');
      }
    }
    function addRule(keyword2, definition, dataType2) {
      var _a2;
      const post = definition === null || definition === void 0 ? void 0 : definition.post;
      if (dataType2 && post)
        throw new Error('keyword with "post" flag cannot have "type"');
      const { RULES } = this;
      let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t2 }) => t2 === dataType2);
      if (!ruleGroup) {
        ruleGroup = { type: dataType2, rules: [] };
        RULES.rules.push(ruleGroup);
      }
      RULES.keywords[keyword2] = true;
      if (!definition)
        return;
      const rule = {
        keyword: keyword2,
        definition: {
          ...definition,
          type: (0, dataType_1.getJSONTypes)(definition.type),
          schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)
        }
      };
      if (definition.before)
        addBeforeRule.call(this, ruleGroup, rule, definition.before);
      else
        ruleGroup.rules.push(rule);
      RULES.all[keyword2] = rule;
      (_a2 = definition.implements) === null || _a2 === void 0 ? void 0 : _a2.forEach((kwd) => this.addKeyword(kwd));
    }
    function addBeforeRule(ruleGroup, rule, before) {
      const i2 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i2 >= 0) {
        ruleGroup.rules.splice(i2, 0, rule);
      } else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
      }
    }
    function keywordMetaschema(def) {
      let { metaSchema } = def;
      if (metaSchema === void 0)
        return;
      if (def.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
      def.validateSchema = this.compile(metaSchema, true);
    }
    const $dataRef = {
      $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
    };
    function schemaOrData(schema) {
      return { anyOf: [schema, $dataRef] };
    }
  })(core$1);
  return core$1;
}
var draft7 = {};
var core = {};
var id$1 = {};
var hasRequiredId;
function requireId() {
  if (hasRequiredId) return id$1;
  hasRequiredId = 1;
  Object.defineProperty(id$1, "__esModule", { value: true });
  const def = {
    keyword: "id",
    code() {
      throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
    }
  };
  id$1.default = def;
  return id$1;
}
var ref = {};
var hasRequiredRef;
function requireRef() {
  if (hasRequiredRef) return ref;
  hasRequiredRef = 1;
  Object.defineProperty(ref, "__esModule", { value: true });
  ref.callRef = ref.getValidate = void 0;
  const ref_error_1 = /* @__PURE__ */ requireRef_error();
  const code_1 = /* @__PURE__ */ requireCode();
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const names_1 = /* @__PURE__ */ requireNames();
  const compile_12 = /* @__PURE__ */ requireCompile();
  const util_1 = /* @__PURE__ */ requireUtil();
  const def = {
    keyword: "$ref",
    schemaType: "string",
    code(cxt) {
      const { gen, schema: $ref, it: it2 } = cxt;
      const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it2;
      const { root } = env;
      if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
        return callRootRef();
      const schOrEnv = compile_12.resolveRef.call(self2, root, baseId, $ref);
      if (schOrEnv === void 0)
        throw new ref_error_1.default(it2.opts.uriResolver, baseId, $ref);
      if (schOrEnv instanceof compile_12.SchemaEnv)
        return callValidate(schOrEnv);
      return inlineRefSchema(schOrEnv);
      function callRootRef() {
        if (env === root)
          return callRef(cxt, validateName, env, env.$async);
        const rootName = gen.scopeValue("root", { ref: root });
        return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
      }
      function callValidate(sch) {
        const v2 = getValidate(cxt, sch);
        callRef(cxt, v2, sch, sch.$async);
      }
      function inlineRefSchema(sch) {
        const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
        const valid = gen.name("valid");
        const schCxt = cxt.subschema({
          schema: sch,
          dataTypes: [],
          schemaPath: codegen_1.nil,
          topSchemaRef: schName,
          errSchemaPath: $ref
        }, valid);
        cxt.mergeEvaluated(schCxt);
        cxt.ok(valid);
      }
    }
  };
  function getValidate(cxt, sch) {
    const { gen } = cxt;
    return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
  }
  ref.getValidate = getValidate;
  function callRef(cxt, v2, sch, $async) {
    const { gen, it: it2 } = cxt;
    const { allErrors, schemaEnv: env, opts } = it2;
    const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
    if ($async)
      callAsyncRef();
    else
      callSyncRef();
    function callAsyncRef() {
      if (!env.$async)
        throw new Error("async schema referenced by sync schema");
      const valid = gen.let("valid");
      gen.try(() => {
        gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v2, passCxt)}`);
        addEvaluatedFrom(v2);
        if (!allErrors)
          gen.assign(valid, true);
      }, (e2) => {
        gen.if((0, codegen_1._)`!(${e2} instanceof ${it2.ValidationError})`, () => gen.throw(e2));
        addErrorsFrom(e2);
        if (!allErrors)
          gen.assign(valid, false);
      });
      cxt.ok(valid);
    }
    function callSyncRef() {
      cxt.result((0, code_1.callValidateCode)(cxt, v2, passCxt), () => addEvaluatedFrom(v2), () => addErrorsFrom(v2));
    }
    function addErrorsFrom(source) {
      const errs = (0, codegen_1._)`${source}.errors`;
      gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);
      gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
    }
    function addEvaluatedFrom(source) {
      var _a2;
      if (!it2.opts.unevaluated)
        return;
      const schEvaluated = (_a2 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a2 === void 0 ? void 0 : _a2.evaluated;
      if (it2.props !== true) {
        if (schEvaluated && !schEvaluated.dynamicProps) {
          if (schEvaluated.props !== void 0) {
            it2.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it2.props);
          }
        } else {
          const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`);
          it2.props = util_1.mergeEvaluated.props(gen, props, it2.props, codegen_1.Name);
        }
      }
      if (it2.items !== true) {
        if (schEvaluated && !schEvaluated.dynamicItems) {
          if (schEvaluated.items !== void 0) {
            it2.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it2.items);
          }
        } else {
          const items2 = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`);
          it2.items = util_1.mergeEvaluated.items(gen, items2, it2.items, codegen_1.Name);
        }
      }
    }
  }
  ref.callRef = callRef;
  ref.default = def;
  return ref;
}
var hasRequiredCore;
function requireCore() {
  if (hasRequiredCore) return core;
  hasRequiredCore = 1;
  Object.defineProperty(core, "__esModule", { value: true });
  const id_1 = /* @__PURE__ */ requireId();
  const ref_1 = /* @__PURE__ */ requireRef();
  const core$12 = [
    "$schema",
    "$id",
    "$defs",
    "$vocabulary",
    { keyword: "$comment" },
    "definitions",
    id_1.default,
    ref_1.default
  ];
  core.default = core$12;
  return core;
}
var validation = {};
var limitNumber = {};
var hasRequiredLimitNumber;
function requireLimitNumber() {
  if (hasRequiredLimitNumber) return limitNumber;
  hasRequiredLimitNumber = 1;
  Object.defineProperty(limitNumber, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const ops = codegen_1.operators;
  const KWDs = {
    maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
    minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
    exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
    exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
  };
  const error = {
    message: ({ keyword: keyword2, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword2].okStr} ${schemaCode}`,
    params: ({ keyword: keyword2, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword2].okStr}, limit: ${schemaCode}}`
  };
  const def = {
    keyword: Object.keys(KWDs),
    type: "number",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
      const { keyword: keyword2, data: data2, schemaCode } = cxt;
      cxt.fail$data((0, codegen_1._)`${data2} ${KWDs[keyword2].fail} ${schemaCode} || isNaN(${data2})`);
    }
  };
  limitNumber.default = def;
  return limitNumber;
}
var multipleOf = {};
var hasRequiredMultipleOf;
function requireMultipleOf() {
  if (hasRequiredMultipleOf) return multipleOf;
  hasRequiredMultipleOf = 1;
  Object.defineProperty(multipleOf, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const error = {
    message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,
    params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`
  };
  const def = {
    keyword: "multipleOf",
    type: "number",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
      const { gen, data: data2, schemaCode, it: it2 } = cxt;
      const prec = it2.opts.multipleOfPrecision;
      const res = gen.let("res");
      const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
      cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data2}/${schemaCode}, ${invalid}))`);
    }
  };
  multipleOf.default = def;
  return multipleOf;
}
var limitLength = {};
var ucs2length = {};
var hasRequiredUcs2length;
function requireUcs2length() {
  if (hasRequiredUcs2length) return ucs2length;
  hasRequiredUcs2length = 1;
  Object.defineProperty(ucs2length, "__esModule", { value: true });
  function ucs2length$12(str) {
    const len = str.length;
    let length = 0;
    let pos = 0;
    let 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;
  }
  ucs2length.default = ucs2length$12;
  ucs2length$12.code = 'require("ajv/dist/runtime/ucs2length").default';
  return ucs2length;
}
var hasRequiredLimitLength;
function requireLimitLength() {
  if (hasRequiredLimitLength) return limitLength;
  hasRequiredLimitLength = 1;
  Object.defineProperty(limitLength, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const ucs2length_1 = /* @__PURE__ */ requireUcs2length();
  const error = {
    message({ keyword: keyword2, schemaCode }) {
      const comp = keyword2 === "maxLength" ? "more" : "fewer";
      return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
    },
    params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
  };
  const def = {
    keyword: ["maxLength", "minLength"],
    type: "string",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
      const { keyword: keyword2, data: data2, schemaCode, it: it2 } = cxt;
      const op2 = keyword2 === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
      const len = it2.opts.unicode === false ? (0, codegen_1._)`${data2}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data2})`;
      cxt.fail$data((0, codegen_1._)`${len} ${op2} ${schemaCode}`);
    }
  };
  limitLength.default = def;
  return limitLength;
}
var pattern = {};
var hasRequiredPattern;
function requirePattern() {
  if (hasRequiredPattern) return pattern;
  hasRequiredPattern = 1;
  Object.defineProperty(pattern, "__esModule", { value: true });
  const code_1 = /* @__PURE__ */ requireCode();
  const util_1 = /* @__PURE__ */ requireUtil();
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const error = {
    message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
    params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`
  };
  const def = {
    keyword: "pattern",
    type: "string",
    schemaType: "string",
    $data: true,
    error,
    code(cxt) {
      const { gen, data: data2, $data, schema, schemaCode, it: it2 } = cxt;
      const u2 = it2.opts.unicodeRegExp ? "u" : "";
      if ($data) {
        const { regExp } = it2.opts.code;
        const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp);
        const valid = gen.let("valid");
        gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u2}).test(${data2})`), () => gen.assign(valid, false));
        cxt.fail$data((0, codegen_1._)`!${valid}`);
      } else {
        const regExp = (0, code_1.usePattern)(cxt, schema);
        cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data2})`);
      }
    }
  };
  pattern.default = def;
  return pattern;
}
var limitProperties = {};
var hasRequiredLimitProperties;
function requireLimitProperties() {
  if (hasRequiredLimitProperties) return limitProperties;
  hasRequiredLimitProperties = 1;
  Object.defineProperty(limitProperties, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const error = {
    message({ keyword: keyword2, schemaCode }) {
      const comp = keyword2 === "maxProperties" ? "more" : "fewer";
      return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;
    },
    params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
  };
  const def = {
    keyword: ["maxProperties", "minProperties"],
    type: "object",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
      const { keyword: keyword2, data: data2, schemaCode } = cxt;
      const op2 = keyword2 === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
      cxt.fail$data((0, codegen_1._)`Object.keys(${data2}).length ${op2} ${schemaCode}`);
    }
  };
  limitProperties.default = def;
  return limitProperties;
}
var required = {};
var hasRequiredRequired;
function requireRequired() {
  if (hasRequiredRequired) return required;
  hasRequiredRequired = 1;
  Object.defineProperty(required, "__esModule", { value: true });
  const code_1 = /* @__PURE__ */ requireCode();
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const error = {
    message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,
    params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`
  };
  const def = {
    keyword: "required",
    type: "object",
    schemaType: "array",
    $data: true,
    error,
    code(cxt) {
      const { gen, schema, schemaCode, data: data2, $data, it: it2 } = cxt;
      const { opts } = it2;
      if (!$data && schema.length === 0)
        return;
      const useLoop = schema.length >= opts.loopRequired;
      if (it2.allErrors)
        allErrorsMode();
      else
        exitOnErrorMode();
      if (opts.strictRequired) {
        const props = cxt.parentSchema.properties;
        const { definedProperties } = cxt.it;
        for (const requiredKey of schema) {
          if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
            const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath;
            const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
            (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictRequired);
          }
        }
      }
      function allErrorsMode() {
        if (useLoop || $data) {
          cxt.block$data(codegen_1.nil, loopAllRequired);
        } else {
          for (const prop of schema) {
            (0, code_1.checkReportMissingProp)(cxt, prop);
          }
        }
      }
      function exitOnErrorMode() {
        const missing = gen.let("missing");
        if (useLoop || $data) {
          const valid = gen.let("valid", true);
          cxt.block$data(valid, () => loopUntilMissing(missing, valid));
          cxt.ok(valid);
        } else {
          gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
          (0, code_1.reportMissingProp)(cxt, missing);
          gen.else();
        }
      }
      function loopAllRequired() {
        gen.forOf("prop", schemaCode, (prop) => {
          cxt.setParams({ missingProperty: prop });
          gen.if((0, code_1.noPropertyInData)(gen, data2, prop, opts.ownProperties), () => cxt.error());
        });
      }
      function loopUntilMissing(missing, valid) {
        cxt.setParams({ missingProperty: missing });
        gen.forOf(missing, schemaCode, () => {
          gen.assign(valid, (0, code_1.propertyInData)(gen, data2, missing, opts.ownProperties));
          gen.if((0, codegen_1.not)(valid), () => {
            cxt.error();
            gen.break();
          });
        }, codegen_1.nil);
      }
    }
  };
  required.default = def;
  return required;
}
var limitItems = {};
var hasRequiredLimitItems;
function requireLimitItems() {
  if (hasRequiredLimitItems) return limitItems;
  hasRequiredLimitItems = 1;
  Object.defineProperty(limitItems, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const error = {
    message({ keyword: keyword2, schemaCode }) {
      const comp = keyword2 === "maxItems" ? "more" : "fewer";
      return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;
    },
    params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
  };
  const def = {
    keyword: ["maxItems", "minItems"],
    type: "array",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
      const { keyword: keyword2, data: data2, schemaCode } = cxt;
      const op2 = keyword2 === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
      cxt.fail$data((0, codegen_1._)`${data2}.length ${op2} ${schemaCode}`);
    }
  };
  limitItems.default = def;
  return limitItems;
}
var uniqueItems = {};
var equal = {};
var hasRequiredEqual;
function requireEqual() {
  if (hasRequiredEqual) return equal;
  hasRequiredEqual = 1;
  Object.defineProperty(equal, "__esModule", { value: true });
  const equal$12 = requireFastDeepEqual();
  equal$12.code = 'require("ajv/dist/runtime/equal").default';
  equal.default = equal$12;
  return equal;
}
var hasRequiredUniqueItems;
function requireUniqueItems() {
  if (hasRequiredUniqueItems) return uniqueItems;
  hasRequiredUniqueItems = 1;
  Object.defineProperty(uniqueItems, "__esModule", { value: true });
  const dataType_1 = /* @__PURE__ */ requireDataType();
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const equal_1 = /* @__PURE__ */ requireEqual();
  const error = {
    message: ({ params: { i: i2, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i2} are identical)`,
    params: ({ params: { i: i2, j } }) => (0, codegen_1._)`{i: ${i2}, j: ${j}}`
  };
  const def = {
    keyword: "uniqueItems",
    type: "array",
    schemaType: "boolean",
    $data: true,
    error,
    code(cxt) {
      const { gen, data: data2, $data, schema, parentSchema, schemaCode, it: it2 } = cxt;
      if (!$data && !schema)
        return;
      const valid = gen.let("valid");
      const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
      cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);
      cxt.ok(valid);
      function validateUniqueItems() {
        const i2 = gen.let("i", (0, codegen_1._)`${data2}.length`);
        const j = gen.let("j");
        cxt.setParams({ i: i2, j });
        gen.assign(valid, true);
        gen.if((0, codegen_1._)`${i2} > 1`, () => (canOptimize() ? loopN : loopN2)(i2, j));
      }
      function canOptimize() {
        return itemTypes.length > 0 && !itemTypes.some((t2) => t2 === "object" || t2 === "array");
      }
      function loopN(i2, j) {
        const item = gen.name("item");
        const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it2.opts.strictNumbers, dataType_1.DataType.Wrong);
        const indices = gen.const("indices", (0, codegen_1._)`{}`);
        gen.for((0, codegen_1._)`;${i2}--;`, () => {
          gen.let(item, (0, codegen_1._)`${data2}[${i2}]`);
          gen.if(wrongType, (0, codegen_1._)`continue`);
          if (itemTypes.length > 1)
            gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`);
          gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => {
            gen.assign(j, (0, codegen_1._)`${indices}[${item}]`);
            cxt.error();
            gen.assign(valid, false).break();
          }).code((0, codegen_1._)`${indices}[${item}] = ${i2}`);
        });
      }
      function loopN2(i2, j) {
        const eql = (0, util_1.useFunc)(gen, equal_1.default);
        const outer = gen.name("outer");
        gen.label(outer).for((0, codegen_1._)`;${i2}--;`, () => gen.for((0, codegen_1._)`${j} = ${i2}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data2}[${i2}], ${data2}[${j}])`, () => {
          cxt.error();
          gen.assign(valid, false).break(outer);
        })));
      }
    }
  };
  uniqueItems.default = def;
  return uniqueItems;
}
var _const = {};
var hasRequired_const;
function require_const() {
  if (hasRequired_const) return _const;
  hasRequired_const = 1;
  Object.defineProperty(_const, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const equal_1 = /* @__PURE__ */ requireEqual();
  const error = {
    message: "must be equal to constant",
    params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
  };
  const def = {
    keyword: "const",
    $data: true,
    error,
    code(cxt) {
      const { gen, data: data2, $data, schemaCode, schema } = cxt;
      if ($data || schema && typeof schema == "object") {
        cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data2}, ${schemaCode})`);
      } else {
        cxt.fail((0, codegen_1._)`${schema} !== ${data2}`);
      }
    }
  };
  _const.default = def;
  return _const;
}
var _enum = {};
var hasRequired_enum;
function require_enum() {
  if (hasRequired_enum) return _enum;
  hasRequired_enum = 1;
  Object.defineProperty(_enum, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const equal_1 = /* @__PURE__ */ requireEqual();
  const error = {
    message: "must be equal to one of the allowed values",
    params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`
  };
  const def = {
    keyword: "enum",
    schemaType: "array",
    $data: true,
    error,
    code(cxt) {
      const { gen, data: data2, $data, schema, schemaCode, it: it2 } = cxt;
      if (!$data && schema.length === 0)
        throw new Error("enum must have non-empty array");
      const useLoop = schema.length >= it2.opts.loopEnum;
      let eql;
      const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default);
      let valid;
      if (useLoop || $data) {
        valid = gen.let("valid");
        cxt.block$data(valid, loopEnum);
      } else {
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        const vSchema = gen.const("vSchema", schemaCode);
        valid = (0, codegen_1.or)(...schema.map((_x, i2) => equalCode(vSchema, i2)));
      }
      cxt.pass(valid);
      function loopEnum() {
        gen.assign(valid, false);
        gen.forOf("v", schemaCode, (v2) => gen.if((0, codegen_1._)`${getEql()}(${data2}, ${v2})`, () => gen.assign(valid, true).break()));
      }
      function equalCode(vSchema, i2) {
        const sch = schema[i2];
        return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data2}, ${vSchema}[${i2}])` : (0, codegen_1._)`${data2} === ${sch}`;
      }
    }
  };
  _enum.default = def;
  return _enum;
}
var hasRequiredValidation;
function requireValidation() {
  if (hasRequiredValidation) return validation;
  hasRequiredValidation = 1;
  Object.defineProperty(validation, "__esModule", { value: true });
  const limitNumber_1 = /* @__PURE__ */ requireLimitNumber();
  const multipleOf_1 = /* @__PURE__ */ requireMultipleOf();
  const limitLength_1 = /* @__PURE__ */ requireLimitLength();
  const pattern_1 = /* @__PURE__ */ requirePattern();
  const limitProperties_1 = /* @__PURE__ */ requireLimitProperties();
  const required_1 = /* @__PURE__ */ requireRequired();
  const limitItems_1 = /* @__PURE__ */ requireLimitItems();
  const uniqueItems_1 = /* @__PURE__ */ requireUniqueItems();
  const const_1 = /* @__PURE__ */ require_const();
  const enum_1 = /* @__PURE__ */ require_enum();
  const validation$12 = [
    // number
    limitNumber_1.default,
    multipleOf_1.default,
    // string
    limitLength_1.default,
    pattern_1.default,
    // object
    limitProperties_1.default,
    required_1.default,
    // array
    limitItems_1.default,
    uniqueItems_1.default,
    // any
    { keyword: "type", schemaType: ["string", "array"] },
    { keyword: "nullable", schemaType: "boolean" },
    const_1.default,
    enum_1.default
  ];
  validation.default = validation$12;
  return validation;
}
var applicator = {};
var additionalItems = {};
var hasRequiredAdditionalItems;
function requireAdditionalItems() {
  if (hasRequiredAdditionalItems) return additionalItems;
  hasRequiredAdditionalItems = 1;
  Object.defineProperty(additionalItems, "__esModule", { value: true });
  additionalItems.validateAdditionalItems = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const error = {
    message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
  };
  const def = {
    keyword: "additionalItems",
    type: "array",
    schemaType: ["boolean", "object"],
    before: "uniqueItems",
    error,
    code(cxt) {
      const { parentSchema, it: it2 } = cxt;
      const { items: items2 } = parentSchema;
      if (!Array.isArray(items2)) {
        (0, util_1.checkStrictMode)(it2, '"additionalItems" is ignored when "items" is not an array of schemas');
        return;
      }
      validateAdditionalItems(cxt, items2);
    }
  };
  function validateAdditionalItems(cxt, items2) {
    const { gen, schema, data: data2, keyword: keyword2, it: it2 } = cxt;
    it2.items = true;
    const len = gen.const("len", (0, codegen_1._)`${data2}.length`);
    if (schema === false) {
      cxt.setParams({ len: items2.length });
      cxt.pass((0, codegen_1._)`${len} <= ${items2.length}`);
    } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it2, schema)) {
      const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items2.length}`);
      gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
      cxt.ok(valid);
    }
    function validateItems(valid) {
      gen.forRange("i", items2.length, len, (i2) => {
        cxt.subschema({ keyword: keyword2, dataProp: i2, dataPropType: util_1.Type.Num }, valid);
        if (!it2.allErrors)
          gen.if((0, codegen_1.not)(valid), () => gen.break());
      });
    }
  }
  additionalItems.validateAdditionalItems = validateAdditionalItems;
  additionalItems.default = def;
  return additionalItems;
}
var prefixItems = {};
var items = {};
var hasRequiredItems;
function requireItems() {
  if (hasRequiredItems) return items;
  hasRequiredItems = 1;
  Object.defineProperty(items, "__esModule", { value: true });
  items.validateTuple = void 0;
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const code_1 = /* @__PURE__ */ requireCode();
  const def = {
    keyword: "items",
    type: "array",
    schemaType: ["object", "array", "boolean"],
    before: "uniqueItems",
    code(cxt) {
      const { schema, it: it2 } = cxt;
      if (Array.isArray(schema))
        return validateTuple(cxt, "additionalItems", schema);
      it2.items = true;
      if ((0, util_1.alwaysValidSchema)(it2, schema))
        return;
      cxt.ok((0, code_1.validateArray)(cxt));
    }
  };
  function validateTuple(cxt, extraItems, schArr = cxt.schema) {
    const { gen, parentSchema, data: data2, keyword: keyword2, it: it2 } = cxt;
    checkStrictTuple(parentSchema);
    if (it2.opts.unevaluated && schArr.length && it2.items !== true) {
      it2.items = util_1.mergeEvaluated.items(gen, schArr.length, it2.items);
    }
    const valid = gen.name("valid");
    const len = gen.const("len", (0, codegen_1._)`${data2}.length`);
    schArr.forEach((sch, i2) => {
      if ((0, util_1.alwaysValidSchema)(it2, sch))
        return;
      gen.if((0, codegen_1._)`${len} > ${i2}`, () => cxt.subschema({
        keyword: keyword2,
        schemaProp: i2,
        dataProp: i2
      }, valid));
      cxt.ok(valid);
    });
    function checkStrictTuple(sch) {
      const { opts, errSchemaPath } = it2;
      const l2 = schArr.length;
      const fullTuple = l2 === sch.minItems && (l2 === sch.maxItems || sch[extraItems] === false);
      if (opts.strictTuples && !fullTuple) {
        const msg = `"${keyword2}" is ${l2}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
        (0, util_1.checkStrictMode)(it2, msg, opts.strictTuples);
      }
    }
  }
  items.validateTuple = validateTuple;
  items.default = def;
  return items;
}
var hasRequiredPrefixItems;
function requirePrefixItems() {
  if (hasRequiredPrefixItems) return prefixItems;
  hasRequiredPrefixItems = 1;
  Object.defineProperty(prefixItems, "__esModule", { value: true });
  const items_1 = /* @__PURE__ */ requireItems();
  const def = {
    keyword: "prefixItems",
    type: "array",
    schemaType: ["array"],
    before: "uniqueItems",
    code: (cxt) => (0, items_1.validateTuple)(cxt, "items")
  };
  prefixItems.default = def;
  return prefixItems;
}
var items2020 = {};
var hasRequiredItems2020;
function requireItems2020() {
  if (hasRequiredItems2020) return items2020;
  hasRequiredItems2020 = 1;
  Object.defineProperty(items2020, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const code_1 = /* @__PURE__ */ requireCode();
  const additionalItems_1 = /* @__PURE__ */ requireAdditionalItems();
  const error = {
    message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
  };
  const def = {
    keyword: "items",
    type: "array",
    schemaType: ["object", "boolean"],
    before: "uniqueItems",
    error,
    code(cxt) {
      const { schema, parentSchema, it: it2 } = cxt;
      const { prefixItems: prefixItems2 } = parentSchema;
      it2.items = true;
      if ((0, util_1.alwaysValidSchema)(it2, schema))
        return;
      if (prefixItems2)
        (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems2);
      else
        cxt.ok((0, code_1.validateArray)(cxt));
    }
  };
  items2020.default = def;
  return items2020;
}
var contains = {};
var hasRequiredContains;
function requireContains() {
  if (hasRequiredContains) return contains;
  hasRequiredContains = 1;
  Object.defineProperty(contains, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const error = {
    message: ({ params: { min: min2, max: max2 } }) => max2 === void 0 ? (0, codegen_1.str)`must contain at least ${min2} valid item(s)` : (0, codegen_1.str)`must contain at least ${min2} and no more than ${max2} valid item(s)`,
    params: ({ params: { min: min2, max: max2 } }) => max2 === void 0 ? (0, codegen_1._)`{minContains: ${min2}}` : (0, codegen_1._)`{minContains: ${min2}, maxContains: ${max2}}`
  };
  const def = {
    keyword: "contains",
    type: "array",
    schemaType: ["object", "boolean"],
    before: "uniqueItems",
    trackErrors: true,
    error,
    code(cxt) {
      const { gen, schema, parentSchema, data: data2, it: it2 } = cxt;
      let min2;
      let max2;
      const { minContains, maxContains } = parentSchema;
      if (it2.opts.next) {
        min2 = minContains === void 0 ? 1 : minContains;
        max2 = maxContains;
      } else {
        min2 = 1;
      }
      const len = gen.const("len", (0, codegen_1._)`${data2}.length`);
      cxt.setParams({ min: min2, max: max2 });
      if (max2 === void 0 && min2 === 0) {
        (0, util_1.checkStrictMode)(it2, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
        return;
      }
      if (max2 !== void 0 && min2 > max2) {
        (0, util_1.checkStrictMode)(it2, `"minContains" > "maxContains" is always invalid`);
        cxt.fail();
        return;
      }
      if ((0, util_1.alwaysValidSchema)(it2, schema)) {
        let cond = (0, codegen_1._)`${len} >= ${min2}`;
        if (max2 !== void 0)
          cond = (0, codegen_1._)`${cond} && ${len} <= ${max2}`;
        cxt.pass(cond);
        return;
      }
      it2.items = true;
      const valid = gen.name("valid");
      if (max2 === void 0 && min2 === 1) {
        validateItems(valid, () => gen.if(valid, () => gen.break()));
      } else if (min2 === 0) {
        gen.let(valid, true);
        if (max2 !== void 0)
          gen.if((0, codegen_1._)`${data2}.length > 0`, validateItemsWithCount);
      } else {
        gen.let(valid, false);
        validateItemsWithCount();
      }
      cxt.result(valid, () => cxt.reset());
      function validateItemsWithCount() {
        const schValid = gen.name("_valid");
        const count2 = gen.let("count", 0);
        validateItems(schValid, () => gen.if(schValid, () => checkLimits(count2)));
      }
      function validateItems(_valid, block) {
        gen.forRange("i", 0, len, (i2) => {
          cxt.subschema({
            keyword: "contains",
            dataProp: i2,
            dataPropType: util_1.Type.Num,
            compositeRule: true
          }, _valid);
          block();
        });
      }
      function checkLimits(count2) {
        gen.code((0, codegen_1._)`${count2}++`);
        if (max2 === void 0) {
          gen.if((0, codegen_1._)`${count2} >= ${min2}`, () => gen.assign(valid, true).break());
        } else {
          gen.if((0, codegen_1._)`${count2} > ${max2}`, () => gen.assign(valid, false).break());
          if (min2 === 1)
            gen.assign(valid, true);
          else
            gen.if((0, codegen_1._)`${count2} >= ${min2}`, () => gen.assign(valid, true));
        }
      }
    }
  };
  contains.default = def;
  return contains;
}
var dependencies = {};
var hasRequiredDependencies;
function requireDependencies() {
  if (hasRequiredDependencies) return dependencies;
  hasRequiredDependencies = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
    const codegen_1 = /* @__PURE__ */ requireCodegen();
    const util_1 = /* @__PURE__ */ requireUtil();
    const code_1 = /* @__PURE__ */ requireCode();
    exports.error = {
      message: ({ params: { property, depsCount, deps } }) => {
        const property_ies = depsCount === 1 ? "property" : "properties";
        return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;
      },
      params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`
      // TODO change to reference
    };
    const def = {
      keyword: "dependencies",
      type: "object",
      schemaType: "object",
      error: exports.error,
      code(cxt) {
        const [propDeps, schDeps] = splitDependencies(cxt);
        validatePropertyDeps(cxt, propDeps);
        validateSchemaDeps(cxt, schDeps);
      }
    };
    function splitDependencies({ schema }) {
      const propertyDeps = {};
      const schemaDeps = {};
      for (const key in schema) {
        if (key === "__proto__")
          continue;
        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
        deps[key] = schema[key];
      }
      return [propertyDeps, schemaDeps];
    }
    function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
      const { gen, data: data2, it: it2 } = cxt;
      if (Object.keys(propertyDeps).length === 0)
        return;
      const missing = gen.let("missing");
      for (const prop in propertyDeps) {
        const deps = propertyDeps[prop];
        if (deps.length === 0)
          continue;
        const hasProperty = (0, code_1.propertyInData)(gen, data2, prop, it2.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it2.allErrors) {
          gen.if(hasProperty, () => {
            for (const depProp of deps) {
              (0, code_1.checkReportMissingProp)(cxt, depProp);
            }
          });
        } else {
          gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
          (0, code_1.reportMissingProp)(cxt, missing);
          gen.else();
        }
      }
    }
    exports.validatePropertyDeps = validatePropertyDeps;
    function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
      const { gen, data: data2, keyword: keyword2, it: it2 } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it2, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data2, prop, it2.opts.ownProperties),
          () => {
            const schCxt = cxt.subschema({ keyword: keyword2, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
          },
          () => gen.var(valid, true)
          // TODO var
        );
        cxt.ok(valid);
      }
    }
    exports.validateSchemaDeps = validateSchemaDeps;
    exports.default = def;
  })(dependencies);
  return dependencies;
}
var propertyNames = {};
var hasRequiredPropertyNames;
function requirePropertyNames() {
  if (hasRequiredPropertyNames) return propertyNames;
  hasRequiredPropertyNames = 1;
  Object.defineProperty(propertyNames, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const error = {
    message: "property name must be valid",
    params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
  };
  const def = {
    keyword: "propertyNames",
    type: "object",
    schemaType: ["object", "boolean"],
    error,
    code(cxt) {
      const { gen, schema, data: data2, it: it2 } = cxt;
      if ((0, util_1.alwaysValidSchema)(it2, schema))
        return;
      const valid = gen.name("valid");
      gen.forIn("key", data2, (key) => {
        cxt.setParams({ propertyName: key });
        cxt.subschema({
          keyword: "propertyNames",
          data: key,
          dataTypes: ["string"],
          propertyName: key,
          compositeRule: true
        }, valid);
        gen.if((0, codegen_1.not)(valid), () => {
          cxt.error(true);
          if (!it2.allErrors)
            gen.break();
        });
      });
      cxt.ok(valid);
    }
  };
  propertyNames.default = def;
  return propertyNames;
}
var additionalProperties = {};
var hasRequiredAdditionalProperties;
function requireAdditionalProperties() {
  if (hasRequiredAdditionalProperties) return additionalProperties;
  hasRequiredAdditionalProperties = 1;
  Object.defineProperty(additionalProperties, "__esModule", { value: true });
  const code_1 = /* @__PURE__ */ requireCode();
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const names_1 = /* @__PURE__ */ requireNames();
  const util_1 = /* @__PURE__ */ requireUtil();
  const error = {
    message: "must NOT have additional properties",
    params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`
  };
  const def = {
    keyword: "additionalProperties",
    type: ["object"],
    schemaType: ["boolean", "object"],
    allowUndefined: true,
    trackErrors: true,
    error,
    code(cxt) {
      const { gen, schema, parentSchema, data: data2, errsCount, it: it2 } = cxt;
      if (!errsCount)
        throw new Error("ajv implementation error");
      const { allErrors, opts } = it2;
      it2.props = true;
      if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it2, schema))
        return;
      const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
      const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
      checkAdditionalProperties();
      cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
      function checkAdditionalProperties() {
        gen.forIn("key", data2, (key) => {
          if (!props.length && !patProps.length)
            additionalPropertyCode(key);
          else
            gen.if(isAdditional(key), () => additionalPropertyCode(key));
        });
      }
      function isAdditional(key) {
        let definedProp;
        if (props.length > 8) {
          const propsSchema = (0, util_1.schemaRefOrVal)(it2, parentSchema.properties, "properties");
          definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
        } else if (props.length) {
          definedProp = (0, codegen_1.or)(...props.map((p2) => (0, codegen_1._)`${key} === ${p2}`));
        } else {
          definedProp = codegen_1.nil;
        }
        if (patProps.length) {
          definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p2) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p2)}.test(${key})`));
        }
        return (0, codegen_1.not)(definedProp);
      }
      function deleteAdditional(key) {
        gen.code((0, codegen_1._)`delete ${data2}[${key}]`);
      }
      function additionalPropertyCode(key) {
        if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
          deleteAdditional(key);
          return;
        }
        if (schema === false) {
          cxt.setParams({ additionalProperty: key });
          cxt.error();
          if (!allErrors)
            gen.break();
          return;
        }
        if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it2, schema)) {
          const valid = gen.name("valid");
          if (opts.removeAdditional === "failing") {
            applyAdditionalSchema(key, valid, false);
            gen.if((0, codegen_1.not)(valid), () => {
              cxt.reset();
              deleteAdditional(key);
            });
          } else {
            applyAdditionalSchema(key, valid);
            if (!allErrors)
              gen.if((0, codegen_1.not)(valid), () => gen.break());
          }
        }
      }
      function applyAdditionalSchema(key, valid, errors2) {
        const subschema2 = {
          keyword: "additionalProperties",
          dataProp: key,
          dataPropType: util_1.Type.Str
        };
        if (errors2 === false) {
          Object.assign(subschema2, {
            compositeRule: true,
            createErrors: false,
            allErrors: false
          });
        }
        cxt.subschema(subschema2, valid);
      }
    }
  };
  additionalProperties.default = def;
  return additionalProperties;
}
var properties$1 = {};
var hasRequiredProperties;
function requireProperties() {
  if (hasRequiredProperties) return properties$1;
  hasRequiredProperties = 1;
  Object.defineProperty(properties$1, "__esModule", { value: true });
  const validate_1 = /* @__PURE__ */ requireValidate();
  const code_1 = /* @__PURE__ */ requireCode();
  const util_1 = /* @__PURE__ */ requireUtil();
  const additionalProperties_1 = /* @__PURE__ */ requireAdditionalProperties();
  const def = {
    keyword: "properties",
    type: "object",
    schemaType: "object",
    code(cxt) {
      const { gen, schema, parentSchema, data: data2, it: it2 } = cxt;
      if (it2.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
        additionalProperties_1.default.code(new validate_1.KeywordCxt(it2, additionalProperties_1.default, "additionalProperties"));
      }
      const allProps = (0, code_1.allSchemaProperties)(schema);
      for (const prop of allProps) {
        it2.definedProperties.add(prop);
      }
      if (it2.opts.unevaluated && allProps.length && it2.props !== true) {
        it2.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it2.props);
      }
      const properties2 = allProps.filter((p2) => !(0, util_1.alwaysValidSchema)(it2, schema[p2]));
      if (properties2.length === 0)
        return;
      const valid = gen.name("valid");
      for (const prop of properties2) {
        if (hasDefault(prop)) {
          applyPropertySchema(prop);
        } else {
          gen.if((0, code_1.propertyInData)(gen, data2, prop, it2.opts.ownProperties));
          applyPropertySchema(prop);
          if (!it2.allErrors)
            gen.else().var(valid, true);
          gen.endIf();
        }
        cxt.it.definedProperties.add(prop);
        cxt.ok(valid);
      }
      function hasDefault(prop) {
        return it2.opts.useDefaults && !it2.compositeRule && schema[prop].default !== void 0;
      }
      function applyPropertySchema(prop) {
        cxt.subschema({
          keyword: "properties",
          schemaProp: prop,
          dataProp: prop
        }, valid);
      }
    }
  };
  properties$1.default = def;
  return properties$1;
}
var patternProperties = {};
var hasRequiredPatternProperties;
function requirePatternProperties() {
  if (hasRequiredPatternProperties) return patternProperties;
  hasRequiredPatternProperties = 1;
  Object.defineProperty(patternProperties, "__esModule", { value: true });
  const code_1 = /* @__PURE__ */ requireCode();
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const util_2 = /* @__PURE__ */ requireUtil();
  const def = {
    keyword: "patternProperties",
    type: "object",
    schemaType: "object",
    code(cxt) {
      const { gen, schema, data: data2, parentSchema, it: it2 } = cxt;
      const { opts } = it2;
      const patterns = (0, code_1.allSchemaProperties)(schema);
      const alwaysValidPatterns = patterns.filter((p2) => (0, util_1.alwaysValidSchema)(it2, schema[p2]));
      if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it2.opts.unevaluated || it2.props === true)) {
        return;
      }
      const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
      const valid = gen.name("valid");
      if (it2.props !== true && !(it2.props instanceof codegen_1.Name)) {
        it2.props = (0, util_2.evaluatedPropsToName)(gen, it2.props);
      }
      const { props } = it2;
      validatePatternProperties();
      function validatePatternProperties() {
        for (const pat of patterns) {
          if (checkProperties)
            checkMatchingProperties(pat);
          if (it2.allErrors) {
            validateProperties(pat);
          } else {
            gen.var(valid, true);
            validateProperties(pat);
            gen.if(valid);
          }
        }
      }
      function checkMatchingProperties(pat) {
        for (const prop in checkProperties) {
          if (new RegExp(pat).test(prop)) {
            (0, util_1.checkStrictMode)(it2, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
          }
        }
      }
      function validateProperties(pat) {
        gen.forIn("key", data2, (key) => {
          gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
            const alwaysValid = alwaysValidPatterns.includes(pat);
            if (!alwaysValid) {
              cxt.subschema({
                keyword: "patternProperties",
                schemaProp: pat,
                dataProp: key,
                dataPropType: util_2.Type.Str
              }, valid);
            }
            if (it2.opts.unevaluated && props !== true) {
              gen.assign((0, codegen_1._)`${props}[${key}]`, true);
            } else if (!alwaysValid && !it2.allErrors) {
              gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
          });
        });
      }
    }
  };
  patternProperties.default = def;
  return patternProperties;
}
var not = {};
var hasRequiredNot;
function requireNot() {
  if (hasRequiredNot) return not;
  hasRequiredNot = 1;
  Object.defineProperty(not, "__esModule", { value: true });
  const util_1 = /* @__PURE__ */ requireUtil();
  const def = {
    keyword: "not",
    schemaType: ["object", "boolean"],
    trackErrors: true,
    code(cxt) {
      const { gen, schema, it: it2 } = cxt;
      if ((0, util_1.alwaysValidSchema)(it2, schema)) {
        cxt.fail();
        return;
      }
      const valid = gen.name("valid");
      cxt.subschema({
        keyword: "not",
        compositeRule: true,
        createErrors: false,
        allErrors: false
      }, valid);
      cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
    },
    error: { message: "must NOT be valid" }
  };
  not.default = def;
  return not;
}
var anyOf = {};
var hasRequiredAnyOf;
function requireAnyOf() {
  if (hasRequiredAnyOf) return anyOf;
  hasRequiredAnyOf = 1;
  Object.defineProperty(anyOf, "__esModule", { value: true });
  const code_1 = /* @__PURE__ */ requireCode();
  const def = {
    keyword: "anyOf",
    schemaType: "array",
    trackErrors: true,
    code: code_1.validateUnion,
    error: { message: "must match a schema in anyOf" }
  };
  anyOf.default = def;
  return anyOf;
}
var oneOf = {};
var hasRequiredOneOf;
function requireOneOf() {
  if (hasRequiredOneOf) return oneOf;
  hasRequiredOneOf = 1;
  Object.defineProperty(oneOf, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const error = {
    message: "must match exactly one schema in oneOf",
    params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`
  };
  const def = {
    keyword: "oneOf",
    schemaType: "array",
    trackErrors: true,
    error,
    code(cxt) {
      const { gen, schema, parentSchema, it: it2 } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      if (it2.opts.discriminator && parentSchema.discriminator)
        return;
      const schArr = schema;
      const valid = gen.let("valid", false);
      const passing = gen.let("passing", null);
      const schValid = gen.name("_valid");
      cxt.setParams({ passing });
      gen.block(validateOneOf);
      cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
      function validateOneOf() {
        schArr.forEach((sch, i2) => {
          let schCxt;
          if ((0, util_1.alwaysValidSchema)(it2, sch)) {
            gen.var(schValid, true);
          } else {
            schCxt = cxt.subschema({
              keyword: "oneOf",
              schemaProp: i2,
              compositeRule: true
            }, schValid);
          }
          if (i2 > 0) {
            gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i2}]`).else();
          }
          gen.if(schValid, () => {
            gen.assign(valid, true);
            gen.assign(passing, i2);
            if (schCxt)
              cxt.mergeEvaluated(schCxt, codegen_1.Name);
          });
        });
      }
    }
  };
  oneOf.default = def;
  return oneOf;
}
var allOf = {};
var hasRequiredAllOf;
function requireAllOf() {
  if (hasRequiredAllOf) return allOf;
  hasRequiredAllOf = 1;
  Object.defineProperty(allOf, "__esModule", { value: true });
  const util_1 = /* @__PURE__ */ requireUtil();
  const def = {
    keyword: "allOf",
    schemaType: "array",
    code(cxt) {
      const { gen, schema, it: it2 } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const valid = gen.name("valid");
      schema.forEach((sch, i2) => {
        if ((0, util_1.alwaysValidSchema)(it2, sch))
          return;
        const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i2 }, valid);
        cxt.ok(valid);
        cxt.mergeEvaluated(schCxt);
      });
    }
  };
  allOf.default = def;
  return allOf;
}
var _if = {};
var hasRequired_if;
function require_if() {
  if (hasRequired_if) return _if;
  hasRequired_if = 1;
  Object.defineProperty(_if, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const util_1 = /* @__PURE__ */ requireUtil();
  const error = {
    message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,
    params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`
  };
  const def = {
    keyword: "if",
    schemaType: ["object", "boolean"],
    trackErrors: true,
    error,
    code(cxt) {
      const { gen, parentSchema, it: it2 } = cxt;
      if (parentSchema.then === void 0 && parentSchema.else === void 0) {
        (0, util_1.checkStrictMode)(it2, '"if" without "then" and "else" is ignored');
      }
      const hasThen = hasSchema(it2, "then");
      const hasElse = hasSchema(it2, "else");
      if (!hasThen && !hasElse)
        return;
      const valid = gen.let("valid", true);
      const schValid = gen.name("_valid");
      validateIf();
      cxt.reset();
      if (hasThen && hasElse) {
        const ifClause = gen.let("ifClause");
        cxt.setParams({ ifClause });
        gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
      } else if (hasThen) {
        gen.if(schValid, validateClause("then"));
      } else {
        gen.if((0, codegen_1.not)(schValid), validateClause("else"));
      }
      cxt.pass(valid, () => cxt.error(true));
      function validateIf() {
        const schCxt = cxt.subschema({
          keyword: "if",
          compositeRule: true,
          createErrors: false,
          allErrors: false
        }, schValid);
        cxt.mergeEvaluated(schCxt);
      }
      function validateClause(keyword2, ifClause) {
        return () => {
          const schCxt = cxt.subschema({ keyword: keyword2 }, schValid);
          gen.assign(valid, schValid);
          cxt.mergeValidEvaluated(schCxt, valid);
          if (ifClause)
            gen.assign(ifClause, (0, codegen_1._)`${keyword2}`);
          else
            cxt.setParams({ ifClause: keyword2 });
        };
      }
    }
  };
  function hasSchema(it2, keyword2) {
    const schema = it2.schema[keyword2];
    return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it2, schema);
  }
  _if.default = def;
  return _if;
}
var thenElse = {};
var hasRequiredThenElse;
function requireThenElse() {
  if (hasRequiredThenElse) return thenElse;
  hasRequiredThenElse = 1;
  Object.defineProperty(thenElse, "__esModule", { value: true });
  const util_1 = /* @__PURE__ */ requireUtil();
  const def = {
    keyword: ["then", "else"],
    schemaType: ["object", "boolean"],
    code({ keyword: keyword2, parentSchema, it: it2 }) {
      if (parentSchema.if === void 0)
        (0, util_1.checkStrictMode)(it2, `"${keyword2}" without "if" is ignored`);
    }
  };
  thenElse.default = def;
  return thenElse;
}
var hasRequiredApplicator;
function requireApplicator() {
  if (hasRequiredApplicator) return applicator;
  hasRequiredApplicator = 1;
  Object.defineProperty(applicator, "__esModule", { value: true });
  const additionalItems_1 = /* @__PURE__ */ requireAdditionalItems();
  const prefixItems_1 = /* @__PURE__ */ requirePrefixItems();
  const items_1 = /* @__PURE__ */ requireItems();
  const items2020_1 = /* @__PURE__ */ requireItems2020();
  const contains_1 = /* @__PURE__ */ requireContains();
  const dependencies_1 = /* @__PURE__ */ requireDependencies();
  const propertyNames_1 = /* @__PURE__ */ requirePropertyNames();
  const additionalProperties_1 = /* @__PURE__ */ requireAdditionalProperties();
  const properties_1 = /* @__PURE__ */ requireProperties();
  const patternProperties_1 = /* @__PURE__ */ requirePatternProperties();
  const not_1 = /* @__PURE__ */ requireNot();
  const anyOf_1 = /* @__PURE__ */ requireAnyOf();
  const oneOf_1 = /* @__PURE__ */ requireOneOf();
  const allOf_1 = /* @__PURE__ */ requireAllOf();
  const if_1 = /* @__PURE__ */ require_if();
  const thenElse_1 = /* @__PURE__ */ requireThenElse();
  function getApplicator(draft2020 = false) {
    const applicator2 = [
      // any
      not_1.default,
      anyOf_1.default,
      oneOf_1.default,
      allOf_1.default,
      if_1.default,
      thenElse_1.default,
      // object
      propertyNames_1.default,
      additionalProperties_1.default,
      dependencies_1.default,
      properties_1.default,
      patternProperties_1.default
    ];
    if (draft2020)
      applicator2.push(prefixItems_1.default, items2020_1.default);
    else
      applicator2.push(additionalItems_1.default, items_1.default);
    applicator2.push(contains_1.default);
    return applicator2;
  }
  applicator.default = getApplicator;
  return applicator;
}
var format$1 = {};
var format = {};
var hasRequiredFormat$1;
function requireFormat$1() {
  if (hasRequiredFormat$1) return format;
  hasRequiredFormat$1 = 1;
  Object.defineProperty(format, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const error = {
    message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,
    params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`
  };
  const def = {
    keyword: "format",
    type: ["number", "string"],
    schemaType: "string",
    $data: true,
    error,
    code(cxt, ruleType) {
      const { gen, data: data2, $data, schema, schemaCode, it: it2 } = cxt;
      const { opts, errSchemaPath, schemaEnv, self: self2 } = it2;
      if (!opts.validateFormats)
        return;
      if ($data)
        validate$DataFormat();
      else
        validateFormat();
      function validate$DataFormat() {
        const fmts = gen.scopeValue("formats", {
          ref: self2.formats,
          code: opts.code.formats
        });
        const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
        const fType = gen.let("fType");
        const format2 = gen.let("format");
        gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format2, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format2, fDef));
        cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
        function unknownFmt() {
          if (opts.strictSchema === false)
            return codegen_1.nil;
          return (0, codegen_1._)`${schemaCode} && !${format2}`;
        }
        function invalidFmt() {
          const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format2}(${data2}) : ${format2}(${data2}))` : (0, codegen_1._)`${format2}(${data2})`;
          const validData = (0, codegen_1._)`(typeof ${format2} == "function" ? ${callFormat} : ${format2}.test(${data2}))`;
          return (0, codegen_1._)`${format2} && ${format2} !== true && ${fType} === ${ruleType} && !${validData}`;
        }
      }
      function validateFormat() {
        const formatDef = self2.formats[schema];
        if (!formatDef) {
          unknownFormat();
          return;
        }
        if (formatDef === true)
          return;
        const [fmtType, format2, fmtRef] = getFormat(formatDef);
        if (fmtType === ruleType)
          cxt.pass(validCondition());
        function unknownFormat() {
          if (opts.strictSchema === false) {
            self2.logger.warn(unknownMsg());
            return;
          }
          throw new Error(unknownMsg());
          function unknownMsg() {
            return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
          }
        }
        function getFormat(fmtDef) {
          const code2 = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0;
          const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code: code2 });
          if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
            return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`];
          }
          return ["string", fmtDef, fmt];
        }
        function validCondition() {
          if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
            if (!schemaEnv.$async)
              throw new Error("async format in sync schema");
            return (0, codegen_1._)`await ${fmtRef}(${data2})`;
          }
          return typeof format2 == "function" ? (0, codegen_1._)`${fmtRef}(${data2})` : (0, codegen_1._)`${fmtRef}.test(${data2})`;
        }
      }
    }
  };
  format.default = def;
  return format;
}
var hasRequiredFormat;
function requireFormat() {
  if (hasRequiredFormat) return format$1;
  hasRequiredFormat = 1;
  Object.defineProperty(format$1, "__esModule", { value: true });
  const format_1 = /* @__PURE__ */ requireFormat$1();
  const format2 = [format_1.default];
  format$1.default = format2;
  return format$1;
}
var metadata = {};
var hasRequiredMetadata;
function requireMetadata() {
  if (hasRequiredMetadata) return metadata;
  hasRequiredMetadata = 1;
  Object.defineProperty(metadata, "__esModule", { value: true });
  metadata.contentVocabulary = metadata.metadataVocabulary = void 0;
  metadata.metadataVocabulary = [
    "title",
    "description",
    "default",
    "deprecated",
    "readOnly",
    "writeOnly",
    "examples"
  ];
  metadata.contentVocabulary = [
    "contentMediaType",
    "contentEncoding",
    "contentSchema"
  ];
  return metadata;
}
var hasRequiredDraft7;
function requireDraft7() {
  if (hasRequiredDraft7) return draft7;
  hasRequiredDraft7 = 1;
  Object.defineProperty(draft7, "__esModule", { value: true });
  const core_1 = /* @__PURE__ */ requireCore();
  const validation_1 = /* @__PURE__ */ requireValidation();
  const applicator_1 = /* @__PURE__ */ requireApplicator();
  const format_1 = /* @__PURE__ */ requireFormat();
  const metadata_1 = /* @__PURE__ */ requireMetadata();
  const draft7Vocabularies = [
    core_1.default,
    validation_1.default,
    (0, applicator_1.default)(),
    format_1.default,
    metadata_1.metadataVocabulary,
    metadata_1.contentVocabulary
  ];
  draft7.default = draft7Vocabularies;
  return draft7;
}
var discriminator = {};
var types = {};
var hasRequiredTypes;
function requireTypes() {
  if (hasRequiredTypes) return types;
  hasRequiredTypes = 1;
  Object.defineProperty(types, "__esModule", { value: true });
  types.DiscrError = void 0;
  var DiscrError;
  (function(DiscrError2) {
    DiscrError2["Tag"] = "tag";
    DiscrError2["Mapping"] = "mapping";
  })(DiscrError || (types.DiscrError = DiscrError = {}));
  return types;
}
var hasRequiredDiscriminator;
function requireDiscriminator() {
  if (hasRequiredDiscriminator) return discriminator;
  hasRequiredDiscriminator = 1;
  Object.defineProperty(discriminator, "__esModule", { value: true });
  const codegen_1 = /* @__PURE__ */ requireCodegen();
  const types_1 = /* @__PURE__ */ requireTypes();
  const compile_12 = /* @__PURE__ */ requireCompile();
  const ref_error_1 = /* @__PURE__ */ requireRef_error();
  const util_1 = /* @__PURE__ */ requireUtil();
  const error = {
    message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,
    params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`
  };
  const def = {
    keyword: "discriminator",
    type: "object",
    schemaType: "object",
    error,
    code(cxt) {
      const { gen, data: data2, schema, parentSchema, it: it2 } = cxt;
      const { oneOf: oneOf2 } = parentSchema;
      if (!it2.opts.discriminator) {
        throw new Error("discriminator: requires discriminator option");
      }
      const tagName = schema.propertyName;
      if (typeof tagName != "string")
        throw new Error("discriminator: requires propertyName");
      if (schema.mapping)
        throw new Error("discriminator: mapping is not supported");
      if (!oneOf2)
        throw new Error("discriminator: requires oneOf keyword");
      const valid = gen.let("valid", false);
      const tag = gen.const("tag", (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(tagName)}`);
      gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
      cxt.ok(valid);
      function validateMapping() {
        const mapping = getMapping();
        gen.if(false);
        for (const tagValue in mapping) {
          gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);
          gen.assign(valid, applyTagSchema(mapping[tagValue]));
        }
        gen.else();
        cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
        gen.endIf();
      }
      function applyTagSchema(schemaProp) {
        const _valid = gen.name("valid");
        const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
        cxt.mergeEvaluated(schCxt, codegen_1.Name);
        return _valid;
      }
      function getMapping() {
        var _a2;
        const oneOfMapping = {};
        const topRequired = hasRequired(parentSchema);
        let tagRequired = true;
        for (let i2 = 0; i2 < oneOf2.length; i2++) {
          let sch = oneOf2[i2];
          if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it2.self.RULES)) {
            const ref2 = sch.$ref;
            sch = compile_12.resolveRef.call(it2.self, it2.schemaEnv.root, it2.baseId, ref2);
            if (sch instanceof compile_12.SchemaEnv)
              sch = sch.schema;
            if (sch === void 0)
              throw new ref_error_1.default(it2.opts.uriResolver, it2.baseId, ref2);
          }
          const propSch = (_a2 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a2 === void 0 ? void 0 : _a2[tagName];
          if (typeof propSch != "object") {
            throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
          }
          tagRequired = tagRequired && (topRequired || hasRequired(sch));
          addMappings(propSch, i2);
        }
        if (!tagRequired)
          throw new Error(`discriminator: "${tagName}" must be required`);
        return oneOfMapping;
        function hasRequired({ required: required2 }) {
          return Array.isArray(required2) && required2.includes(tagName);
        }
        function addMappings(sch, i2) {
          if (sch.const) {
            addMapping(sch.const, i2);
          } else if (sch.enum) {
            for (const tagValue of sch.enum) {
              addMapping(tagValue, i2);
            }
          } else {
            throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
          }
        }
        function addMapping(tagValue, i2) {
          if (typeof tagValue != "string" || tagValue in oneOfMapping) {
            throw new Error(`discriminator: "${tagName}" values must be unique strings`);
          }
          oneOfMapping[tagValue] = i2;
        }
      }
    }
  };
  discriminator.default = def;
  return discriminator;
}
const $schema = "http://json-schema.org/draft-07/schema#";
const $id = "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 = ["object", "boolean"];
const properties = { "$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$$3 = {
  $schema,
  $id,
  title,
  definitions,
  type,
  properties,
  "default": true
};
var hasRequiredAjv;
function requireAjv() {
  if (hasRequiredAjv) return ajv.exports;
  hasRequiredAjv = 1;
  (function(module, exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
    const core_1 = /* @__PURE__ */ requireCore$1();
    const draft7_1 = /* @__PURE__ */ requireDraft7();
    const discriminator_1 = /* @__PURE__ */ requireDiscriminator();
    const draft7MetaSchema = require$$3;
    const META_SUPPORT_DATA = ["/properties"];
    const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
    class Ajv2 extends core_1.default {
      _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v2) => this.addVocabulary(v2));
        if (this.opts.discriminator)
          this.addKeyword(discriminator_1.default);
      }
      _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
          return;
        const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema;
        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
      }
      defaultMeta() {
        return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);
      }
    }
    exports.Ajv = Ajv2;
    module.exports = exports = Ajv2;
    module.exports.Ajv = Ajv2;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = Ajv2;
    var validate_1 = /* @__PURE__ */ requireValidate();
    Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
      return validate_1.KeywordCxt;
    } });
    var codegen_1 = /* @__PURE__ */ requireCodegen();
    Object.defineProperty(exports, "_", { enumerable: true, get: function() {
      return codegen_1._;
    } });
    Object.defineProperty(exports, "str", { enumerable: true, get: function() {
      return codegen_1.str;
    } });
    Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
      return codegen_1.stringify;
    } });
    Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
      return codegen_1.nil;
    } });
    Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
      return codegen_1.Name;
    } });
    Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
      return codegen_1.CodeGen;
    } });
    var validation_error_1 = /* @__PURE__ */ requireValidation_error();
    Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() {
      return validation_error_1.default;
    } });
    var ref_error_1 = /* @__PURE__ */ requireRef_error();
    Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() {
      return ref_error_1.default;
    } });
  })(ajv, ajv.exports);
  return ajv.exports;
}
var hasRequiredLimit;
function requireLimit() {
  if (hasRequiredLimit) return limit;
  hasRequiredLimit = 1;
  (function(exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.formatLimitDefinition = void 0;
    const ajv_1 = /* @__PURE__ */ requireAjv();
    const codegen_1 = /* @__PURE__ */ requireCodegen();
    const ops = codegen_1.operators;
    const KWDs = {
      formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
      formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
      formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
      formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
    };
    const error = {
      message: ({ keyword: keyword2, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword2].okStr} ${schemaCode}`,
      params: ({ keyword: keyword2, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword2].okStr}, limit: ${schemaCode}}`
    };
    exports.formatLimitDefinition = {
      keyword: Object.keys(KWDs),
      type: "string",
      schemaType: "string",
      $data: true,
      error,
      code(cxt) {
        const { gen, data: data2, schemaCode, keyword: keyword2, it: it2 } = cxt;
        const { opts, self: self2 } = it2;
        if (!opts.validateFormats)
          return;
        const fCxt = new ajv_1.KeywordCxt(it2, self2.RULES.all.format.definition, "format");
        if (fCxt.$data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self2.formats,
            code: opts.code.formats
          });
          const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`);
          cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt)));
        }
        function validateFormat() {
          const format2 = fCxt.schema;
          const fmtDef = self2.formats[format2];
          if (!fmtDef || fmtDef === true)
            return;
          if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") {
            throw new Error(`"${keyword2}": format "${format2}" does not define "compare" function`);
          }
          const fmt = gen.scopeValue("formats", {
            key: format2,
            ref: fmtDef,
            code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format2)}` : void 0
          });
          cxt.fail$data(compareCode(fmt));
        }
        function compareCode(fmt) {
          return (0, codegen_1._)`${fmt}.compare(${data2}, ${schemaCode}) ${KWDs[keyword2].fail} 0`;
        }
      },
      dependencies: ["format"]
    };
    const formatLimitPlugin = (ajv2) => {
      ajv2.addKeyword(exports.formatLimitDefinition);
      return ajv2;
    };
    exports.default = formatLimitPlugin;
  })(limit);
  return limit;
}
var hasRequiredDist;
function requireDist() {
  if (hasRequiredDist) return dist.exports;
  hasRequiredDist = 1;
  (function(module, exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    const formats_12 = requireFormats();
    const limit_1 = requireLimit();
    const codegen_1 = /* @__PURE__ */ requireCodegen();
    const fullName = new codegen_1.Name("fullFormats");
    const fastName = new codegen_1.Name("fastFormats");
    const formatsPlugin = (ajv2, opts = { keywords: true }) => {
      if (Array.isArray(opts)) {
        addFormats(ajv2, opts, formats_12.fullFormats, fullName);
        return ajv2;
      }
      const [formats2, exportName] = opts.mode === "fast" ? [formats_12.fastFormats, fastName] : [formats_12.fullFormats, fullName];
      const list = opts.formats || formats_12.formatNames;
      addFormats(ajv2, list, formats2, exportName);
      if (opts.keywords)
        (0, limit_1.default)(ajv2);
      return ajv2;
    };
    formatsPlugin.get = (name2, mode = "full") => {
      const formats2 = mode === "fast" ? formats_12.fastFormats : formats_12.fullFormats;
      const f2 = formats2[name2];
      if (!f2)
        throw new Error(`Unknown format "${name2}"`);
      return f2;
    };
    function addFormats(ajv2, list, fs2, exportName) {
      var _a2;
      var _b;
      (_a2 = (_b = ajv2.opts.code).formats) !== null && _a2 !== void 0 ? _a2 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
      for (const f2 of list)
        ajv2.addFormat(f2, fs2[f2]);
    }
    module.exports = exports = formatsPlugin;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = formatsPlugin;
  })(dist, dist.exports);
  return dist.exports;
}
var distExports = requireDist();
const _addFormats = /* @__PURE__ */ getDefaultExportFromCjs(distExports);
function createDefaultAjvInstance() {
  const ajv2 = new Ajv({
    strict: false,
    validateFormats: true,
    validateSchema: false,
    allErrors: true
  });
  const addFormats = _addFormats;
  addFormats(ajv2);
  return ajv2;
}
class AjvJsonSchemaValidator {
  /**
   * Create an AJV validator
   *
   * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.
   *
   * @example
   * ```typescript
   * // Use default configuration (recommended for most cases)
   * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
   * const validator = new AjvJsonSchemaValidator();
   *
   * // Or provide custom AJV instance for advanced configuration
   * import { Ajv } from 'ajv';
   * import addFormats from 'ajv-formats';
   *
   * const ajv = new Ajv({ validateFormats: true });
   * addFormats(ajv);
   * const validator = new AjvJsonSchemaValidator(ajv);
   * ```
   */
  constructor(ajv2) {
    this._ajv = ajv2 ?? createDefaultAjvInstance();
  }
  /**
   * Create a validator for the given JSON Schema
   *
   * The validator is compiled once and can be reused multiple times.
   * If the schema has an $id, it will be cached by AJV automatically.
   *
   * @param schema - Standard JSON Schema object
   * @returns A validator function that validates input data
   */
  getValidator(schema) {
    const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema);
    return (input) => {
      const valid = ajvValidator(input);
      if (valid) {
        return {
          valid: true,
          data: input,
          errorMessage: void 0
        };
      } else {
        return {
          valid: false,
          data: void 0,
          errorMessage: this._ajv.errorsText(ajvValidator.errors)
        };
      }
    };
  }
}
class ExperimentalClientTasks {
  constructor(_client) {
    this._client = _client;
  }
  /**
   * Calls a tool and returns an AsyncGenerator that yields response messages.
   * The generator is guaranteed to end with either a 'result' or 'error' message.
   *
   * This method provides streaming access to tool execution, allowing you to
   * observe intermediate task status updates for long-running tool calls.
   * Automatically validates structured output if the tool has an outputSchema.
   *
   * @example
   * ```typescript
   * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
   * for await (const message of stream) {
   *   switch (message.type) {
   *     case 'taskCreated':
   *       console.log('Tool execution started:', message.task.taskId);
   *       break;
   *     case 'taskStatus':
   *       console.log('Tool status:', message.task.status);
   *       break;
   *     case 'result':
   *       console.log('Tool result:', message.result);
   *       break;
   *     case 'error':
   *       console.error('Tool error:', message.error);
   *       break;
   *   }
   * }
   * ```
   *
   * @param params - Tool call parameters (name and arguments)
   * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
   * @param options - Optional request options (timeout, signal, task creation params, etc.)
   * @returns AsyncGenerator that yields ResponseMessage objects
   *
   * @experimental
   */
  async *callToolStream(params, resultSchema = CallToolResultSchema, options) {
    const clientInternal = this._client;
    const optionsWithTask = {
      ...options,
      // We check if the tool is known to be a task during auto-configuration, but assume
      // the caller knows what they're doing if they pass this explicitly
      task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : void 0)
    };
    const stream = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
    const validator = clientInternal.getToolOutputValidator(params.name);
    for await (const message of stream) {
      if (message.type === "result" && validator) {
        const result = message.result;
        if (!result.structuredContent && !result.isError) {
          yield {
            type: "error",
            error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
          };
          return;
        }
        if (result.structuredContent) {
          try {
            const validationResult = validator(result.structuredContent);
            if (!validationResult.valid) {
              yield {
                type: "error",
                error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
              };
              return;
            }
          } catch (error) {
            if (error instanceof McpError) {
              yield { type: "error", error };
              return;
            }
            yield {
              type: "error",
              error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)
            };
            return;
          }
        }
      }
      yield message;
    }
  }
  /**
   * Gets the current status of a task.
   *
   * @param taskId - The task identifier
   * @param options - Optional request options
   * @returns The task status
   *
   * @experimental
   */
  async getTask(taskId, options) {
    return this._client.getTask({ taskId }, options);
  }
  /**
   * Retrieves the result of a completed task.
   *
   * @param taskId - The task identifier
   * @param resultSchema - Zod schema for validating the result
   * @param options - Optional request options
   * @returns The task result
   *
   * @experimental
   */
  async getTaskResult(taskId, resultSchema, options) {
    return this._client.getTaskResult({ taskId }, resultSchema, options);
  }
  /**
   * Lists tasks with optional pagination.
   *
   * @param cursor - Optional pagination cursor
   * @param options - Optional request options
   * @returns List of tasks with optional next cursor
   *
   * @experimental
   */
  async listTasks(cursor, options) {
    return this._client.listTasks(cursor ? { cursor } : void 0, options);
  }
  /**
   * Cancels a running task.
   *
   * @param taskId - The task identifier
   * @param options - Optional request options
   *
   * @experimental
   */
  async cancelTask(taskId, options) {
    return this._client.cancelTask({ taskId }, options);
  }
  /**
   * Sends a request and returns an AsyncGenerator that yields response messages.
   * The generator is guaranteed to end with either a 'result' or 'error' message.
   *
   * This method provides streaming access to request processing, allowing you to
   * observe intermediate task status updates for task-augmented requests.
   *
   * @param request - The request to send
   * @param resultSchema - Zod schema for validating the result
   * @param options - Optional request options (timeout, signal, task creation params, etc.)
   * @returns AsyncGenerator that yields ResponseMessage objects
   *
   * @experimental
   */
  requestStream(request, resultSchema, options) {
    return this._client.requestStream(request, resultSchema, options);
  }
}
function assertToolsCallTaskCapability(requests, method, entityName) {
  if (!requests) {
    throw new Error(`${entityName} does not support task creation (required for ${method})`);
  }
  switch (method) {
    case "tools/call":
      if (!requests.tools?.call) {
        throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
      }
      break;
  }
}
function assertClientRequestTaskCapability(requests, method, entityName) {
  if (!requests) {
    throw new Error(`${entityName} does not support task creation (required for ${method})`);
  }
  switch (method) {
    case "sampling/createMessage":
      if (!requests.sampling?.createMessage) {
        throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
      }
      break;
    case "elicitation/create":
      if (!requests.elicitation?.create) {
        throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
      }
      break;
  }
}
function applyElicitationDefaults(schema, data2) {
  if (!schema || data2 === null || typeof data2 !== "object")
    return;
  if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
    const obj = data2;
    const props = schema.properties;
    for (const key of Object.keys(props)) {
      const propSchema = props[key];
      if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) {
        obj[key] = propSchema.default;
      }
      if (obj[key] !== void 0) {
        applyElicitationDefaults(propSchema, obj[key]);
      }
    }
  }
  if (Array.isArray(schema.anyOf)) {
    for (const sub of schema.anyOf) {
      if (typeof sub !== "boolean") {
        applyElicitationDefaults(sub, data2);
      }
    }
  }
  if (Array.isArray(schema.oneOf)) {
    for (const sub of schema.oneOf) {
      if (typeof sub !== "boolean") {
        applyElicitationDefaults(sub, data2);
      }
    }
  }
}
function getSupportedElicitationModes(capabilities) {
  if (!capabilities) {
    return { supportsFormMode: false, supportsUrlMode: false };
  }
  const hasFormCapability = capabilities.form !== void 0;
  const hasUrlCapability = capabilities.url !== void 0;
  const supportsFormMode = hasFormCapability || !hasFormCapability && !hasUrlCapability;
  const supportsUrlMode = hasUrlCapability;
  return { supportsFormMode, supportsUrlMode };
}
class Client extends Protocol {
  /**
   * Initializes this client with the given name and version information.
   */
  constructor(_clientInfo, options) {
    super(options);
    this._clientInfo = _clientInfo;
    this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
    this._cachedKnownTaskTools = /* @__PURE__ */ new Set();
    this._cachedRequiredTaskTools = /* @__PURE__ */ new Set();
    this._listChangedDebounceTimers = /* @__PURE__ */ new Map();
    this._capabilities = options?.capabilities ?? {};
    this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
    if (options?.listChanged) {
      this._pendingListChangedConfig = options.listChanged;
    }
  }
  /**
   * Set up handlers for list changed notifications based on config and server capabilities.
   * This should only be called after initialization when server capabilities are known.
   * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
   * @internal
   */
  _setupListChangedHandlers(config2) {
    if (config2.tools && this._serverCapabilities?.tools?.listChanged) {
      this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config2.tools, async () => {
        const result = await this.listTools();
        return result.tools;
      });
    }
    if (config2.prompts && this._serverCapabilities?.prompts?.listChanged) {
      this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config2.prompts, async () => {
        const result = await this.listPrompts();
        return result.prompts;
      });
    }
    if (config2.resources && this._serverCapabilities?.resources?.listChanged) {
      this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config2.resources, async () => {
        const result = await this.listResources();
        return result.resources;
      });
    }
  }
  /**
   * Access experimental features.
   *
   * WARNING: These APIs are experimental and may change without notice.
   *
   * @experimental
   */
  get experimental() {
    if (!this._experimental) {
      this._experimental = {
        tasks: new ExperimentalClientTasks(this)
      };
    }
    return this._experimental;
  }
  /**
   * 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);
  }
  /**
   * Override request handler registration to enforce client-side validation for elicitation.
   */
  setRequestHandler(requestSchema, handler) {
    const shape = getObjectShape(requestSchema);
    const methodSchema = shape?.method;
    if (!methodSchema) {
      throw new Error("Schema is missing a method literal");
    }
    let methodValue;
    if (isZ4Schema(methodSchema)) {
      const v4Schema = methodSchema;
      const v4Def = v4Schema._zod?.def;
      methodValue = v4Def?.value ?? v4Schema.value;
    } else {
      const v3Schema = methodSchema;
      const legacyDef = v3Schema._def;
      methodValue = legacyDef?.value ?? v3Schema.value;
    }
    if (typeof methodValue !== "string") {
      throw new Error("Schema method literal must be a string");
    }
    const method = methodValue;
    if (method === "elicitation/create") {
      const wrappedHandler = async (request, extra) => {
        const validatedRequest = safeParse(ElicitRequestSchema, request);
        if (!validatedRequest.success) {
          const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
          throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
        }
        const { params } = validatedRequest.data;
        params.mode = params.mode ?? "form";
        const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
        if (params.mode === "form" && !supportsFormMode) {
          throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
        }
        if (params.mode === "url" && !supportsUrlMode) {
          throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
        }
        const result = await Promise.resolve(handler(request, extra));
        if (params.task) {
          const taskValidationResult = safeParse(CreateTaskResultSchema, result);
          if (!taskValidationResult.success) {
            const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
            throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
          }
          return taskValidationResult.data;
        }
        const validationResult = safeParse(ElicitResultSchema, result);
        if (!validationResult.success) {
          const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
          throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
        }
        const validatedResult = validationResult.data;
        const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
        if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
          if (this._capabilities.elicitation?.form?.applyDefaults) {
            try {
              applyElicitationDefaults(requestedSchema, validatedResult.content);
            } catch {
            }
          }
        }
        return validatedResult;
      };
      return super.setRequestHandler(requestSchema, wrappedHandler);
    }
    if (method === "sampling/createMessage") {
      const wrappedHandler = async (request, extra) => {
        const validatedRequest = safeParse(CreateMessageRequestSchema, request);
        if (!validatedRequest.success) {
          const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
          throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
        }
        const { params } = validatedRequest.data;
        const result = await Promise.resolve(handler(request, extra));
        if (params.task) {
          const taskValidationResult = safeParse(CreateTaskResultSchema, result);
          if (!taskValidationResult.success) {
            const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
            throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
          }
          return taskValidationResult.data;
        }
        const hasTools = params.tools || params.toolChoice;
        const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
        const validationResult = safeParse(resultSchema, result);
        if (!validationResult.success) {
          const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
          throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
        }
        return validationResult.data;
      };
      return super.setRequestHandler(requestSchema, wrappedHandler);
    }
    return super.setRequestHandler(requestSchema, handler);
  }
  assertCapability(capability, method) {
    if (!this._serverCapabilities?.[capability]) {
      throw new Error(`Server does not support ${capability} (required for ${method})`);
    }
  }
  async connect(transport, options) {
    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, options);
      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"
      });
      if (this._pendingListChangedConfig) {
        this._setupListChangedHandlers(this._pendingListChangedConfig);
        this._pendingListChangedConfig = void 0;
      }
    } 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) {
    switch (method) {
      case "logging/setLevel":
        if (!this._serverCapabilities?.logging) {
          throw new Error(`Server does not support logging (required for ${method})`);
        }
        break;
      case "prompts/get":
      case "prompts/list":
        if (!this._serverCapabilities?.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 (!this._serverCapabilities?.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 (!this._serverCapabilities?.tools) {
          throw new Error(`Server does not support tools (required for ${method})`);
        }
        break;
      case "completion/complete":
        if (!this._serverCapabilities?.completions) {
          throw new Error(`Server does not support completions (required for ${method})`);
        }
        break;
    }
  }
  assertNotificationCapability(method) {
    switch (method) {
      case "notifications/roots/list_changed":
        if (!this._capabilities.roots?.listChanged) {
          throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
        }
        break;
    }
  }
  assertRequestHandlerCapability(method) {
    if (!this._capabilities) {
      return;
    }
    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;
      case "tasks/get":
      case "tasks/list":
      case "tasks/result":
      case "tasks/cancel":
        if (!this._capabilities.tasks) {
          throw new Error(`Client does not support tasks capability (required for ${method})`);
        }
        break;
    }
  }
  assertTaskCapability(method) {
    assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, "Server");
  }
  assertTaskHandlerCapability(method) {
    if (!this._capabilities) {
      return;
    }
    assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, "Client");
  }
  async ping(options) {
    return this.request({ method: "ping" }, EmptyResultSchema, options);
  }
  async complete(params, options) {
    return this.request({ method: "completion/complete", params }, CompleteResultSchema, options);
  }
  async setLoggingLevel(level, options) {
    return this.request({ method: "logging/setLevel", params: { level } }, EmptyResultSchema, options);
  }
  async getPrompt(params, options) {
    return this.request({ method: "prompts/get", params }, GetPromptResultSchema, options);
  }
  async listPrompts(params, options) {
    return this.request({ method: "prompts/list", params }, ListPromptsResultSchema, options);
  }
  async listResources(params, options) {
    return this.request({ method: "resources/list", params }, ListResourcesResultSchema, options);
  }
  async listResourceTemplates(params, options) {
    return this.request({ method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, options);
  }
  async readResource(params, options) {
    return this.request({ method: "resources/read", params }, ReadResourceResultSchema, options);
  }
  async subscribeResource(params, options) {
    return this.request({ method: "resources/subscribe", params }, EmptyResultSchema, options);
  }
  async unsubscribeResource(params, options) {
    return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options);
  }
  /**
   * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
   *
   * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
   */
  async callTool(params, resultSchema = CallToolResultSchema, options) {
    if (this.isToolTaskRequired(params.name)) {
      throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
    }
    const result = await this.request({ method: "tools/call", params }, resultSchema, options);
    const validator = this.getToolOutputValidator(params.name);
    if (validator) {
      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 validationResult = validator(result.structuredContent);
          if (!validationResult.valid) {
            throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
          }
        } 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;
  }
  isToolTask(toolName) {
    if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {
      return false;
    }
    return this._cachedKnownTaskTools.has(toolName);
  }
  /**
   * Check if a tool requires task-based execution.
   * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
   */
  isToolTaskRequired(toolName) {
    return this._cachedRequiredTaskTools.has(toolName);
  }
  /**
   * Cache validators for tool output schemas.
   * Called after listTools() to pre-compile validators for better performance.
   */
  cacheToolMetadata(tools) {
    this._cachedToolOutputValidators.clear();
    this._cachedKnownTaskTools.clear();
    this._cachedRequiredTaskTools.clear();
    for (const tool of tools) {
      if (tool.outputSchema) {
        const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
        this._cachedToolOutputValidators.set(tool.name, toolValidator);
      }
      const taskSupport = tool.execution?.taskSupport;
      if (taskSupport === "required" || taskSupport === "optional") {
        this._cachedKnownTaskTools.add(tool.name);
      }
      if (taskSupport === "required") {
        this._cachedRequiredTaskTools.add(tool.name);
      }
    }
  }
  /**
   * Get cached validator for a tool
   */
  getToolOutputValidator(toolName) {
    return this._cachedToolOutputValidators.get(toolName);
  }
  async listTools(params, options) {
    const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options);
    this.cacheToolMetadata(result.tools);
    return result;
  }
  /**
   * Set up a single list changed handler.
   * @internal
   */
  _setupListChangedHandler(listType, notificationSchema, options, fetcher) {
    const parseResult = ListChangedOptionsBaseSchema.safeParse(options);
    if (!parseResult.success) {
      throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
    }
    if (typeof options.onChanged !== "function") {
      throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
    }
    const { autoRefresh, debounceMs } = parseResult.data;
    const { onChanged } = options;
    const refresh = async () => {
      if (!autoRefresh) {
        onChanged(null, null);
        return;
      }
      try {
        const items2 = await fetcher();
        onChanged(null, items2);
      } catch (e2) {
        const error = e2 instanceof Error ? e2 : new Error(String(e2));
        onChanged(error, null);
      }
    };
    const handler = () => {
      if (debounceMs) {
        const existingTimer = this._listChangedDebounceTimers.get(listType);
        if (existingTimer) {
          clearTimeout(existingTimer);
        }
        const timer = setTimeout(refresh, debounceMs);
        this._listChangedDebounceTimers.set(listType, timer);
      } else {
        refresh();
      }
    };
    this.setNotificationHandler(notificationSchema, handler);
  }
  async sendRootsListChanged() {
    return this.notification({ method: "notifications/roots/list_changed" });
  }
}
class ParseError extends Error {
  constructor(message, options) {
    super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
  }
}
const LF = 10, CR = 13, SPACE = 32;
function noop$1(_arg) {
}
function createParser(config2) {
  if (typeof config2 == "function")
    throw new TypeError(
      "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
    );
  const { onEvent = noop$1, onError = noop$1, onRetry = noop$1, onComment, maxBufferSize } = config2, pendingFragments = [];
  let pendingFragmentsLength = 0, isFirstChunk = true, id2, data2 = "", dataLines = 0, eventType, terminated = false;
  function feed(chunk) {
    if (terminated)
      throw new Error(
        "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
      );
    if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
      const trailing2 = processLines(chunk);
      trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
      return;
    }
    if (chunk.indexOf(`
`) === -1 && chunk.indexOf("\r") === -1) {
      pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
      return;
    }
    pendingFragments.push(chunk);
    const input = pendingFragments.join("");
    pendingFragments.length = 0, pendingFragmentsLength = 0;
    const trailing = processLines(input);
    trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
  }
  function checkBufferSize() {
    maxBufferSize !== void 0 && (pendingFragmentsLength + data2.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id2 = void 0, data2 = "", dataLines = 0, eventType = void 0, onError(
      new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
        type: "max-buffer-size-exceeded"
      })
    )));
  }
  function processLines(chunk) {
    let searchIndex = 0;
    if (chunk.indexOf("\r") === -1) {
      let lfIndex = chunk.indexOf(`
`, searchIndex);
      for (; lfIndex !== -1; ) {
        if (searchIndex === lfIndex) {
          dataLines > 0 && onEvent({ id: id2, event: eventType, data: data2 }), id2 = void 0, data2 = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
`, searchIndex);
          continue;
        }
        const firstCharCode = chunk.charCodeAt(searchIndex);
        if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
          const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
          if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
            onEvent({ id: id2, event: eventType, data: value }), id2 = void 0, data2 = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
`, searchIndex);
            continue;
          }
          data2 = dataLines === 0 ? value : `${data2}
${value}`, dataLines++;
        } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
          chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
          lfIndex
        ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
        searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
`, searchIndex);
      }
      return chunk.slice(searchIndex);
    }
    for (; searchIndex < chunk.length; ) {
      const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
`, searchIndex);
      let lineEnd = -1;
      if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
        break;
      parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
    }
    return chunk.slice(searchIndex);
  }
  function parseLine(chunk, start, end) {
    if (start === end) {
      dispatchEvent();
      return;
    }
    const firstCharCode = chunk.charCodeAt(start);
    if (isDataPrefix(chunk, start, firstCharCode)) {
      const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
      data2 = dataLines === 0 ? value2 : `${data2}
${value2}`, dataLines++;
      return;
    }
    if (isEventPrefix(chunk, start, firstCharCode)) {
      eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
      return;
    }
    if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
      const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
      id2 = value2.includes("\0") ? void 0 : value2;
      return;
    }
    if (firstCharCode === 58) {
      if (onComment) {
        const line2 = chunk.slice(start, end);
        onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
      }
      return;
    }
    const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
    if (fieldSeparatorIndex === -1) {
      processField(line, "", line);
      return;
    }
    const field = line.slice(0, fieldSeparatorIndex), offset2 = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset2);
    processField(field, value, line);
  }
  function processField(field, value, line) {
    switch (field) {
      case "event":
        eventType = value || void 0;
        break;
      case "data":
        data2 = dataLines === 0 ? value : `${data2}
${value}`, dataLines++;
        break;
      case "id":
        id2 = value.includes("\0") ? void 0 : value;
        break;
      case "retry":
        /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
          new ParseError(`Invalid \`retry\` value: "${value}"`, {
            type: "invalid-retry",
            value,
            line
          })
        );
        break;
      default:
        onError(
          new ParseError(
            `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}…` : field}"`,
            { type: "unknown-field", field, value, line }
          )
        );
        break;
    }
  }
  function dispatchEvent() {
    dataLines > 0 && onEvent({
      id: id2,
      event: eventType,
      data: data2
    }), id2 = void 0, data2 = "", dataLines = 0, eventType = void 0;
  }
  function reset(options = {}) {
    if (options.consume && pendingFragments.length > 0) {
      const incompleteLine = pendingFragments.join("");
      parseLine(incompleteLine, 0, incompleteLine.length);
    }
    isFirstChunk = true, id2 = void 0, data2 = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
  }
  return { feed, reset };
}
function isDataPrefix(chunk, i2, firstCharCode) {
  return firstCharCode === 100 && chunk.charCodeAt(i2 + 1) === 97 && chunk.charCodeAt(i2 + 2) === 116 && chunk.charCodeAt(i2 + 3) === 97 && chunk.charCodeAt(i2 + 4) === 58;
}
function isEventPrefix(chunk, i2, firstCharCode) {
  return firstCharCode === 101 && chunk.charCodeAt(i2 + 1) === 118 && chunk.charCodeAt(i2 + 2) === 101 && chunk.charCodeAt(i2 + 3) === 110 && chunk.charCodeAt(i2 + 4) === 116 && chunk.charCodeAt(i2 + 5) === 58;
}
class ErrorEvent extends Event {
  /**
   * Constructs a new `ErrorEvent` instance. This is typically not called directly,
   * but rather emitted by the `EventSource` object when an error occurs.
   *
   * @param type - The type of the event (should be "error")
   * @param errorEventInitDict - Optional properties to include in the error event
   */
  constructor(type2, errorEventInitDict) {
    var _a2, _b;
    super(type2), this.code = (_a2 = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a2 : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0;
  }
  /**
   * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
   * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
   * we explicitly include the properties in the `inspect` method.
   *
   * This is automatically called by Node.js when you `console.log` an instance of this class.
   *
   * @param _depth - The current depth
   * @param options - The options passed to `util.inspect`
   * @param inspect - The inspect function to use (prevents having to import it from `util`)
   * @returns A string representation of the error
   */
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
    return inspect(inspectableError(this), options);
  }
  /**
   * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
   * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
   * we explicitly include the properties in the `inspect` method.
   *
   * This is automatically called by Deno when you `console.log` an instance of this class.
   *
   * @param inspect - The inspect function to use (prevents having to import it from `util`)
   * @param options - The options passed to `Deno.inspect`
   * @returns A string representation of the error
   */
  [/* @__PURE__ */ Symbol.for("Deno.customInspect")](inspect, options) {
    return inspect(inspectableError(this), options);
  }
}
function syntaxError(message) {
  const DomException = globalThis.DOMException;
  return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
}
function flattenError(err) {
  return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`;
}
function inspectableError(err) {
  return {
    type: err.type,
    message: err.message,
    code: err.code,
    defaultPrevented: err.defaultPrevented,
    cancelable: err.cancelable,
    timeStamp: err.timeStamp
  };
}
var __typeError = (msg) => {
  throw TypeError(msg);
}, __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg), __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __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), __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value), __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method), _readyState, _url, _redirectUrl, _withCredentials, _fetch, _reconnectInterval, _reconnectTimer, _lastEventId, _controller, _parser, _onError, _onMessage, _onOpen, _EventSource_instances, connect_fn, _onFetchResponse, _onFetchError, getRequestOptions_fn, _onEvent, _onRetryChange, failConnection_fn, scheduleReconnect_fn, _reconnect;
class EventSource extends EventTarget {
  constructor(url2, eventSourceInitDict) {
    var _a2, _b;
    super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => {
      var _a22;
      __privateGet(this, _parser).reset();
      const { body, redirected, status, headers } = response;
      if (status === 204) {
        __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
        return;
      }
      if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
        __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
        return;
      }
      if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
        __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status);
        return;
      }
      if (__privateGet(this, _readyState) === this.CLOSED)
        return;
      __privateSet(this, _readyState, this.OPEN);
      const openEvent = new Event("open");
      if ((_a22 = __privateGet(this, _onOpen)) == null || _a22.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
        __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
        return;
      }
      const decoder = new TextDecoder(), reader = body.getReader();
      let open = true;
      do {
        const { done, value } = await reader.read();
        value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
      } while (open);
    }), __privateAdd(this, _onFetchError, (err) => {
      __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));
    }), __privateAdd(this, _onEvent, (event) => {
      typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
      const messageEvent = new MessageEvent(event.event || "message", {
        data: event.data,
        origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,
        lastEventId: event.id || ""
      });
      __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
    }), __privateAdd(this, _onRetryChange, (value) => {
      __privateSet(this, _reconnectInterval, value);
    }), __privateAdd(this, _reconnect, () => {
      __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
    });
    try {
      if (url2 instanceof URL)
        __privateSet(this, _url, url2);
      else if (typeof url2 == "string")
        __privateSet(this, _url, new URL(url2, getBaseURL()));
      else
        throw new Error("Invalid URL");
    } catch {
      throw syntaxError("An invalid or illegal string was specified");
    }
    __privateSet(this, _parser, createParser({
      onEvent: __privateGet(this, _onEvent),
      onRetry: __privateGet(this, _onRetryChange)
    })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a2 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a2 : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
  }
  /**
   * Returns the state of this EventSource object's connection. It can have the values described below.
   *
   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
   *
   * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
   * defined in the TypeScript `dom` library.
   *
   * @public
   */
  get readyState() {
    return __privateGet(this, _readyState);
  }
  /**
   * Returns the URL providing the event stream.
   *
   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
   *
   * @public
   */
  get url() {
    return __privateGet(this, _url).href;
  }
  /**
   * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
   *
   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
   */
  get withCredentials() {
    return __privateGet(this, _withCredentials);
  }
  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
  get onerror() {
    return __privateGet(this, _onError);
  }
  set onerror(value) {
    __privateSet(this, _onError, value);
  }
  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
  get onmessage() {
    return __privateGet(this, _onMessage);
  }
  set onmessage(value) {
    __privateSet(this, _onMessage, value);
  }
  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
  get onopen() {
    return __privateGet(this, _onOpen);
  }
  set onopen(value) {
    __privateSet(this, _onOpen, value);
  }
  addEventListener(type2, listener, options) {
    const listen = listener;
    super.addEventListener(type2, listen, options);
  }
  removeEventListener(type2, listener, options) {
    const listen = listener;
    super.removeEventListener(type2, listen, options);
  }
  /**
   * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
   *
   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
   *
   * @public
   */
  close() {
    __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0));
  }
}
_readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /**
* Connect to the given URL and start receiving events
*
* @internal
*/
connect_fn = function() {
  __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));
}, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**
* Get request options for the `fetch()` request
*
* @returns The request options
* @internal
*/
getRequestOptions_fn = function() {
  var _a2;
  const init = {
    // [spec] Let `corsAttributeState` be `Anonymous`…
    // [spec] …will have their mode set to "cors"…
    mode: "cors",
    redirect: "follow",
    headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 },
    cache: "no-store",
    signal: (_a2 = __privateGet(this, _controller)) == null ? void 0 : _a2.signal
  };
  return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
}, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**
* Handles the process referred to in the EventSource specification as "failing a connection".
*
* @param error - The error causing the connection to fail
* @param code - The HTTP status code, if available
* @internal
*/
failConnection_fn = function(message, code2) {
  var _a2;
  __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
  const errorEvent = new ErrorEvent("error", { code: code2, message });
  (_a2 = __privateGet(this, _onError)) == null || _a2.call(this, errorEvent), this.dispatchEvent(errorEvent);
}, /**
* Schedules a reconnection attempt against the EventSource endpoint.
*
* @param message - The error causing the connection to fail
* @param code - The HTTP status code, if available
* @internal
*/
scheduleReconnect_fn = function(message, code2) {
  var _a2;
  if (__privateGet(this, _readyState) === this.CLOSED)
    return;
  __privateSet(this, _readyState, this.CONNECTING);
  const errorEvent = new ErrorEvent("error", { code: code2, message });
  (_a2 = __privateGet(this, _onError)) == null || _a2.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
}, _reconnect = /* @__PURE__ */ new WeakMap(), /**
* ReadyState representing an EventSource currently trying to connect
*
* @public
*/
EventSource.CONNECTING = 0, /**
* ReadyState representing an EventSource connection that is open (eg connected)
*
* @public
*/
EventSource.OPEN = 1, /**
* ReadyState representing an EventSource connection that is closed (eg disconnected)
*
* @public
*/
EventSource.CLOSED = 2;
function getBaseURL() {
  const doc = "document" in globalThis ? globalThis.document : void 0;
  return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
}
function normalizeHeaders(headers) {
  if (!headers)
    return {};
  if (headers instanceof Headers) {
    return Object.fromEntries(headers.entries());
  }
  if (Array.isArray(headers)) {
    return Object.fromEntries(headers);
  }
  return { ...headers };
}
function createFetchWithInit(baseFetch = fetch, baseInit) {
  if (!baseInit) {
    return baseFetch;
  }
  return async (url2, init) => {
    const mergedInit = {
      ...baseInit,
      ...init,
      // Headers need special handling - merge instead of replace
      headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers
    };
    return baseFetch(url2, mergedInit);
  };
}
class SseError extends Error {
  constructor(code2, message, event) {
    super(`SSE error: ${message}`);
    this.code = code2;
    this.event = event;
  }
}
class SSEClientTransport {
  constructor(url2, opts) {
    this._url = url2;
    this._resourceMetadataUrl = void 0;
    this._scope = void 0;
    this._eventSourceInit = opts?.eventSourceInit;
    this._requestInit = opts?.requestInit;
    this._authProvider = opts?.authProvider;
    this._fetch = opts?.fetch;
    this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
  }
  async _authThenStart() {
    if (!this._authProvider) {
      throw new UnauthorizedError("No auth provider");
    }
    let result;
    try {
      result = await auth(this._authProvider, {
        serverUrl: this._url,
        resourceMetadataUrl: this._resourceMetadataUrl,
        scope: this._scope,
        fetchFn: this._fetchWithInit
      });
    } catch (error) {
      this.onerror?.(error);
      throw error;
    }
    if (result !== "AUTHORIZED") {
      throw new UnauthorizedError();
    }
    return await this._startOrAuth();
  }
  async _commonHeaders() {
    const headers = {};
    if (this._authProvider) {
      const tokens = await this._authProvider.tokens();
      if (tokens) {
        headers["Authorization"] = `Bearer ${tokens.access_token}`;
      }
    }
    if (this._protocolVersion) {
      headers["mcp-protocol-version"] = this._protocolVersion;
    }
    const extraHeaders = normalizeHeaders(this._requestInit?.headers);
    return new Headers({
      ...headers,
      ...extraHeaders
    });
  }
  _startOrAuth() {
    const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
    return new Promise((resolve2, reject) => {
      this._eventSource = new EventSource(this._url.href, {
        ...this._eventSourceInit,
        fetch: async (url2, init) => {
          const headers = await this._commonHeaders();
          headers.set("Accept", "text/event-stream");
          const response = await fetchImpl(url2, {
            ...init,
            headers
          });
          if (response.status === 401 && response.headers.has("www-authenticate")) {
            const { resourceMetadataUrl, scope: scope2 } = extractWWWAuthenticateParams(response);
            this._resourceMetadataUrl = resourceMetadataUrl;
            this._scope = scope2;
          }
          return response;
        }
      });
      this._abortController = new AbortController();
      this._eventSource.onerror = (event) => {
        if (event.code === 401 && this._authProvider) {
          this._authThenStart().then(resolve2, reject);
          return;
        }
        const error = new SseError(event.code, event.message, event);
        reject(error);
        this.onerror?.(error);
      };
      this._eventSource.onopen = () => {
      };
      this._eventSource.addEventListener("endpoint", (event) => {
        const messageEvent = event;
        try {
          this._endpoint = new URL(messageEvent.data, this._url);
          if (this._endpoint.origin !== this._url.origin) {
            throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
          }
        } catch (error) {
          reject(error);
          this.onerror?.(error);
          void this.close();
          return;
        }
        resolve2();
      });
      this._eventSource.onmessage = (event) => {
        const messageEvent = event;
        let message;
        try {
          message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
        } catch (error) {
          this.onerror?.(error);
          return;
        }
        this.onmessage?.(message);
      };
    });
  }
  async start() {
    if (this._eventSource) {
      throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");
    }
    return await this._startOrAuth();
  }
  /**
   * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
   */
  async finishAuth(authorizationCode) {
    if (!this._authProvider) {
      throw new UnauthorizedError("No auth provider");
    }
    const result = await auth(this._authProvider, {
      serverUrl: this._url,
      authorizationCode,
      resourceMetadataUrl: this._resourceMetadataUrl,
      scope: this._scope,
      fetchFn: this._fetchWithInit
    });
    if (result !== "AUTHORIZED") {
      throw new UnauthorizedError("Failed to authorize");
    }
  }
  async close() {
    this._abortController?.abort();
    this._eventSource?.close();
    this.onclose?.();
  }
  async send(message) {
    if (!this._endpoint) {
      throw new Error("Not connected");
    }
    try {
      const headers = await this._commonHeaders();
      headers.set("content-type", "application/json");
      const init = {
        ...this._requestInit,
        method: "POST",
        headers,
        body: JSON.stringify(message),
        signal: this._abortController?.signal
      };
      const response = await (this._fetch ?? fetch)(this._endpoint, init);
      if (!response.ok) {
        const text = await response.text().catch(() => null);
        if (response.status === 401 && this._authProvider) {
          const { resourceMetadataUrl, scope: scope2 } = extractWWWAuthenticateParams(response);
          this._resourceMetadataUrl = resourceMetadataUrl;
          this._scope = scope2;
          const result = await auth(this._authProvider, {
            serverUrl: this._url,
            resourceMetadataUrl: this._resourceMetadataUrl,
            scope: this._scope,
            fetchFn: this._fetchWithInit
          });
          if (result !== "AUTHORIZED") {
            throw new UnauthorizedError();
          }
          return this.send(message);
        }
        throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
      }
      await response.body?.cancel();
    } catch (error) {
      this.onerror?.(error);
      throw error;
    }
  }
  setProtocolVersion(version2) {
    this._protocolVersion = version2;
  }
}
class EventSourceParserStream extends TransformStream {
  constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
    let parser;
    super({
      start(controller) {
        parser = createParser({
          onEvent: (event) => {
            controller.enqueue(event);
          },
          onError(error) {
            typeof onError == "function" && onError(error), (onError === "terminate" || error.type === "max-buffer-size-exceeded") && controller.error(error);
          },
          onRetry,
          onComment,
          maxBufferSize
        });
      },
      transform(chunk) {
        parser.feed(chunk);
      }
    });
  }
}
const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
  initialReconnectionDelay: 1e3,
  maxReconnectionDelay: 3e4,
  reconnectionDelayGrowFactor: 1.5,
  maxRetries: 2
};
class StreamableHTTPError extends Error {
  constructor(code2, message) {
    super(`Streamable HTTP error: ${message}`);
    this.code = code2;
  }
}
class StreamableHTTPClientTransport {
  constructor(url2, opts) {
    this._hasCompletedAuthFlow = false;
    this._url = url2;
    this._resourceMetadataUrl = void 0;
    this._scope = void 0;
    this._requestInit = opts?.requestInit;
    this._authProvider = opts?.authProvider;
    this._fetch = opts?.fetch;
    this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
    this._sessionId = opts?.sessionId;
    this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
  }
  async _authThenStart() {
    if (!this._authProvider) {
      throw new UnauthorizedError("No auth provider");
    }
    let result;
    try {
      result = await auth(this._authProvider, {
        serverUrl: this._url,
        resourceMetadataUrl: this._resourceMetadataUrl,
        scope: this._scope,
        fetchFn: this._fetchWithInit
      });
    } catch (error) {
      this.onerror?.(error);
      throw error;
    }
    if (result !== "AUTHORIZED") {
      throw new UnauthorizedError();
    }
    return await this._startOrAuthSse({ resumptionToken: void 0 });
  }
  async _commonHeaders() {
    const headers = {};
    if (this._authProvider) {
      const tokens = await this._authProvider.tokens();
      if (tokens) {
        headers["Authorization"] = `Bearer ${tokens.access_token}`;
      }
    }
    if (this._sessionId) {
      headers["mcp-session-id"] = this._sessionId;
    }
    if (this._protocolVersion) {
      headers["mcp-protocol-version"] = this._protocolVersion;
    }
    const extraHeaders = normalizeHeaders(this._requestInit?.headers);
    return new Headers({
      ...headers,
      ...extraHeaders
    });
  }
  async _startOrAuthSse(options) {
    const { resumptionToken } = options;
    try {
      const headers = await this._commonHeaders();
      headers.set("Accept", "text/event-stream");
      if (resumptionToken) {
        headers.set("last-event-id", resumptionToken);
      }
      const response = await (this._fetch ?? fetch)(this._url, {
        method: "GET",
        headers,
        signal: this._abortController?.signal
      });
      if (!response.ok) {
        await response.body?.cancel();
        if (response.status === 401 && this._authProvider) {
          return await this._authThenStart();
        }
        if (response.status === 405) {
          return;
        }
        throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
      }
      this._handleSseStream(response.body, options, true);
    } catch (error) {
      this.onerror?.(error);
      throw error;
    }
  }
  /**
   * Calculates the next reconnection delay using  backoff algorithm
   *
   * @param attempt Current reconnection attempt count for the specific stream
   * @returns Time to wait in milliseconds before next reconnection attempt
   */
  _getNextReconnectionDelay(attempt) {
    if (this._serverRetryMs !== void 0) {
      return this._serverRetryMs;
    }
    const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
    const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
    const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
    return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
  }
  /**
   * Schedule a reconnection attempt using server-provided retry interval or backoff
   *
   * @param lastEventId The ID of the last received event for resumability
   * @param attemptCount Current reconnection attempt count for this specific stream
   */
  _scheduleReconnection(options, attemptCount = 0) {
    const maxRetries = this._reconnectionOptions.maxRetries;
    if (attemptCount >= maxRetries) {
      this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
      return;
    }
    const delay = this._getNextReconnectionDelay(attemptCount);
    this._reconnectionTimeout = setTimeout(() => {
      this._startOrAuthSse(options).catch((error) => {
        this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
        this._scheduleReconnection(options, attemptCount + 1);
      });
    }, delay);
  }
  _handleSseStream(stream, options, isReconnectable) {
    if (!stream) {
      return;
    }
    const { onresumptiontoken, replayMessageId } = options;
    let lastEventId;
    let hasPrimingEvent = false;
    let receivedResponse = false;
    const processStream = async () => {
      try {
        const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
          onRetry: (retryMs) => {
            this._serverRetryMs = retryMs;
          }
        })).getReader();
        while (true) {
          const { value: event, done } = await reader.read();
          if (done) {
            break;
          }
          if (event.id) {
            lastEventId = event.id;
            hasPrimingEvent = true;
            onresumptiontoken?.(event.id);
          }
          if (!event.data) {
            continue;
          }
          if (!event.event || event.event === "message") {
            try {
              const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
              if (isJSONRPCResultResponse(message)) {
                receivedResponse = true;
                if (replayMessageId !== void 0) {
                  message.id = replayMessageId;
                }
              }
              this.onmessage?.(message);
            } catch (error) {
              this.onerror?.(error);
            }
          }
        }
        const canResume = isReconnectable || hasPrimingEvent;
        const needsReconnect = canResume && !receivedResponse;
        if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
          this._scheduleReconnection({
            resumptionToken: lastEventId,
            onresumptiontoken,
            replayMessageId
          }, 0);
        }
      } catch (error) {
        this.onerror?.(new Error(`SSE stream disconnected: ${error}`));
        const canResume = isReconnectable || hasPrimingEvent;
        const needsReconnect = canResume && !receivedResponse;
        if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
          try {
            this._scheduleReconnection({
              resumptionToken: lastEventId,
              onresumptiontoken,
              replayMessageId
            }, 0);
          } catch (error2) {
            this.onerror?.(new Error(`Failed to reconnect: ${error2 instanceof Error ? error2.message : String(error2)}`));
          }
        }
      }
    };
    processStream();
  }
  async start() {
    if (this._abortController) {
      throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
    }
    this._abortController = new AbortController();
  }
  /**
   * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
   */
  async finishAuth(authorizationCode) {
    if (!this._authProvider) {
      throw new UnauthorizedError("No auth provider");
    }
    const result = await auth(this._authProvider, {
      serverUrl: this._url,
      authorizationCode,
      resourceMetadataUrl: this._resourceMetadataUrl,
      scope: this._scope,
      fetchFn: this._fetchWithInit
    });
    if (result !== "AUTHORIZED") {
      throw new UnauthorizedError("Failed to authorize");
    }
  }
  async close() {
    if (this._reconnectionTimeout) {
      clearTimeout(this._reconnectionTimeout);
      this._reconnectionTimeout = void 0;
    }
    this._abortController?.abort();
    this.onclose?.();
  }
  async send(message, options) {
    try {
      const { resumptionToken, onresumptiontoken } = options || {};
      if (resumptionToken) {
        this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => this.onerror?.(err));
        return;
      }
      const headers = await this._commonHeaders();
      headers.set("content-type", "application/json");
      headers.set("accept", "application/json, text/event-stream");
      const init = {
        ...this._requestInit,
        method: "POST",
        headers,
        body: JSON.stringify(message),
        signal: this._abortController?.signal
      };
      const response = await (this._fetch ?? fetch)(this._url, init);
      const sessionId = response.headers.get("mcp-session-id");
      if (sessionId) {
        this._sessionId = sessionId;
      }
      if (!response.ok) {
        const text = await response.text().catch(() => null);
        if (response.status === 401 && this._authProvider) {
          if (this._hasCompletedAuthFlow) {
            throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
          }
          const { resourceMetadataUrl, scope: scope2 } = extractWWWAuthenticateParams(response);
          this._resourceMetadataUrl = resourceMetadataUrl;
          this._scope = scope2;
          const result = await auth(this._authProvider, {
            serverUrl: this._url,
            resourceMetadataUrl: this._resourceMetadataUrl,
            scope: this._scope,
            fetchFn: this._fetchWithInit
          });
          if (result !== "AUTHORIZED") {
            throw new UnauthorizedError();
          }
          this._hasCompletedAuthFlow = true;
          return this.send(message);
        }
        if (response.status === 403 && this._authProvider) {
          const { resourceMetadataUrl, scope: scope2, error } = extractWWWAuthenticateParams(response);
          if (error === "insufficient_scope") {
            const wwwAuthHeader = response.headers.get("WWW-Authenticate");
            if (this._lastUpscopingHeader === wwwAuthHeader) {
              throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
            }
            if (scope2) {
              this._scope = scope2;
            }
            if (resourceMetadataUrl) {
              this._resourceMetadataUrl = resourceMetadataUrl;
            }
            this._lastUpscopingHeader = wwwAuthHeader ?? void 0;
            const result = await auth(this._authProvider, {
              serverUrl: this._url,
              resourceMetadataUrl: this._resourceMetadataUrl,
              scope: this._scope,
              fetchFn: this._fetch
            });
            if (result !== "AUTHORIZED") {
              throw new UnauthorizedError();
            }
            return this.send(message);
          }
        }
        throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
      }
      this._hasCompletedAuthFlow = false;
      this._lastUpscopingHeader = void 0;
      if (response.status === 202) {
        await response.body?.cancel();
        if (isInitializedNotification(message)) {
          this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(err));
        }
        return;
      }
      const messages = Array.isArray(message) ? message : [message];
      const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
      const contentType = response.headers.get("content-type");
      if (hasRequests) {
        if (contentType?.includes("text/event-stream")) {
          this._handleSseStream(response.body, { onresumptiontoken }, false);
        } else if (contentType?.includes("application/json")) {
          const data2 = await response.json();
          const responseMessages = Array.isArray(data2) ? data2.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data2)];
          for (const msg of responseMessages) {
            this.onmessage?.(msg);
          }
        } else {
          await response.body?.cancel();
          throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
        }
      } else {
        await response.body?.cancel();
      }
    } catch (error) {
      this.onerror?.(error);
      throw error;
    }
  }
  get sessionId() {
    return this._sessionId;
  }
  /**
   * Terminates the current session by sending a DELETE request to the server.
   *
   * Clients that no longer need a particular session
   * (e.g., because the user is leaving the client application) SHOULD send an
   * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
   * terminate the session.
   *
   * The server MAY respond with HTTP 405 Method Not Allowed, indicating that
   * the server does not allow clients to terminate sessions.
   */
  async terminateSession() {
    if (!this._sessionId) {
      return;
    }
    try {
      const headers = await this._commonHeaders();
      const init = {
        ...this._requestInit,
        method: "DELETE",
        headers,
        signal: this._abortController?.signal
      };
      const response = await (this._fetch ?? fetch)(this._url, init);
      await response.body?.cancel();
      if (!response.ok && response.status !== 405) {
        throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
      }
      this._sessionId = void 0;
    } catch (error) {
      this.onerror?.(error);
      throw error;
    }
  }
  setProtocolVersion(version2) {
    this._protocolVersion = version2;
  }
  get protocolVersion() {
    return this._protocolVersion;
  }
  /**
   * Resume an SSE stream from a previous event ID.
   * Opens a GET SSE connection with Last-Event-ID header to replay missed events.
   *
   * @param lastEventId The event ID to resume from
   * @param options Optional callback to receive new resumption tokens
   */
  async resumeStream(lastEventId, options) {
    await this._startOrAuthSse({
      resumptionToken: lastEventId,
      onresumptiontoken: options?.onresumptiontoken
    });
  }
}
function isPlainObject(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function mcpProxyTransportErrorDataIndicatesUnauthorized(data2) {
  if ("upstream401" in data2) {
    const snapshot = data2.upstream401;
    if (snapshot != null) return true;
  }
  const status = data2.httpStatus;
  return typeof status === "number" && status === 401;
}
function isConnectionAuthError(error) {
  if (error instanceof SseError && error.code === 401) return true;
  if (error instanceof StreamableHTTPError && error.code === 401) return true;
  if (error instanceof UnauthorizedError) return true;
  if (error instanceof McpError && error.code === MCP_PROXY_TRANSPORT_ERROR_CODE && isPlainObject(error.data) && mcpProxyTransportErrorDataIndicatesUnauthorized(error.data)) {
    return true;
  }
  return false;
}
function useConnection({
  transportType,
  command,
  args,
  sseUrl,
  env,
  customHeaders,
  oauthClientId,
  oauthClientSecret,
  oauthScope,
  config: config2,
  connectionType = "proxy",
  onNotification,
  onPendingRequest,
  onElicitationRequest,
  getRoots,
  defaultLoggingLevel,
  metadata: metadata2 = {}
}) {
  const [connectionStatus, setConnectionStatus] = reactExports.useState("disconnected");
  const { toast: toast2 } = useToast();
  const [serverCapabilities, setServerCapabilities] = reactExports.useState(null);
  const [mcpClient, setMcpClient] = reactExports.useState(null);
  const [clientTransport, setClientTransport] = reactExports.useState(
    null
  );
  const [requestHistory, setRequestHistory] = reactExports.useState([]);
  const [completionsSupported, setCompletionsSupported] = reactExports.useState(false);
  const [mcpSessionId, setMcpSessionId] = reactExports.useState(null);
  const [mcpProtocolVersion, setMcpProtocolVersion] = reactExports.useState(
    null
  );
  const [serverImplementation, setServerImplementation] = reactExports.useState(null);
  const receiverTasksRef = reactExports.useRef(/* @__PURE__ */ new Map());
  reactExports.useEffect(() => {
    if (!oauthClientId) {
      clearClientInformationFromSessionStorage({
        serverUrl: sseUrl,
        isPreregistered: true
      });
      return;
    }
    const clientInformation = {
      client_id: oauthClientId
    };
    if (oauthClientSecret) {
      clientInformation.client_secret = oauthClientSecret;
    }
    saveClientInformationToSessionStorage({
      serverUrl: sseUrl,
      clientInformation,
      isPreregistered: true
    });
  }, [oauthClientId, oauthClientSecret, sseUrl]);
  reactExports.useEffect(() => {
    if (!oauthScope) {
      clearScopeFromSessionStorage(sseUrl);
      return;
    }
    saveScopeToSessionStorage(sseUrl, oauthScope);
  }, [oauthScope, sseUrl]);
  const pushHistory = (request, response) => {
    setRequestHistory((prev) => [
      ...prev,
      {
        request: JSON.stringify(request),
        response: response !== void 0 ? JSON.stringify(response) : void 0
      }
    ]);
  };
  const makeRequest = async (request, schema, options) => {
    if (!mcpClient) {
      throw new Error("MCP client not connected");
    }
    try {
      const abortController = new AbortController();
      const shouldAddGeneralMetadata = request.method !== "tools/call" && Object.keys(metadata2).length > 0;
      const requestWithMetadata = shouldAddGeneralMetadata ? {
        ...request,
        params: {
          ...request.params,
          _meta: metadata2
        }
      } : request;
      const mcpRequestOptions = {
        signal: options?.signal ?? abortController.signal,
        resetTimeoutOnProgress: options?.resetTimeoutOnProgress ?? resetRequestTimeoutOnProgress(config2),
        timeout: options?.timeout ?? getMCPServerRequestTimeout(config2),
        maxTotalTimeout: options?.maxTotalTimeout ?? getMCPServerRequestMaxTotalTimeout(config2)
      };
      if (mcpRequestOptions.resetTimeoutOnProgress) {
        mcpRequestOptions.onprogress = (params) => {
          if (onNotification) {
            onNotification({
              method: "notifications/progress",
              params
            });
          }
        };
      }
      let response;
      try {
        response = await mcpClient.request(
          requestWithMetadata,
          schema,
          mcpRequestOptions
        );
        pushHistory(requestWithMetadata, response);
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        pushHistory(requestWithMetadata, { error: errorMessage });
        throw error;
      }
      return response;
    } catch (e2) {
      if (!options?.suppressToast) {
        const errorString = e2.message ?? String(e2);
        toast2({
          title: "Error",
          description: errorString,
          variant: "destructive"
        });
      }
      throw e2;
    }
  };
  const handleCompletion = async (ref2, argName, value, context, signal) => {
    if (!mcpClient || !completionsSupported) {
      return [];
    }
    const request = {
      method: "completion/complete",
      params: {
        argument: {
          name: argName,
          value
        },
        ref: ref2
      }
    };
    if (context) {
      request["params"]["context"] = {
        arguments: context
      };
    }
    try {
      const response = await makeRequest(request, CompleteResultSchema, {
        signal,
        suppressToast: true
      });
      return response?.completion.values || [];
    } catch (e2) {
      if (e2 instanceof McpError && e2.code === ErrorCode.MethodNotFound) {
        setCompletionsSupported(false);
        return [];
      }
      toast2({
        title: "Error",
        description: e2 instanceof Error ? e2.message : String(e2),
        variant: "destructive"
      });
      throw e2;
    }
  };
  const sendNotification = async (notification) => {
    if (!mcpClient) {
      const error = new Error("MCP client not connected");
      toast2({
        title: "Error",
        description: error.message,
        variant: "destructive"
      });
      throw error;
    }
    try {
      await mcpClient.notification(notification);
      pushHistory(notification);
    } catch (e2) {
      if (e2 instanceof McpError) {
        pushHistory(notification, { error: e2.message });
      }
      toast2({
        title: "Error",
        description: e2 instanceof Error ? e2.message : String(e2),
        variant: "destructive"
      });
      throw e2;
    }
  };
  const checkProxyHealth = async () => {
    try {
      const proxyHealthUrl = new URL(`${getMCPProxyAddress(config2)}/health`);
      const { token: proxyAuthToken, header: proxyAuthTokenHeader } = getMCPProxyAuthToken(config2);
      const headers = {};
      if (proxyAuthToken) {
        headers[proxyAuthTokenHeader] = `Bearer ${proxyAuthToken}`;
      }
      const proxyHealthResponse = await fetch(proxyHealthUrl, { headers });
      const proxyHealth = await proxyHealthResponse.json();
      if (proxyHealth?.status !== "ok") {
        throw new Error("MCP Proxy Server is not healthy");
      }
    } catch (e2) {
      console.error("Couldn't connect to MCP Proxy Server", e2);
      throw e2;
    }
  };
  const isProxyAuthError = (error) => {
    return error instanceof Error && error.message.includes("Authentication required. Use the session token");
  };
  const handleAuthError = async (error) => {
    if (isConnectionAuthError(error)) {
      let scope2 = oauthScope?.trim();
      const fetchFn = connectionType === "proxy" ? createProxyFetch(config2) : void 0;
      if (!scope2) {
        let resourceMetadata;
        try {
          resourceMetadata = await discoverOAuthProtectedResourceMetadata(
            new URL("/", sseUrl),
            {},
            fetchFn
          );
        } catch {
        }
        scope2 = await discoverScopes(sseUrl, resourceMetadata, fetchFn);
      }
      saveScopeToSessionStorage(sseUrl, scope2);
      const serverAuthProvider = new InspectorOAuthClientProvider(sseUrl);
      try {
        const result = await auth(serverAuthProvider, {
          serverUrl: sseUrl,
          scope: scope2,
          ...fetchFn && { fetchFn }
        });
        return result === "AUTHORIZED";
      } catch (authError) {
        toast2({
          title: "OAuth Authentication Failed",
          description: authError instanceof Error ? authError.message : String(authError),
          variant: "destructive"
        });
        return false;
      }
    }
    return false;
  };
  const captureResponseHeaders = (response) => {
    const sessionId = response.headers.get("mcp-session-id");
    const protocolVersion = response.headers.get("mcp-protocol-version");
    if (sessionId && sessionId !== mcpSessionId) {
      setMcpSessionId(sessionId);
    }
    if (protocolVersion && protocolVersion !== mcpProtocolVersion) {
      setMcpProtocolVersion(protocolVersion);
    }
  };
  const connect = async (_e2, retryCount = 0) => {
    const clientCapabilities = {
      capabilities: {
        sampling: {},
        elicitation: {
          form: {},
          url: {}
        },
        roots: {
          listChanged: true
        },
        tasks: {
          list: {},
          cancel: {},
          ...onPendingRequest || onElicitationRequest ? {
            requests: {
              ...onPendingRequest ? { sampling: { createMessage: {} } } : void 0,
              ...onElicitationRequest ? { elicitation: { create: {} } } : void 0
            }
          } : void 0
        }
      }
    };
    const client2 = new Client(
      CLIENT_IDENTITY,
      clientCapabilities
    );
    if (connectionType === "proxy") {
      try {
        await checkProxyHealth();
      } catch {
        setConnectionStatus("error-connecting-to-proxy");
        return;
      }
    }
    let lastRequest = "";
    try {
      const headers = {};
      const serverAuthProvider = new InspectorOAuthClientProvider(sseUrl);
      let finalHeaders = customHeaders || [];
      const isEmptyAuthHeader = (header) => header.name.trim().toLowerCase() === "authorization" && header.value.trim().toLowerCase() === "bearer";
      const hasEmptyAuthHeader = finalHeaders.some(
        (header) => header.enabled && isEmptyAuthHeader(header)
      );
      if (hasEmptyAuthHeader) {
        toast2({
          title: "Invalid Authorization Header",
          description: "Authorization header is enabled but empty. Please add a token or disable the header.",
          variant: "destructive"
        });
      }
      const needsOAuthToken = !finalHeaders.some(
        (header) => header.enabled && header.name.trim().toLowerCase() === "authorization"
      );
      if (needsOAuthToken) {
        const oauthToken = (await serverAuthProvider.tokens())?.access_token;
        if (oauthToken) {
          finalHeaders = [
            // Remove any existing Authorization headers with empty tokens
            ...finalHeaders.filter((header) => !isEmptyAuthHeader(header)),
            {
              name: "Authorization",
              value: `Bearer ${oauthToken}`,
              enabled: true
            }
          ];
        }
      }
      const customHeaderNames = [];
      finalHeaders.forEach((header) => {
        if (header.enabled && header.name.trim() && header.value.trim()) {
          const headerName = header.name.trim();
          const headerValue = header.value.trim();
          headers[headerName] = headerValue;
          if (headerName.toLowerCase() !== "authorization") {
            customHeaderNames.push(headerName);
          }
        }
      });
      if (customHeaderNames.length > 0) {
        headers["x-custom-auth-headers"] = JSON.stringify(customHeaderNames);
      }
      let transportOptions;
      let serverUrl;
      if (connectionType === "direct" && transportType !== "stdio") {
        serverUrl = new URL(sseUrl);
        const requestHeaders = { ...headers };
        if (mcpSessionId) {
          requestHeaders["mcp-session-id"] = mcpSessionId;
        }
        switch (transportType) {
          case "sse":
            requestHeaders["Accept"] = "text/event-stream";
            requestHeaders["content-type"] = "application/json";
            transportOptions = {
              authProvider: serverAuthProvider,
              fetch: async (url2, init) => {
                const response = await fetch(url2, {
                  ...init,
                  headers: requestHeaders
                });
                captureResponseHeaders(response);
                return response;
              },
              requestInit: {
                headers: requestHeaders
              }
            };
            break;
          case "streamable-http":
            transportOptions = {
              authProvider: serverAuthProvider,
              fetch: async (url2, init) => {
                requestHeaders["Accept"] = "text/event-stream, application/json";
                requestHeaders["Content-Type"] = "application/json";
                const response = await fetch(url2, {
                  headers: requestHeaders,
                  ...init
                });
                captureResponseHeaders(response);
                return response;
              },
              requestInit: {
                headers: requestHeaders
              },
              // TODO these should be configurable...
              reconnectionOptions: {
                maxReconnectionDelay: 3e4,
                initialReconnectionDelay: 1e3,
                reconnectionDelayGrowFactor: 1.5,
                maxRetries: 2
              }
            };
            break;
        }
      } else {
        const { token: proxyAuthToken, header: proxyAuthTokenHeader } = getMCPProxyAuthToken(config2);
        const proxyHeaders = {};
        if (proxyAuthToken) {
          proxyHeaders[proxyAuthTokenHeader] = `Bearer ${proxyAuthToken}`;
        }
        let mcpProxyServerUrl;
        switch (transportType) {
          case "stdio": {
            mcpProxyServerUrl = new URL(`${getMCPProxyAddress(config2)}/stdio`);
            mcpProxyServerUrl.searchParams.append("command", command);
            mcpProxyServerUrl.searchParams.append("args", args);
            mcpProxyServerUrl.searchParams.append("env", JSON.stringify(env));
            const proxyFullAddress = config2.MCP_PROXY_FULL_ADDRESS.value;
            if (proxyFullAddress) {
              mcpProxyServerUrl.searchParams.append(
                "proxyFullAddress",
                proxyFullAddress
              );
            }
            transportOptions = {
              authProvider: serverAuthProvider,
              eventSourceInit: {
                fetch: (url2, init) => fetch(url2, {
                  ...init,
                  headers: { ...headers, ...proxyHeaders }
                })
              },
              requestInit: {
                headers: { ...headers, ...proxyHeaders }
              }
            };
            break;
          }
          case "sse": {
            mcpProxyServerUrl = new URL(`${getMCPProxyAddress(config2)}/sse`);
            mcpProxyServerUrl.searchParams.append("url", sseUrl);
            const proxyFullAddressSSE = config2.MCP_PROXY_FULL_ADDRESS.value;
            if (proxyFullAddressSSE) {
              mcpProxyServerUrl.searchParams.append(
                "proxyFullAddress",
                proxyFullAddressSSE
              );
            }
            transportOptions = {
              authProvider: serverAuthProvider,
              eventSourceInit: {
                fetch: (url2, init) => fetch(url2, {
                  ...init,
                  headers: { ...headers, ...proxyHeaders }
                })
              },
              requestInit: {
                headers: { ...headers, ...proxyHeaders }
              }
            };
            break;
          }
          case "streamable-http":
            mcpProxyServerUrl = new URL(`${getMCPProxyAddress(config2)}/mcp`);
            mcpProxyServerUrl.searchParams.append("url", sseUrl);
            transportOptions = {
              authProvider: serverAuthProvider,
              eventSourceInit: {
                fetch: (url2, init) => fetch(url2, {
                  ...init,
                  headers: { ...headers, ...proxyHeaders }
                })
              },
              requestInit: {
                headers: { ...headers, ...proxyHeaders }
              },
              // TODO these should be configurable...
              reconnectionOptions: {
                maxReconnectionDelay: 3e4,
                initialReconnectionDelay: 1e3,
                reconnectionDelayGrowFactor: 1.5,
                maxRetries: 2
              }
            };
            break;
        }
        serverUrl = mcpProxyServerUrl;
        serverUrl.searchParams.append("transportType", transportType);
      }
      if (onNotification) {
        [
          CancelledNotificationSchema,
          LoggingMessageNotificationSchema,
          ResourceUpdatedNotificationSchema,
          ResourceListChangedNotificationSchema,
          ToolListChangedNotificationSchema,
          PromptListChangedNotificationSchema,
          TaskStatusNotificationSchema,
          // SEP-1036: elicitation/complete is surfaced in the notification panel
          // so the user can observe out-of-band completion. The Inspector does
          // not auto-correlate the notification's elicitationId back to its
          // pending request (a spec MAY); the user resolves the request manually
          // via the Accept button (the spec SHOULD).
          ElicitationCompleteNotificationSchema
        ].forEach((notificationSchema) => {
          client2.setNotificationHandler(notificationSchema, onNotification);
        });
        client2.fallbackNotificationHandler = (notification) => {
          onNotification(notification);
          return Promise.resolve();
        };
      }
      let capabilities;
      try {
        const transport = transportType === "streamable-http" ? new StreamableHTTPClientTransport(serverUrl, {
          sessionId: void 0,
          ...transportOptions
        }) : new SSEClientTransport(serverUrl, transportOptions);
        await client2.connect(transport);
        const protocolOnMessage = transport.onmessage;
        if (protocolOnMessage) {
          transport.onmessage = (message) => {
            const resolvedMessage = resolveRefsInMessage(message);
            protocolOnMessage(resolvedMessage);
          };
        }
        setClientTransport(transport);
        capabilities = client2.getServerCapabilities();
        const serverInfo = client2.getServerVersion();
        setServerImplementation(serverInfo || null);
        const initializeRequest = {
          method: "initialize"
        };
        pushHistory(initializeRequest, {
          capabilities,
          serverInfo: client2.getServerVersion(),
          instructions: client2.getInstructions()
        });
      } catch (error) {
        console.error(
          connectionType === "direct" ? `Failed to connect directly to MCP Server at: ${serverUrl}:` : `Failed to connect to MCP Server via the MCP Inspector Proxy: ${serverUrl}:`,
          error
        );
        if (isProxyAuthError(error)) {
          toast2({
            title: "Proxy Authentication Required",
            description: "Please enter the session token from the proxy server console in the Configuration settings.",
            variant: "destructive"
          });
          setConnectionStatus("error");
          return;
        }
        const shouldRetry = await handleAuthError(error);
        if (shouldRetry) {
          return connect(void 0, retryCount + 1);
        }
        if (isConnectionAuthError(error)) {
          return;
        }
        throw error;
      }
      setServerCapabilities(capabilities ?? null);
      setCompletionsSupported(capabilities?.completions !== void 0);
      const nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
      const makeTaskId = () => {
        const cryptoAny = globalThis.crypto;
        return cryptoAny?.randomUUID?.() ?? `task_${Date.now()}_${Math.random().toString(16).slice(2)}`;
      };
      const emitTaskStatus = async (task) => {
        try {
          const notification = {
            method: "notifications/tasks/status",
            params: task
          };
          await client2.notification(notification);
          pushHistory(notification);
        } catch (e2) {
          console.warn("Failed to send notifications/tasks/status", e2);
        }
      };
      const upsertReceiverTask = async (task) => {
        const record2 = receiverTasksRef.current.get(task.taskId);
        if (record2) {
          receiverTasksRef.current.set(task.taskId, { ...record2, task });
        }
        await emitTaskStatus(task);
      };
      const createReceiverTask = (opts) => {
        const taskId = makeTaskId();
        const createdAt = nowIso();
        const ttl = opts.ttl ?? getMCPTaskTtl(config2);
        let resolvePayload = () => void 0;
        let rejectPayload = () => void 0;
        const payloadPromise = new Promise((resolve2, reject) => {
          resolvePayload = resolve2;
          rejectPayload = reject;
        });
        const task = {
          taskId,
          status: opts.initialStatus,
          ttl,
          createdAt,
          lastUpdatedAt: createdAt,
          ...opts.pollInterval !== void 0 ? { pollInterval: opts.pollInterval } : void 0,
          ...opts.statusMessage ? { statusMessage: opts.statusMessage } : {}
        };
        const record2 = {
          task,
          payloadPromise,
          resolvePayload,
          rejectPayload
        };
        if (ttl !== null && ttl > 0) {
          record2.cleanupTimeoutId = setTimeout(() => {
            receiverTasksRef.current.delete(taskId);
          }, ttl);
        }
        receiverTasksRef.current.set(taskId, record2);
        void emitTaskStatus(task);
        return record2;
      };
      client2.setRequestHandler(ListTasksRequestSchema, async () => {
        return {
          tasks: Array.from(receiverTasksRef.current.values()).map(
            (r2) => r2.task
          )
        };
      });
      client2.setRequestHandler(GetTaskRequestSchema, async (request) => {
        const record2 = receiverTasksRef.current.get(request.params.taskId);
        if (!record2) {
          throw new McpError(
            ErrorCode.InvalidParams,
            `Unknown taskId: ${request.params.taskId}`
          );
        }
        return record2.task;
      });
      client2.setRequestHandler(GetTaskPayloadRequestSchema, async (request) => {
        const record2 = receiverTasksRef.current.get(request.params.taskId);
        if (!record2) {
          throw new McpError(
            ErrorCode.InvalidParams,
            `Unknown taskId: ${request.params.taskId}`
          );
        }
        return await record2.payloadPromise;
      });
      client2.setRequestHandler(CancelTaskRequestSchema, async (request) => {
        const record2 = receiverTasksRef.current.get(request.params.taskId);
        if (!record2) {
          throw new McpError(
            ErrorCode.InvalidParams,
            `Unknown taskId: ${request.params.taskId}`
          );
        }
        const terminalStatuses = [
          "completed",
          "failed",
          "cancelled"
        ];
        if (!terminalStatuses.includes(record2.task.status)) {
          const updated = {
            ...record2.task,
            status: "cancelled",
            lastUpdatedAt: nowIso(),
            statusMessage: "Cancelled"
          };
          receiverTasksRef.current.set(request.params.taskId, {
            ...record2,
            task: updated
          });
          record2.rejectPayload(
            new McpError(ErrorCode.InternalError, "Task was cancelled")
          );
          await emitTaskStatus(updated);
        }
        return receiverTasksRef.current.get(request.params.taskId).task;
      });
      if (onPendingRequest) {
        client2.setRequestHandler(CreateMessageRequestSchema, (request) => {
          const taskSpec = request.params?.task;
          if (!taskSpec) {
            return new Promise((resolve2, reject) => {
              onPendingRequest(request, resolve2, reject);
            });
          }
          const record2 = createReceiverTask({
            ttl: taskSpec.ttl,
            initialStatus: "input_required",
            statusMessage: "Awaiting user input"
          });
          void (async () => {
            try {
              const payload = await new Promise((resolve2, reject) => {
                onPendingRequest(request, resolve2, reject);
              });
              record2.resolvePayload(payload);
              const updated = {
                ...record2.task,
                status: "completed",
                lastUpdatedAt: nowIso()
              };
              receiverTasksRef.current.set(record2.task.taskId, {
                ...record2,
                task: updated
              });
              await upsertReceiverTask(updated);
            } catch (e2) {
              record2.rejectPayload(e2);
              const updated = {
                ...record2.task,
                status: "failed",
                lastUpdatedAt: nowIso(),
                statusMessage: e2 instanceof Error ? e2.message : "Task failed"
              };
              receiverTasksRef.current.set(record2.task.taskId, {
                ...record2,
                task: updated
              });
              await upsertReceiverTask(updated);
            }
          })();
          const createTaskResult = {
            task: record2.task
          };
          return createTaskResult;
        });
      }
      if (getRoots) {
        client2.setRequestHandler(ListRootsRequestSchema, async () => {
          return { roots: getRoots() };
        });
      }
      if (onElicitationRequest) {
        client2.setRequestHandler(ElicitRequestSchema, (request) => {
          const taskSpec = request.params?.task;
          if (!taskSpec) {
            return new Promise((resolve2) => {
              onElicitationRequest(request, resolve2);
            });
          }
          const record2 = createReceiverTask({
            ttl: taskSpec.ttl,
            initialStatus: "input_required",
            statusMessage: "Awaiting user input"
          });
          void (async () => {
            try {
              const payload = await new Promise((resolve2) => {
                onElicitationRequest(request, resolve2);
              });
              record2.resolvePayload(payload);
              const updated = {
                ...record2.task,
                status: "completed",
                lastUpdatedAt: nowIso()
              };
              receiverTasksRef.current.set(record2.task.taskId, {
                ...record2,
                task: updated
              });
              await upsertReceiverTask(updated);
            } catch (e2) {
              record2.rejectPayload(e2);
              const updated = {
                ...record2.task,
                status: "failed",
                lastUpdatedAt: nowIso(),
                statusMessage: e2 instanceof Error ? e2.message : "Task failed"
              };
              receiverTasksRef.current.set(record2.task.taskId, {
                ...record2,
                task: updated
              });
              await upsertReceiverTask(updated);
            }
          })();
          const createTaskResult = {
            task: record2.task
          };
          return createTaskResult;
        });
      }
      if (capabilities?.logging && defaultLoggingLevel) {
        lastRequest = "logging/setLevel";
        await client2.setLoggingLevel(defaultLoggingLevel);
        pushHistory(
          {
            method: "logging/setLevel",
            params: {
              level: defaultLoggingLevel
            }
          },
          {}
        );
        lastRequest = "";
      }
      setMcpClient(client2);
      setConnectionStatus("connected");
    } catch (e2) {
      if (lastRequest === "logging/setLevel" && e2 instanceof McpError && e2.code === ErrorCode.MethodNotFound) {
        toast2({
          title: "Error",
          description: `Server declares logging capability but doesn't implement method: "${lastRequest}"`,
          variant: "destructive"
        });
      } else {
        toast2({
          title: "Connection error",
          description: `Connection failed: "${e2}"`,
          variant: "destructive"
        });
      }
      console.error(e2);
      setConnectionStatus("error");
    }
  };
  const cancelTask = async (taskId) => {
    return makeRequest(
      {
        method: "tasks/cancel",
        params: { taskId }
      },
      CancelTaskResultSchema
    );
  };
  const listTasks = async (cursor) => {
    return makeRequest(
      {
        method: "tasks/list",
        params: { cursor }
      },
      ListTasksResultSchema
    );
  };
  const disconnect = async () => {
    receiverTasksRef.current.forEach((record2) => {
      if (record2.cleanupTimeoutId) {
        clearTimeout(record2.cleanupTimeoutId);
      }
    });
    receiverTasksRef.current.clear();
    if (transportType === "streamable-http")
      await clientTransport.terminateSession();
    await mcpClient?.close();
    const authProvider = new InspectorOAuthClientProvider(sseUrl);
    authProvider.clear();
    setMcpClient(null);
    setClientTransport(null);
    setConnectionStatus("disconnected");
    setCompletionsSupported(false);
    setServerCapabilities(null);
    setMcpSessionId(null);
    setMcpProtocolVersion(null);
  };
  const clearRequestHistory = () => {
    setRequestHistory([]);
    setServerImplementation(null);
  };
  return {
    connectionStatus,
    serverCapabilities,
    serverImplementation,
    mcpClient,
    requestHistory,
    clearRequestHistory,
    makeRequest,
    cancelTask,
    listTasks,
    sendNotification,
    handleCompletion,
    completionsSupported,
    connect,
    disconnect
  };
}
function useDraggablePane(initialHeight) {
  const [height, setHeight] = reactExports.useState(initialHeight);
  const [isDragging, setIsDragging] = reactExports.useState(false);
  const dragStartY = reactExports.useRef(0);
  const dragStartHeight = reactExports.useRef(0);
  const handleDragStart = reactExports.useCallback(
    (e2) => {
      setIsDragging(true);
      dragStartY.current = e2.clientY;
      dragStartHeight.current = height;
      document.body.style.userSelect = "none";
    },
    [height]
  );
  const handleDragMove = reactExports.useCallback(
    (e2) => {
      if (!isDragging) return;
      const deltaY = dragStartY.current - e2.clientY;
      const newHeight = Math.max(
        100,
        Math.min(800, dragStartHeight.current + deltaY)
      );
      setHeight(newHeight);
    },
    [isDragging]
  );
  const handleDragEnd = reactExports.useCallback(() => {
    setIsDragging(false);
    document.body.style.userSelect = "";
  }, []);
  reactExports.useEffect(() => {
    if (isDragging) {
      window.addEventListener("mousemove", handleDragMove);
      window.addEventListener("mouseup", handleDragEnd);
      return () => {
        window.removeEventListener("mousemove", handleDragMove);
        window.removeEventListener("mouseup", handleDragEnd);
      };
    }
  }, [isDragging, handleDragMove, handleDragEnd]);
  return {
    height,
    isDragging,
    handleDragStart
  };
}
function useDraggableSidebar(initialWidth) {
  const [width, setWidth] = reactExports.useState(initialWidth);
  const [isDragging, setIsDragging] = reactExports.useState(false);
  const dragStartX = reactExports.useRef(0);
  const dragStartWidth = reactExports.useRef(0);
  const handleDragStart = reactExports.useCallback(
    (e2) => {
      setIsDragging(true);
      dragStartX.current = e2.clientX;
      dragStartWidth.current = width;
      document.body.style.userSelect = "none";
    },
    [width]
  );
  const handleDragMove = reactExports.useCallback(
    (e2) => {
      if (!isDragging) return;
      const deltaX = e2.clientX - dragStartX.current;
      const newWidth = Math.max(
        200,
        Math.min(600, dragStartWidth.current + deltaX)
      );
      setWidth(newWidth);
    },
    [isDragging]
  );
  const handleDragEnd = reactExports.useCallback(() => {
    setIsDragging(false);
    document.body.style.userSelect = "";
  }, []);
  reactExports.useEffect(() => {
    if (isDragging) {
      window.addEventListener("mousemove", handleDragMove);
      window.addEventListener("mouseup", handleDragEnd);
      return () => {
        window.removeEventListener("mousemove", handleDragMove);
        window.removeEventListener("mouseup", handleDragEnd);
      };
    }
  }, [isDragging, handleDragMove, handleDragEnd]);
  return {
    width,
    isDragging,
    handleDragStart
  };
}
var useReactId = React$1[" useId ".trim().toString()] || (() => void 0);
var count$1 = 0;
function useId(deterministicId) {
  const [id2, setId] = reactExports.useState(useReactId());
  useLayoutEffect2(() => {
    setId((reactId) => reactId ?? String(count$1++));
  }, [deterministicId]);
  return id2 ? `radix-${id2}` : "";
}
var DirectionContext = reactExports.createContext(void 0);
function useDirection(localDir) {
  const globalDir = reactExports.useContext(DirectionContext);
  return localDir || globalDir || "ltr";
}
var ENTRY_FOCUS = "rovingFocusGroup.onEntryFocus";
var EVENT_OPTIONS$1 = { bubbles: false, cancelable: true };
var GROUP_NAME$1 = "RovingFocusGroup";
var [Collection$1, useCollection$1, createCollectionScope$1] = createCollection(GROUP_NAME$1);
var [createRovingFocusGroupContext, createRovingFocusGroupScope] = createContextScope(
  GROUP_NAME$1,
  [createCollectionScope$1]
);
var [RovingFocusProvider, useRovingFocusContext] = createRovingFocusGroupContext(GROUP_NAME$1);
var RovingFocusGroup = reactExports.forwardRef(
  (props, forwardedRef) => {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Collection$1.Provider, { scope: props.__scopeRovingFocusGroup, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Collection$1.Slot, { scope: props.__scopeRovingFocusGroup, children: /* @__PURE__ */ jsxRuntimeExports.jsx(RovingFocusGroupImpl, { ...props, ref: forwardedRef }) }) });
  }
);
RovingFocusGroup.displayName = GROUP_NAME$1;
var RovingFocusGroupImpl = reactExports.forwardRef((props, forwardedRef) => {
  const {
    __scopeRovingFocusGroup,
    orientation,
    loop = false,
    dir,
    currentTabStopId: currentTabStopIdProp,
    defaultCurrentTabStopId,
    onCurrentTabStopIdChange,
    onEntryFocus,
    preventScrollOnEntryFocus = false,
    ...groupProps
  } = props;
  const ref2 = reactExports.useRef(null);
  const composedRefs = useComposedRefs(forwardedRef, ref2);
  const direction = useDirection(dir);
  const [currentTabStopId, setCurrentTabStopId] = useControllableState({
    prop: currentTabStopIdProp,
    defaultProp: defaultCurrentTabStopId ?? null,
    onChange: onCurrentTabStopIdChange,
    caller: GROUP_NAME$1
  });
  const [isTabbingBackOut, setIsTabbingBackOut] = reactExports.useState(false);
  const handleEntryFocus = useCallbackRef$1(onEntryFocus);
  const getItems = useCollection$1(__scopeRovingFocusGroup);
  const isClickFocusRef = reactExports.useRef(false);
  const [focusableItemsCount, setFocusableItemsCount] = reactExports.useState(0);
  reactExports.useEffect(() => {
    const node = ref2.current;
    if (node) {
      node.addEventListener(ENTRY_FOCUS, handleEntryFocus);
      return () => node.removeEventListener(ENTRY_FOCUS, handleEntryFocus);
    }
  }, [handleEntryFocus]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    RovingFocusProvider,
    {
      scope: __scopeRovingFocusGroup,
      orientation,
      dir: direction,
      loop,
      currentTabStopId,
      onItemFocus: reactExports.useCallback(
        (tabStopId) => setCurrentTabStopId(tabStopId),
        [setCurrentTabStopId]
      ),
      onItemShiftTab: reactExports.useCallback(() => setIsTabbingBackOut(true), []),
      onFocusableItemAdd: reactExports.useCallback(
        () => setFocusableItemsCount((prevCount) => prevCount + 1),
        []
      ),
      onFocusableItemRemove: reactExports.useCallback(
        () => setFocusableItemsCount((prevCount) => prevCount - 1),
        []
      ),
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Primitive$1.div,
        {
          tabIndex: isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0,
          "data-orientation": orientation,
          ...groupProps,
          ref: composedRefs,
          style: { outline: "none", ...props.style },
          onMouseDown: composeEventHandlers(props.onMouseDown, () => {
            isClickFocusRef.current = true;
          }),
          onFocus: composeEventHandlers(props.onFocus, (event) => {
            const isKeyboardFocus = !isClickFocusRef.current;
            if (event.target === event.currentTarget && isKeyboardFocus && !isTabbingBackOut) {
              const entryFocusEvent = new CustomEvent(ENTRY_FOCUS, EVENT_OPTIONS$1);
              event.currentTarget.dispatchEvent(entryFocusEvent);
              if (!entryFocusEvent.defaultPrevented) {
                const items2 = getItems().filter((item) => item.focusable);
                const activeItem = items2.find((item) => item.active);
                const currentItem = items2.find((item) => item.id === currentTabStopId);
                const candidateItems = [activeItem, currentItem, ...items2].filter(
                  Boolean
                );
                const candidateNodes = candidateItems.map((item) => item.ref.current);
                focusFirst$1(candidateNodes, preventScrollOnEntryFocus);
              }
            }
            isClickFocusRef.current = false;
          }),
          onBlur: composeEventHandlers(props.onBlur, () => setIsTabbingBackOut(false))
        }
      )
    }
  );
});
var ITEM_NAME$1 = "RovingFocusGroupItem";
var RovingFocusGroupItem = reactExports.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeRovingFocusGroup,
      focusable = true,
      active = false,
      tabStopId,
      children,
      ...itemProps
    } = props;
    const autoId = useId();
    const id2 = tabStopId || autoId;
    const context = useRovingFocusContext(ITEM_NAME$1, __scopeRovingFocusGroup);
    const isCurrentTabStop = context.currentTabStopId === id2;
    const getItems = useCollection$1(__scopeRovingFocusGroup);
    const { onFocusableItemAdd, onFocusableItemRemove, currentTabStopId } = context;
    reactExports.useEffect(() => {
      if (focusable) {
        onFocusableItemAdd();
        return () => onFocusableItemRemove();
      }
    }, [focusable, onFocusableItemAdd, onFocusableItemRemove]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Collection$1.ItemSlot,
      {
        scope: __scopeRovingFocusGroup,
        id: id2,
        focusable,
        active,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Primitive$1.span,
          {
            tabIndex: isCurrentTabStop ? 0 : -1,
            "data-orientation": context.orientation,
            ...itemProps,
            ref: forwardedRef,
            onMouseDown: composeEventHandlers(props.onMouseDown, (event) => {
              if (!focusable) event.preventDefault();
              else context.onItemFocus(id2);
            }),
            onFocus: composeEventHandlers(props.onFocus, () => context.onItemFocus(id2)),
            onKeyDown: composeEventHandlers(props.onKeyDown, (event) => {
              if (event.key === "Tab" && event.shiftKey) {
                context.onItemShiftTab();
                return;
              }
              if (event.target !== event.currentTarget) return;
              const focusIntent = getFocusIntent(event, context.orientation, context.dir);
              if (focusIntent !== void 0) {
                if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
                event.preventDefault();
                const items2 = getItems().filter((item) => item.focusable);
                let candidateNodes = items2.map((item) => item.ref.current);
                if (focusIntent === "last") candidateNodes.reverse();
                else if (focusIntent === "prev" || focusIntent === "next") {
                  if (focusIntent === "prev") candidateNodes.reverse();
                  const currentIndex = candidateNodes.indexOf(event.currentTarget);
                  candidateNodes = context.loop ? wrapArray$1(candidateNodes, currentIndex + 1) : candidateNodes.slice(currentIndex + 1);
                }
                setTimeout(() => focusFirst$1(candidateNodes));
              }
            }),
            children: typeof children === "function" ? children({ isCurrentTabStop, hasTabStop: currentTabStopId != null }) : children
          }
        )
      }
    );
  }
);
RovingFocusGroupItem.displayName = ITEM_NAME$1;
var MAP_KEY_TO_FOCUS_INTENT = {
  ArrowLeft: "prev",
  ArrowUp: "prev",
  ArrowRight: "next",
  ArrowDown: "next",
  PageUp: "first",
  Home: "first",
  PageDown: "last",
  End: "last"
};
function getDirectionAwareKey(key, dir) {
  if (dir !== "rtl") return key;
  return key === "ArrowLeft" ? "ArrowRight" : key === "ArrowRight" ? "ArrowLeft" : key;
}
function getFocusIntent(event, orientation, dir) {
  const key = getDirectionAwareKey(event.key, dir);
  if (orientation === "vertical" && ["ArrowLeft", "ArrowRight"].includes(key)) return void 0;
  if (orientation === "horizontal" && ["ArrowUp", "ArrowDown"].includes(key)) return void 0;
  return MAP_KEY_TO_FOCUS_INTENT[key];
}
function focusFirst$1(candidates, preventScroll = false) {
  const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;
  for (const candidate of candidates) {
    if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return;
    candidate.focus({ preventScroll });
    if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return;
  }
}
function wrapArray$1(array2, startIndex) {
  return array2.map((_2, index2) => array2[(startIndex + index2) % array2.length]);
}
var Root$4 = RovingFocusGroup;
var Item$1 = RovingFocusGroupItem;
var TABS_NAME = "Tabs";
var [createTabsContext] = createContextScope(TABS_NAME, [
  createRovingFocusGroupScope
]);
var useRovingFocusGroupScope = createRovingFocusGroupScope();
var [TabsProvider, useTabsContext] = createTabsContext(TABS_NAME);
var Tabs$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeTabs,
      value: valueProp,
      onValueChange,
      defaultValue,
      orientation = "horizontal",
      dir,
      activationMode = "automatic",
      ...tabsProps
    } = props;
    const direction = useDirection(dir);
    const [value, setValue] = useControllableState({
      prop: valueProp,
      onChange: onValueChange,
      defaultProp: defaultValue ?? "",
      caller: TABS_NAME
    });
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      TabsProvider,
      {
        scope: __scopeTabs,
        baseId: useId(),
        value,
        onValueChange: setValue,
        orientation,
        dir: direction,
        activationMode,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Primitive$1.div,
          {
            dir: direction,
            "data-orientation": orientation,
            ...tabsProps,
            ref: forwardedRef
          }
        )
      }
    );
  }
);
Tabs$1.displayName = TABS_NAME;
var TAB_LIST_NAME = "TabsList";
var TabsList$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeTabs, loop = true, ...listProps } = props;
    const context = useTabsContext(TAB_LIST_NAME, __scopeTabs);
    const rovingFocusGroupScope = useRovingFocusGroupScope(__scopeTabs);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Root$4,
      {
        asChild: true,
        ...rovingFocusGroupScope,
        orientation: context.orientation,
        dir: context.dir,
        loop,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Primitive$1.div,
          {
            role: "tablist",
            "aria-orientation": context.orientation,
            ...listProps,
            ref: forwardedRef
          }
        )
      }
    );
  }
);
TabsList$1.displayName = TAB_LIST_NAME;
var TRIGGER_NAME$5 = "TabsTrigger";
var TabsTrigger$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeTabs, value, disabled = false, ...triggerProps } = props;
    const context = useTabsContext(TRIGGER_NAME$5, __scopeTabs);
    const rovingFocusGroupScope = useRovingFocusGroupScope(__scopeTabs);
    const triggerId = makeTriggerId(context.baseId, value);
    const contentId = makeContentId(context.baseId, value);
    const isSelected = value === context.value;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Item$1,
      {
        asChild: true,
        ...rovingFocusGroupScope,
        focusable: !disabled,
        active: isSelected,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Primitive$1.button,
          {
            type: "button",
            role: "tab",
            "aria-selected": isSelected,
            "aria-controls": contentId,
            "data-state": isSelected ? "active" : "inactive",
            "data-disabled": disabled ? "" : void 0,
            disabled,
            id: triggerId,
            ...triggerProps,
            ref: forwardedRef,
            onMouseDown: composeEventHandlers(props.onMouseDown, (event) => {
              if (!disabled && event.button === 0 && event.ctrlKey === false) {
                context.onValueChange(value);
              } else {
                event.preventDefault();
              }
            }),
            onKeyDown: composeEventHandlers(props.onKeyDown, (event) => {
              if ([" ", "Enter"].includes(event.key)) context.onValueChange(value);
            }),
            onFocus: composeEventHandlers(props.onFocus, () => {
              const isAutomaticActivation = context.activationMode !== "manual";
              if (!isSelected && !disabled && isAutomaticActivation) {
                context.onValueChange(value);
              }
            })
          }
        )
      }
    );
  }
);
TabsTrigger$1.displayName = TRIGGER_NAME$5;
var CONTENT_NAME$5 = "TabsContent";
var TabsContent$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeTabs, value, forceMount, children, ...contentProps } = props;
    const context = useTabsContext(CONTENT_NAME$5, __scopeTabs);
    const triggerId = makeTriggerId(context.baseId, value);
    const contentId = makeContentId(context.baseId, value);
    const isSelected = value === context.value;
    const isMountAnimationPreventedRef = reactExports.useRef(isSelected);
    reactExports.useEffect(() => {
      const rAF = requestAnimationFrame(() => isMountAnimationPreventedRef.current = false);
      return () => cancelAnimationFrame(rAF);
    }, []);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Presence, { present: forceMount || isSelected, children: ({ present }) => /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.div,
      {
        "data-state": isSelected ? "active" : "inactive",
        "data-orientation": context.orientation,
        role: "tabpanel",
        "aria-labelledby": triggerId,
        hidden: !present,
        id: contentId,
        tabIndex: 0,
        ...contentProps,
        ref: forwardedRef,
        style: {
          ...props.style,
          animationDuration: isMountAnimationPreventedRef.current ? "0s" : void 0
        },
        children: present && children
      }
    ) });
  }
);
TabsContent$1.displayName = CONTENT_NAME$5;
function makeTriggerId(baseId, value) {
  return `${baseId}-trigger-${value}`;
}
function makeContentId(baseId, value) {
  return `${baseId}-content-${value}`;
}
var Root2$3 = Tabs$1;
var List = TabsList$1;
var Trigger$3 = TabsTrigger$1;
var Content$2 = TabsContent$1;
const Tabs = Root2$3;
const TabsList = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  List,
  {
    ref: ref2,
    className: cn$1(
      "inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",
      className
    ),
    ...props
  }
));
TabsList.displayName = List.displayName;
const TabsTrigger = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Trigger$3,
  {
    ref: ref2,
    className: cn$1(
      "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-muted data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",
      className
    ),
    ...props
  }
));
TabsTrigger.displayName = Trigger$3.displayName;
const TabsContent = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Content$2,
  {
    ref: ref2,
    className: cn$1(
      "mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
      className
    ),
    ...props
  }
));
TabsContent.displayName = Content$2.displayName;
var REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy");
var use = React$1[" use ".trim().toString()];
function isPromiseLike(value) {
  return typeof value === "object" && value !== null && "then" in value;
}
function isLazyComponent(element) {
  return element != null && typeof element === "object" && "$$typeof" in element && element.$$typeof === REACT_LAZY_TYPE && "_payload" in element && isPromiseLike(element._payload);
}
// @__NO_SIDE_EFFECTS__
function createSlot$3(ownerName) {
  const SlotClone = /* @__PURE__ */ createSlotClone$3(ownerName);
  const Slot2 = reactExports.forwardRef((props, forwardedRef) => {
    let { children, ...slotProps } = props;
    if (isLazyComponent(children) && typeof use === "function") {
      children = use(children._payload);
    }
    const childrenArray = reactExports.Children.toArray(children);
    const slottable = childrenArray.find(isSlottable$3);
    if (slottable) {
      const newElement = slottable.props.children;
      const newChildren = childrenArray.map((child) => {
        if (child === slottable) {
          if (reactExports.Children.count(newElement) > 1) return reactExports.Children.only(null);
          return reactExports.isValidElement(newElement) ? newElement.props.children : null;
        } else {
          return child;
        }
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children: reactExports.isValidElement(newElement) ? reactExports.cloneElement(newElement, void 0, newChildren) : null });
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children });
  });
  Slot2.displayName = `${ownerName}.Slot`;
  return Slot2;
}
var Slot$3 = /* @__PURE__ */ createSlot$3("Slot");
// @__NO_SIDE_EFFECTS__
function createSlotClone$3(ownerName) {
  const SlotClone = reactExports.forwardRef((props, forwardedRef) => {
    let { children, ...slotProps } = props;
    if (isLazyComponent(children) && typeof use === "function") {
      children = use(children._payload);
    }
    if (reactExports.isValidElement(children)) {
      const childrenRef = getElementRef$3(children);
      const props2 = mergeProps$3(slotProps, children.props);
      if (children.type !== reactExports.Fragment) {
        props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;
      }
      return reactExports.cloneElement(children, props2);
    }
    return reactExports.Children.count(children) > 1 ? reactExports.Children.only(null) : null;
  });
  SlotClone.displayName = `${ownerName}.SlotClone`;
  return SlotClone;
}
var SLOTTABLE_IDENTIFIER$4 = /* @__PURE__ */ Symbol("radix.slottable");
function isSlottable$3(child) {
  return reactExports.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER$4;
}
function mergeProps$3(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          const result = childPropValue(...args);
          slotPropValue(...args);
          return result;
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef$3(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}
const buttonVariants = cva(
  "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
  {
    variants: {
      variant: {
        default: "bg-primary text-primary-foreground shadow hover:bg-primary/90 dark:bg-gray-800 dark:text-white dark:hover:bg-gray-700",
        destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
        outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
        secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
        ghost: "hover:bg-accent hover:text-accent-foreground",
        link: "text-primary underline-offset-4 hover:underline"
      },
      size: {
        default: "h-9 px-4 py-2",
        sm: "h-8 rounded-md px-3 text-xs",
        lg: "h-10 rounded-md px-8",
        icon: "h-9 w-9"
      }
    },
    defaultVariants: {
      variant: "default",
      size: "default"
    }
  }
);
const Button = reactExports.forwardRef(
  ({ className, variant, size: size2, asChild = false, ...props }, ref2) => {
    const Comp = asChild ? Slot$3 : "button";
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Comp,
      {
        className: cn$1(buttonVariants({ variant, size: size2, className })),
        ref: ref2,
        ...props
      }
    );
  }
);
Button.displayName = "Button";
const toKebabCase = (string2) => string2.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
const toCamelCase = (string2) => string2.replace(
  /^([A-Z])|[\s-_]+(\w)/g,
  (match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase()
);
const toPascalCase = (string2) => {
  const camelCase = toCamelCase(string2);
  return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
};
const mergeClasses = (...classes) => classes.filter((className, index2, array2) => {
  return Boolean(className) && className.trim() !== "" && array2.indexOf(className) === index2;
}).join(" ").trim();
const hasA11yProp = (props) => {
  for (const prop in props) {
    if (prop.startsWith("aria-") || prop === "role" || prop === "title") {
      return true;
    }
  }
};
var defaultAttributes = {
  xmlns: "http://www.w3.org/2000/svg",
  width: 24,
  height: 24,
  viewBox: "0 0 24 24",
  fill: "none",
  stroke: "currentColor",
  strokeWidth: 2,
  strokeLinecap: "round",
  strokeLinejoin: "round"
};
const Icon$1 = reactExports.forwardRef(
  ({
    color = "currentColor",
    size: size2 = 24,
    strokeWidth = 2,
    absoluteStrokeWidth,
    className = "",
    children,
    iconNode,
    ...rest
  }, ref2) => reactExports.createElement(
    "svg",
    {
      ref: ref2,
      ...defaultAttributes,
      width: size2,
      height: size2,
      stroke: color,
      strokeWidth: absoluteStrokeWidth ? Number(strokeWidth) * 24 / Number(size2) : strokeWidth,
      className: mergeClasses("lucide", className),
      ...!children && !hasA11yProp(rest) && { "aria-hidden": "true" },
      ...rest
    },
    [
      ...iconNode.map(([tag, attrs]) => reactExports.createElement(tag, attrs)),
      ...Array.isArray(children) ? children : [children]
    ]
  )
);
const createLucideIcon = (iconName, iconNode) => {
  const Component = reactExports.forwardRef(
    ({ className, ...props }, ref2) => reactExports.createElement(Icon$1, {
      ref: ref2,
      iconNode,
      className: mergeClasses(
        `lucide-${toKebabCase(toPascalCase(iconName))}`,
        `lucide-${iconName}`,
        className
      ),
      ...props
    })
  );
  Component.displayName = toPascalCase(iconName);
  return Component;
};
const __iconNode$J = [
  ["rect", { x: "2", y: "4", width: "20", height: "16", rx: "2", key: "izxlao" }],
  ["path", { d: "M10 4v4", key: "pp8u80" }],
  ["path", { d: "M2 8h20", key: "d11cs7" }],
  ["path", { d: "M6 4v4", key: "1svtjw" }]
];
const AppWindow = createLucideIcon("app-window", __iconNode$J);
const __iconNode$I = [
  ["path", { d: "M10.268 21a2 2 0 0 0 3.464 0", key: "vwvbt9" }],
  [
    "path",
    {
      d: "M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",
      key: "11g9vi"
    }
  ]
];
const Bell = createLucideIcon("bell", __iconNode$I);
const __iconNode$H = [
  ["path", { d: "m8 2 1.88 1.88", key: "fmnt4t" }],
  ["path", { d: "M14.12 3.88 16 2", key: "qol33r" }],
  ["path", { d: "M9 7.13v-1a3.003 3.003 0 1 1 6 0v1", key: "d7y7pr" }],
  [
    "path",
    {
      d: "M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6",
      key: "xs1cw7"
    }
  ],
  ["path", { d: "M12 20v-9", key: "1qisl0" }],
  ["path", { d: "M6.53 9C4.6 8.8 3 7.1 3 5", key: "32zzws" }],
  ["path", { d: "M6 13H2", key: "82j7cp" }],
  ["path", { d: "M3 21c0-2.1 1.7-3.9 3.8-4", key: "4p0ekp" }],
  ["path", { d: "M20.97 5c0 2.1-1.6 3.8-3.5 4", key: "18gb23" }],
  ["path", { d: "M22 13h-4", key: "1jl80f" }],
  ["path", { d: "M17.2 17c2.1.1 3.8 1.9 3.8 4", key: "k3fwyw" }]
];
const Bug = createLucideIcon("bug", __iconNode$H);
const __iconNode$G = [
  ["path", { d: "M18 6 7 17l-5-5", key: "116fxf" }],
  ["path", { d: "m22 10-7.5 7.5L13 16", key: "ke71qq" }]
];
const CheckCheck = createLucideIcon("check-check", __iconNode$G);
const __iconNode$F = [["path", { d: "M20 6 9 17l-5-5", key: "1gmf2c" }]];
const Check = createLucideIcon("check", __iconNode$F);
const __iconNode$E = [["path", { d: "m6 9 6 6 6-6", key: "qrunsl" }]];
const ChevronDown = createLucideIcon("chevron-down", __iconNode$E);
const __iconNode$D = [["path", { d: "m9 18 6-6-6-6", key: "mthhwq" }]];
const ChevronRight = createLucideIcon("chevron-right", __iconNode$D);
const __iconNode$C = [["path", { d: "m18 15-6-6-6 6", key: "153udz" }]];
const ChevronUp = createLucideIcon("chevron-up", __iconNode$C);
const __iconNode$B = [
  ["path", { d: "m7 15 5 5 5-5", key: "1hf1tw" }],
  ["path", { d: "m7 9 5-5 5 5", key: "sgt6xg" }]
];
const ChevronsUpDown = createLucideIcon("chevrons-up-down", __iconNode$B);
const __iconNode$A = [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["line", { x1: "12", x2: "12", y1: "8", y2: "12", key: "1pkeuh" }],
  ["line", { x1: "12", x2: "12.01", y1: "16", y2: "16", key: "4dfq90" }]
];
const CircleAlert = createLucideIcon("circle-alert", __iconNode$A);
const __iconNode$z = [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["path", { d: "m9 12 2 2 4-4", key: "dzmm74" }]
];
const CircleCheck = createLucideIcon("circle-check", __iconNode$z);
const __iconNode$y = [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["polygon", { points: "10 8 16 12 10 16 10 8", key: "1cimsy" }]
];
const CirclePlay = createLucideIcon("circle-play", __iconNode$y);
const __iconNode$x = [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["path", { d: "M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3", key: "1u773s" }],
  ["path", { d: "M12 17h.01", key: "p32p05" }]
];
const CircleQuestionMark = createLucideIcon("circle-question-mark", __iconNode$x);
const __iconNode$w = [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["path", { d: "m15 9-6 6", key: "1uzhvr" }],
  ["path", { d: "m9 9 6 6", key: "z0biqf" }]
];
const CircleX = createLucideIcon("circle-x", __iconNode$w);
const __iconNode$v = [["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }]];
const Circle = createLucideIcon("circle", __iconNode$v);
const __iconNode$u = [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["polyline", { points: "12 6 12 12 16 14", key: "68esgv" }]
];
const Clock = createLucideIcon("clock", __iconNode$u);
const __iconNode$t = [
  ["rect", { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2", key: "17jyea" }],
  ["path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2", key: "zix9uf" }]
];
const Copy = createLucideIcon("copy", __iconNode$t);
const __iconNode$s = [
  ["path", { d: "M15 3h6v6", key: "1q9fwt" }],
  ["path", { d: "M10 14 21 3", key: "gplh6r" }],
  ["path", { d: "M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6", key: "a6xqqp" }]
];
const ExternalLink = createLucideIcon("external-link", __iconNode$s);
const __iconNode$r = [
  [
    "path",
    {
      d: "M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",
      key: "ct8e1f"
    }
  ],
  ["path", { d: "M14.084 14.158a3 3 0 0 1-4.242-4.242", key: "151rxh" }],
  [
    "path",
    {
      d: "M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",
      key: "13bj9a"
    }
  ],
  ["path", { d: "m2 2 20 20", key: "1ooewy" }]
];
const EyeOff = createLucideIcon("eye-off", __iconNode$r);
const __iconNode$q = [
  [
    "path",
    {
      d: "M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",
      key: "1nclc0"
    }
  ],
  ["circle", { cx: "12", cy: "12", r: "3", key: "1v7zrd" }]
];
const Eye = createLucideIcon("eye", __iconNode$q);
const __iconNode$p = [
  ["path", { d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z", key: "1rqfz7" }],
  ["path", { d: "M14 2v4a2 2 0 0 0 2 2h4", key: "tnqrlb" }],
  ["path", { d: "M10 9H8", key: "b1mrlr" }],
  ["path", { d: "M16 13H8", key: "t4e002" }],
  ["path", { d: "M16 17H8", key: "z1uh3a" }]
];
const FileText = createLucideIcon("file-text", __iconNode$p);
const __iconNode$o = [
  ["path", { d: "M20 7h-3a2 2 0 0 1-2-2V2", key: "x099mo" }],
  ["path", { d: "M9 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7l4 4v10a2 2 0 0 1-2 2Z", key: "18t6ie" }],
  ["path", { d: "M3 7.6v12.8A1.6 1.6 0 0 0 4.6 22h9.8", key: "1nja0z" }]
];
const Files = createLucideIcon("files", __iconNode$o);
const __iconNode$n = [
  [
    "path",
    {
      d: "M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",
      key: "hod4my"
    }
  ],
  [
    "path",
    {
      d: "M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",
      key: "w4yl2u"
    }
  ],
  ["path", { d: "M3 5a2 2 0 0 0 2 2h3", key: "f2jnh7" }],
  ["path", { d: "M3 3v13a2 2 0 0 0 2 2h3", key: "k8epm1" }]
];
const FolderTree = createLucideIcon("folder-tree", __iconNode$n);
const __iconNode$m = [
  [
    "path",
    {
      d: "M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",
      key: "tonef"
    }
  ],
  ["path", { d: "M9 18c-4.51 2-5-2-7-2", key: "9comsn" }]
];
const Github = createLucideIcon("github", __iconNode$m);
const __iconNode$l = [
  ["path", { d: "m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9", key: "eefl8a" }],
  ["path", { d: "m18 15 4-4", key: "16gjal" }],
  [
    "path",
    {
      d: "m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",
      key: "b7pghm"
    }
  ]
];
const Hammer = createLucideIcon("hammer", __iconNode$l);
const __iconNode$k = [
  ["line", { x1: "4", x2: "20", y1: "9", y2: "9", key: "4lhtct" }],
  ["line", { x1: "4", x2: "20", y1: "15", y2: "15", key: "vyu0kd" }],
  ["line", { x1: "10", x2: "8", y1: "3", y2: "21", key: "1ggp8o" }],
  ["line", { x1: "16", x2: "14", y1: "3", y2: "21", key: "weycgp" }]
];
const Hash = createLucideIcon("hash", __iconNode$k);
const __iconNode$j = [
  ["path", { d: "m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4", key: "g0fldk" }],
  ["path", { d: "m21 2-9.6 9.6", key: "1j0ho8" }],
  ["circle", { cx: "7.5", cy: "15.5", r: "5.5", key: "yqb3hr" }]
];
const Key = createLucideIcon("key", __iconNode$j);
const __iconNode$i = [
  ["rect", { x: "3", y: "5", width: "6", height: "6", rx: "1", key: "1defrl" }],
  ["path", { d: "m3 17 2 2 4-4", key: "1jhpwq" }],
  ["path", { d: "M13 6h8", key: "15sg57" }],
  ["path", { d: "M13 12h8", key: "h98zly" }],
  ["path", { d: "M13 18h8", key: "oe0vm4" }]
];
const ListTodo = createLucideIcon("list-todo", __iconNode$i);
const __iconNode$h = [["path", { d: "M21 12a9 9 0 1 1-6.219-8.56", key: "13zald" }]];
const LoaderCircle = createLucideIcon("loader-circle", __iconNode$h);
const __iconNode$g = [
  ["path", { d: "M15 3h6v6", key: "1q9fwt" }],
  ["path", { d: "m21 3-7 7", key: "1l2asr" }],
  ["path", { d: "m3 21 7-7", key: "tjx5ai" }],
  ["path", { d: "M9 21H3v-6", key: "wtvkvv" }]
];
const Maximize2 = createLucideIcon("maximize-2", __iconNode$g);
const __iconNode$f = [
  ["path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z", key: "1lielz" }]
];
const MessageSquare = createLucideIcon("message-square", __iconNode$f);
const __iconNode$e = [
  ["path", { d: "m14 10 7-7", key: "oa77jy" }],
  ["path", { d: "M20 10h-6V4", key: "mjg0md" }],
  ["path", { d: "m3 21 7-7", key: "tjx5ai" }],
  ["path", { d: "M4 14h6v6", key: "rmj7iw" }]
];
const Minimize2 = createLucideIcon("minimize-2", __iconNode$e);
const __iconNode$d = [["path", { d: "M5 12h14", key: "1ays0h" }]];
const Minus = createLucideIcon("minus", __iconNode$d);
const __iconNode$c = [["polygon", { points: "6 3 20 12 6 21 6 3", key: "1oa8hb" }]];
const Play = createLucideIcon("play", __iconNode$c);
const __iconNode$b = [
  ["path", { d: "M5 12h14", key: "1ays0h" }],
  ["path", { d: "M12 5v14", key: "s699le" }]
];
const Plus = createLucideIcon("plus", __iconNode$b);
const __iconNode$a = [
  ["path", { d: "M21 8L18.74 5.74A9.75 9.75 0 0 0 12 3C11 3 10.03 3.16 9.13 3.47", key: "1krf6h" }],
  ["path", { d: "M8 16H3v5", key: "1cv678" }],
  ["path", { d: "M3 12C3 9.51 4 7.26 5.64 5.64", key: "ruvoct" }],
  ["path", { d: "m3 16 2.26 2.26A9.75 9.75 0 0 0 12 21c2.49 0 4.74-1 6.36-2.64", key: "19q130" }],
  ["path", { d: "M21 12c0 1-.16 1.97-.47 2.87", key: "4w8emr" }],
  ["path", { d: "M21 3v5h-5", key: "1q7to0" }],
  ["path", { d: "M22 22 2 2", key: "1r8tn9" }]
];
const RefreshCwOff = createLucideIcon("refresh-cw-off", __iconNode$a);
const __iconNode$9 = [
  ["path", { d: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8", key: "v9h5vc" }],
  ["path", { d: "M21 3v5h-5", key: "1q7to0" }],
  ["path", { d: "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16", key: "3uifl3" }],
  ["path", { d: "M8 16H3v5", key: "1cv678" }]
];
const RefreshCw = createLucideIcon("refresh-cw", __iconNode$9);
const __iconNode$8 = [
  ["path", { d: "M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8", key: "1357e3" }],
  ["path", { d: "M3 3v5h5", key: "1xhq8a" }]
];
const RotateCcw = createLucideIcon("rotate-ccw", __iconNode$8);
const __iconNode$7 = [
  [
    "path",
    {
      d: "M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",
      key: "1c8476"
    }
  ],
  ["path", { d: "M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7", key: "1ydtos" }],
  ["path", { d: "M7 3v4a1 1 0 0 0 1 1h7", key: "t51u73" }]
];
const Save = createLucideIcon("save", __iconNode$7);
const __iconNode$6 = [
  ["path", { d: "m21 21-4.34-4.34", key: "14j7rj" }],
  ["circle", { cx: "11", cy: "11", r: "8", key: "4ej97u" }]
];
const Search = createLucideIcon("search", __iconNode$6);
const __iconNode$5 = [
  [
    "path",
    {
      d: "M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",
      key: "1ffxy3"
    }
  ],
  ["path", { d: "m21.854 2.147-10.94 10.939", key: "12cjpa" }]
];
const Send = createLucideIcon("send", __iconNode$5);
const __iconNode$4 = [
  ["rect", { width: "20", height: "8", x: "2", y: "2", rx: "2", ry: "2", key: "ngkwjq" }],
  ["rect", { width: "20", height: "8", x: "2", y: "14", rx: "2", ry: "2", key: "iecqi9" }],
  ["line", { x1: "6", x2: "6.01", y1: "6", y2: "6", key: "16zg32" }],
  ["line", { x1: "6", x2: "6.01", y1: "18", y2: "18", key: "nzw8ys" }]
];
const Server = createLucideIcon("server", __iconNode$4);
const __iconNode$3 = [
  [
    "path",
    {
      d: "M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",
      key: "1qme2f"
    }
  ],
  ["circle", { cx: "12", cy: "12", r: "3", key: "1v7zrd" }]
];
const Settings = createLucideIcon("settings", __iconNode$3);
const __iconNode$2 = [
  ["path", { d: "M3 6h18", key: "d0wm0j" }],
  ["path", { d: "M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6", key: "4alrt4" }],
  ["path", { d: "M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2", key: "v07s0e" }],
  ["line", { x1: "10", x2: "10", y1: "11", y2: "17", key: "1uufr5" }],
  ["line", { x1: "14", x2: "14", y1: "11", y2: "17", key: "xtxkd" }]
];
const Trash2 = createLucideIcon("trash-2", __iconNode$2);
const __iconNode$1 = [
  [
    "path",
    {
      d: "m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",
      key: "wmoenq"
    }
  ],
  ["path", { d: "M12 9v4", key: "juzpu7" }],
  ["path", { d: "M12 17h.01", key: "p32p05" }]
];
const TriangleAlert = createLucideIcon("triangle-alert", __iconNode$1);
const __iconNode = [
  ["path", { d: "M18 6 6 18", key: "1bl5f8" }],
  ["path", { d: "m6 6 12 12", key: "d8bk6v" }]
];
const X$1 = createLucideIcon("x", __iconNode);
const OAuthStepDetails = ({
  label,
  isComplete,
  isCurrent,
  error,
  children
}) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: `flex items-center p-2 rounded-md ${isCurrent ? "bg-accent" : ""}`,
        children: [
          isComplete ? /* @__PURE__ */ jsxRuntimeExports.jsx(CircleCheck, { className: "h-5 w-5 text-green-500 mr-2" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Circle, { className: "h-5 w-5 text-muted-foreground mr-2" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${isCurrent ? "font-medium" : ""}`, children: label })
        ]
      }
    ),
    (isCurrent || isComplete) && children && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ml-7 mt-1", children }),
    isCurrent && error && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "ml-7 mt-2 p-3 border border-red-300 bg-red-50 rounded-md", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-red-700", children: "Error:" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-red-600 mt-1", children: error.message })
    ] })
  ] });
};
const steps = [
  "metadata_discovery",
  "client_registration",
  "authorization_redirect",
  "authorization_code",
  "token_request",
  "complete"
];
const OAuthFlowProgress = ({
  serverUrl,
  authState,
  updateAuthState,
  proceedToNextStep
}) => {
  const { toast: toast2 } = useToast();
  const provider = reactExports.useMemo(
    () => new DebugInspectorOAuthClientProvider(serverUrl),
    [serverUrl]
  );
  const [clientInfo, setClientInfo] = reactExports.useState(
    null
  );
  const authorizationServerMetadataDiscoveryUrl = reactExports.useMemo(() => {
    if (!authState.authServerUrl) {
      return null;
    }
    return getAuthorizationServerMetadataDiscoveryUrl(authState.authServerUrl);
  }, [authState.authServerUrl]);
  const currentStepIdx = steps.findIndex((s2) => s2 === authState.oauthStep);
  reactExports.useEffect(() => {
    const fetchClientInfo = async () => {
      if (authState.oauthClientInfo) {
        setClientInfo(authState.oauthClientInfo);
      } else {
        try {
          const info = await provider.clientInformation();
          if (info) {
            setClientInfo(info);
          }
        } catch (error) {
          console.error("Failed to fetch client information:", error);
        }
      }
    };
    if (currentStepIdx > steps.indexOf("client_registration")) {
      fetchClientInfo();
    }
  }, [
    provider,
    authState.oauthStep,
    authState.oauthClientInfo,
    currentStepIdx
  ]);
  const getStepProps = (stepName) => ({
    isComplete: currentStepIdx > steps.indexOf(stepName) || currentStepIdx === steps.length - 1,
    // last step is "complete"
    isCurrent: authState.oauthStep === stepName,
    error: authState.oauthStep === stepName ? authState.latestError : null
  });
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-md border p-6 space-y-4 mt-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-medium", children: "OAuth Flow Progress" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-muted-foreground", children: "Follow these steps to complete OAuth authentication with the server." }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        OAuthStepDetails,
        {
          label: "Metadata Discovery",
          ...getStepProps("metadata_discovery"),
          children: authState.oauthMetadata && /* @__PURE__ */ jsxRuntimeExports.jsxs("details", { className: "text-xs mt-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("summary", { className: "cursor-pointer text-muted-foreground font-medium", children: [
              "OAuth Metadata Sources",
              !authState.resourceMetadata && " ℹ️"
            ] }),
            authState.resourceMetadata && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium", children: "Resource Metadata:" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-muted-foreground", children: [
                "From",
                " ",
                new URL(
                  "/.well-known/oauth-protected-resource",
                  serverUrl
                ).href
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]", children: JSON.stringify(authState.resourceMetadata, null, 2) })
            ] }),
            authState.resourceMetadataError && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2 p-3 border border-blue-300 bg-blue-50 rounded-md", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm font-medium text-blue-700", children: [
                "ℹ️ Problem with resource metadata from",
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "a",
                  {
                    href: new URL(
                      "/.well-known/oauth-protected-resource",
                      serverUrl
                    ).href,
                    target: "_blank",
                    rel: "noopener noreferrer",
                    className: "text-blue-500 hover:text-blue-700",
                    children: new URL(
                      "/.well-known/oauth-protected-resource",
                      serverUrl
                    ).href
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-blue-600 mt-1", children: [
                "Resource metadata was added in the",
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("a", { href: "https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#authorization-server-location", children: "2025-06-18 specification update" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
                authState.resourceMetadataError.message,
                authState.resourceMetadataError instanceof TypeError && " (This could indicate the endpoint doesn't exist or does not have CORS configured)"
              ] })
            ] }),
            authState.oauthMetadata && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium", children: "Authorization Server Metadata:" }),
              authState.authServerUrl && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-muted-foreground", children: [
                "From ",
                authorizationServerMetadataDiscoveryUrl
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]", children: JSON.stringify(authState.oauthMetadata, null, 2) })
            ] })
          ] })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        OAuthStepDetails,
        {
          label: "Client Registration",
          ...getStepProps("client_registration"),
          children: clientInfo && /* @__PURE__ */ jsxRuntimeExports.jsxs("details", { className: "text-xs mt-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("summary", { className: "cursor-pointer text-muted-foreground font-medium", children: "Registered Client Information" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]", children: JSON.stringify(clientInfo, null, 2) })
          ] })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        OAuthStepDetails,
        {
          label: "Preparing Authorization",
          ...getStepProps("authorization_redirect"),
          children: authState.authorizationUrl && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2 p-3 border rounded-md bg-muted", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium mb-2 text-sm", children: "Authorization URL:" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs break-all", children: String(authState.authorizationUrl) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  onClick: () => {
                    try {
                      validateRedirectUrl(authState.authorizationUrl);
                      window.open(
                        authState.authorizationUrl,
                        "_blank",
                        "noopener noreferrer"
                      );
                    } catch (error) {
                      toast2({
                        title: "Invalid URL",
                        description: error instanceof Error ? error.message : "The authorization URL is not valid",
                        variant: "destructive"
                      });
                    }
                  },
                  className: "flex items-center text-blue-500 hover:text-blue-700",
                  "aria-label": "Open authorization URL in new tab",
                  title: "Open authorization URL",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "h-4 w-4" })
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-muted-foreground mt-2", children: "Click the link to authorize in your browser. After authorization, you'll be redirected back to continue the flow." })
          ] })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        OAuthStepDetails,
        {
          label: "Request Authorization and acquire authorization code",
          ...getStepProps("authorization_code"),
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                htmlFor: "authCode",
                className: "block text-sm font-medium mb-1",
                children: "Authorization Code"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              "input",
              {
                id: "authCode",
                value: authState.authorizationCode,
                onChange: (e2) => {
                  updateAuthState({
                    authorizationCode: e2.target.value,
                    validationError: null
                  });
                },
                placeholder: "Enter the code from the authorization server",
                className: `flex h-9 w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${authState.validationError ? "border-red-500" : "border-input"}`
              }
            ) }),
            authState.validationError && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-red-600 mt-1", children: authState.validationError }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-muted-foreground mt-1", children: "Once you've completed authorization in the link, paste the code here." })
          ] })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        OAuthStepDetails,
        {
          label: "Token Request",
          ...getStepProps("token_request"),
          children: authState.oauthMetadata && /* @__PURE__ */ jsxRuntimeExports.jsxs("details", { className: "text-xs mt-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("summary", { className: "cursor-pointer text-muted-foreground font-medium", children: "Token Request Details" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2 p-2 bg-muted rounded-md", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium", children: "Token Endpoint:" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "block mt-1 text-xs overflow-x-auto", children: authState.oauthMetadata.token_endpoint })
            ] })
          ] })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        OAuthStepDetails,
        {
          label: "Authentication Complete",
          ...getStepProps("complete"),
          children: authState.oauthTokens && /* @__PURE__ */ jsxRuntimeExports.jsxs("details", { className: "text-xs mt-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("summary", { className: "cursor-pointer text-muted-foreground font-medium", children: "Access Tokens" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm", children: "Authentication successful! You can now use the authenticated connection. These tokens will be used automatically for server requests." }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]", children: JSON.stringify(authState.oauthTokens, null, 2) })
          ] })
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-3 mt-4", children: [
      authState.oauthStep !== "complete" && /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          onClick: proceedToNextStep,
          disabled: authState.isInitiatingAuth,
          children: authState.isInitiatingAuth ? "Processing..." : "Continue"
        }
      ) }),
      authState.oauthStep === "authorization_redirect" && authState.authorizationUrl && /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          variant: "outline",
          onClick: () => {
            try {
              validateRedirectUrl(authState.authorizationUrl);
              window.open(authState.authorizationUrl, "_blank");
            } catch (error) {
              toast2({
                title: "Invalid URL",
                description: error instanceof Error ? error.message : "The authorization URL is not valid",
                variant: "destructive"
              });
            }
          },
          children: "Open in New Tab"
        }
      )
    ] })
  ] });
};
const StatusMessage = ({ message }) => {
  let bgColor;
  let textColor;
  let borderColor;
  switch (message.type) {
    case "error":
      bgColor = "bg-red-50";
      textColor = "text-red-700";
      borderColor = "border-red-200";
      break;
    case "success":
      bgColor = "bg-green-50";
      textColor = "text-green-700";
      borderColor = "border-green-200";
      break;
    case "info":
    default:
      bgColor = "bg-blue-50";
      textColor = "text-blue-700";
      borderColor = "border-blue-200";
      break;
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      className: `p-3 rounded-md border ${bgColor} ${borderColor} ${textColor} mb-4`,
      children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CircleAlert, { className: "h-4 w-4" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm", children: message.message })
      ] })
    }
  );
};
const AuthDebugger = ({
  serverUrl,
  onBack,
  authState,
  updateAuthState,
  config: config2,
  connectionType
}) => {
  reactExports.useEffect(() => {
    if (serverUrl && !authState.oauthTokens) {
      const checkTokens = async () => {
        try {
          const provider = new DebugInspectorOAuthClientProvider(serverUrl);
          const existingTokens = await provider.tokens();
          if (existingTokens) {
            updateAuthState({
              oauthTokens: existingTokens,
              oauthStep: "complete"
            });
          }
        } catch (error) {
          console.error("Failed to load existing OAuth tokens:", error);
        }
      };
      checkTokens();
    }
  }, [serverUrl, updateAuthState, authState.oauthTokens]);
  const startOAuthFlow = reactExports.useCallback(() => {
    if (!serverUrl) {
      updateAuthState({
        statusMessage: {
          type: "error",
          message: "Please enter a server URL in the sidebar before authenticating"
        }
      });
      return;
    }
    updateAuthState({
      oauthStep: "metadata_discovery",
      authorizationUrl: null,
      statusMessage: null,
      latestError: null
    });
  }, [serverUrl, updateAuthState]);
  const fetchFn = reactExports.useMemo(
    () => connectionType === "proxy" && config2 ? createProxyFetch(config2) : void 0,
    [connectionType, config2]
  );
  const stateMachine = reactExports.useMemo(
    () => new OAuthStateMachine(serverUrl, updateAuthState, fetchFn),
    [serverUrl, updateAuthState, fetchFn]
  );
  const proceedToNextStep = reactExports.useCallback(async () => {
    if (!serverUrl) return;
    try {
      updateAuthState({
        isInitiatingAuth: true,
        statusMessage: null,
        latestError: null
      });
      await stateMachine.executeStep(authState);
    } catch (error) {
      console.error("OAuth flow error:", error);
      updateAuthState({
        latestError: error instanceof Error ? error : new Error(String(error))
      });
    } finally {
      updateAuthState({ isInitiatingAuth: false });
    }
  }, [serverUrl, authState, updateAuthState, stateMachine]);
  const handleQuickOAuth = reactExports.useCallback(async () => {
    if (!serverUrl) {
      updateAuthState({
        statusMessage: {
          type: "error",
          message: "Please enter a server URL in the sidebar before authenticating"
        }
      });
      return;
    }
    updateAuthState({ isInitiatingAuth: true, statusMessage: null });
    try {
      let currentState = {
        ...authState,
        oauthStep: "metadata_discovery",
        authorizationUrl: null,
        latestError: null
      };
      const oauthMachine = new OAuthStateMachine(
        serverUrl,
        (updates) => {
          currentState = { ...currentState, ...updates };
        },
        fetchFn
      );
      while (currentState.oauthStep !== "complete") {
        await oauthMachine.executeStep(currentState);
        if (currentState.oauthStep === "authorization_code" && currentState.authorizationUrl) {
          try {
            validateRedirectUrl(currentState.authorizationUrl);
          } catch (error) {
            updateAuthState({
              ...currentState,
              isInitiatingAuth: false,
              latestError: error instanceof Error ? error : new Error(String(error)),
              statusMessage: {
                type: "error",
                message: `Invalid authorization URL: ${error instanceof Error ? error.message : String(error)}`
              }
            });
            return;
          }
          sessionStorage.setItem(
            SESSION_KEYS.AUTH_DEBUGGER_STATE,
            JSON.stringify(currentState)
          );
          window.location.href = currentState.authorizationUrl.toString();
          break;
        }
      }
      updateAuthState({
        ...currentState,
        statusMessage: {
          type: "info",
          message: currentState.oauthStep === "complete" ? "Authentication completed successfully" : "Please complete authentication in the opened window and enter the code"
        }
      });
    } catch (error) {
      console.error("OAuth initialization error:", error);
      updateAuthState({
        statusMessage: {
          type: "error",
          message: `Failed to start OAuth flow: ${error instanceof Error ? error.message : String(error)}`
        }
      });
    } finally {
      updateAuthState({ isInitiatingAuth: false });
    }
  }, [serverUrl, updateAuthState, authState, fetchFn]);
  const handleClearOAuth = reactExports.useCallback(() => {
    if (serverUrl) {
      const serverAuthProvider = new DebugInspectorOAuthClientProvider(
        serverUrl
      );
      serverAuthProvider.clear();
      updateAuthState({
        ...EMPTY_DEBUGGER_STATE,
        statusMessage: {
          type: "success",
          message: "OAuth tokens cleared successfully"
        }
      });
      setTimeout(() => {
        updateAuthState({ statusMessage: null });
      }, 3e3);
    }
  }, [serverUrl, updateAuthState]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "w-full p-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-center mb-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-2xl font-bold", children: "Authentication Settings" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: onBack, children: "Back to Connect" })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full space-y-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-col gap-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid w-full gap-2", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-muted-foreground mb-4", children: "Configure authentication settings for your MCP server connection." }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-md border p-6 space-y-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-medium", children: "OAuth Authentication" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-muted-foreground mb-2", children: "Use OAuth to securely authenticate with the MCP server." }),
        authState.statusMessage && /* @__PURE__ */ jsxRuntimeExports.jsx(StatusMessage, { message: authState.statusMessage }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
          authState.oauthTokens && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium", children: "Access Token:" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-muted p-2 rounded-md text-xs overflow-x-auto", children: [
              authState.oauthTokens.access_token.substring(0, 25),
              "..."
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                variant: "outline",
                onClick: startOAuthFlow,
                disabled: authState.isInitiatingAuth,
                children: authState.oauthTokens ? "Guided Token Refresh" : "Guided OAuth Flow"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                onClick: handleQuickOAuth,
                disabled: authState.isInitiatingAuth,
                children: authState.isInitiatingAuth ? "Initiating..." : authState.oauthTokens ? "Quick Refresh" : "Quick OAuth Flow"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: handleClearOAuth, children: "Clear OAuth State" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-muted-foreground", children: 'Choose "Guided" for step-by-step instructions or "Quick" for the standard automatic flow.' })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        OAuthFlowProgress,
        {
          serverUrl,
          authState,
          updateAuthState,
          proceedToNextStep
        }
      )
    ] }) }) })
  ] });
};
const ConsoleTab = () => /* @__PURE__ */ jsxRuntimeExports.jsx(TabsContent, { value: "console", className: "h-96", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-gray-900 text-gray-100 p-4 rounded-lg h-full font-mono text-sm overflow-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "opacity-50", children: "Welcome to MCP Client Console" }) }) });
function getDataType(value) {
  if (Array.isArray(value)) return "array";
  if (value === null) return "null";
  return typeof value;
}
function tryParseJson(str) {
  const trimmed = str?.trim();
  if (trimmed && !(trimmed.startsWith("{") && trimmed.endsWith("}")) && !(trimmed.startsWith("[") && trimmed.endsWith("]"))) {
    return { success: false, data: str };
  }
  try {
    return { success: true, data: JSON.parse(str) };
  } catch {
    return { success: false, data: str };
  }
}
function updateValueAtPath(obj, path, value) {
  if (path.length === 0) return value;
  if (obj === null || obj === void 0) {
    obj = !isNaN(Number(path[0])) ? [] : {};
  }
  if (Array.isArray(obj)) {
    return updateArray(obj, path, value);
  } else if (typeof obj === "object" && obj !== null) {
    return updateObject(obj, path, value);
  } else {
    console.error(
      `Cannot update path ${path.join(".")} in non-object/array value:`,
      obj
    );
    return obj;
  }
}
function updateArray(array2, path, value) {
  const [index2, ...restPath] = path;
  const arrayIndex = Number(index2);
  if (isNaN(arrayIndex)) {
    console.error(`Invalid array index: ${index2}`);
    return array2;
  }
  if (arrayIndex < 0) {
    console.error(`Array index out of bounds: ${arrayIndex} < 0`);
    return array2;
  }
  let newArray = [];
  for (let i2 = 0; i2 < array2.length; i2++) {
    newArray[i2] = i2 in array2 ? array2[i2] : null;
  }
  if (arrayIndex >= newArray.length) {
    const extendedArray = new Array(arrayIndex).fill(null);
    for (let i2 = 0; i2 < newArray.length; i2++) {
      extendedArray[i2] = newArray[i2];
    }
    newArray = extendedArray;
  }
  if (restPath.length === 0) {
    newArray[arrayIndex] = value;
  } else {
    newArray[arrayIndex] = updateValueAtPath(
      newArray[arrayIndex],
      restPath,
      value
    );
  }
  return newArray;
}
function updateObject(obj, path, value) {
  const [key, ...restPath] = path;
  if (typeof key !== "string") {
    console.error(`Invalid object key: ${key}`);
    return obj;
  }
  const newObj = { ...obj };
  if (restPath.length === 0) {
    newObj[key] = value;
  } else {
    if (!(key in newObj)) {
      newObj[key] = {};
    }
    newObj[key] = updateValueAtPath(newObj[key], restPath, value);
  }
  return newObj;
}
function useCopy({ timeout = 500 } = {}) {
  const [copied, setCopied] = reactExports.useState(false);
  reactExports.useEffect(() => {
    let timeoutId;
    if (copied) {
      timeoutId = setTimeout(() => {
        setCopied(false);
      }, timeout);
    }
    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
  }, [copied, timeout]);
  return { copied, setCopied };
}
const JsonView = reactExports.memo(
  ({
    data: data2,
    name: name2,
    initialExpandDepth = 3,
    className,
    withCopyButton = true,
    isError = false
  }) => {
    const { toast: toast2 } = useToast();
    const { copied, setCopied } = useCopy();
    const normalizedData = reactExports.useMemo(() => {
      return typeof data2 === "string" ? tryParseJson(data2).success ? tryParseJson(data2).data : data2 : data2;
    }, [data2]);
    const handleCopy = reactExports.useCallback(() => {
      try {
        navigator.clipboard.writeText(
          typeof normalizedData === "string" ? normalizedData : JSON.stringify(normalizedData, null, 2)
        );
        setCopied(true);
      } catch (error) {
        toast2({
          title: "Error",
          description: `There was an error coping result into the clipboard: ${error instanceof Error ? error.message : String(error)}`,
          variant: "destructive"
        });
      }
    }, [toast2, normalizedData, setCopied]);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: clsx(
          "p-4 border overflow-x-auto rounded relative",
          className
        ),
        children: [
          withCopyButton && /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              size: "icon",
              variant: "ghost",
              className: "absolute top-2 right-2",
              onClick: handleCopy,
              children: copied ? /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCheck, { className: "size-4 dark:text-green-700 text-green-600" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "size-4 text-foreground" })
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-mono text-sm transition-all duration-300", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            JsonNode,
            {
              data: normalizedData,
              name: name2,
              depth: 0,
              initialExpandDepth,
              isError
            }
          ) })
        ]
      }
    );
  }
);
JsonView.displayName = "JsonView";
const JsonNode = reactExports.memo(
  ({
    data: data2,
    name: name2,
    depth = 0,
    initialExpandDepth,
    isError = false
  }) => {
    const { toast: toast2 } = useToast();
    const [isExpanded, setIsExpanded] = reactExports.useState(depth < initialExpandDepth);
    const [typeStyleMap] = reactExports.useState({
      number: "text-blue-600",
      boolean: "text-amber-600",
      null: "text-purple-600",
      undefined: "text-gray-600",
      string: "text-green-600 group-hover:text-green-500",
      error: "text-red-600 group-hover:text-red-500",
      default: "text-gray-700"
    });
    const dataType2 = getDataType(data2);
    const [copied, setCopied] = reactExports.useState(false);
    reactExports.useEffect(() => {
      let timeoutId;
      if (copied) {
        timeoutId = setTimeout(() => setCopied(false), 500);
      }
      return () => {
        if (timeoutId) clearTimeout(timeoutId);
      };
    }, [copied]);
    const handleCopyValue = reactExports.useCallback(
      (value) => {
        try {
          let text;
          const valueType = getDataType(value);
          switch (valueType) {
            case "string":
              text = value;
              break;
            case "number":
            case "boolean":
              text = String(value);
              break;
            case "null":
              text = "null";
              break;
            case "undefined":
              text = "undefined";
              break;
            default:
              text = JSON.stringify(value);
          }
          navigator.clipboard.writeText(text);
          setCopied(true);
        } catch (error) {
          toast2({
            title: "Error",
            description: `There was an error coping result into the clipboard: ${error instanceof Error ? error.message : String(error)}`,
            variant: "destructive"
          });
        }
      },
      [toast2]
    );
    const renderCollapsible = (isArray) => {
      const items2 = isArray ? data2 : Object.entries(data2);
      const itemCount = items2.length;
      const isEmpty = itemCount === 0;
      const symbolMap = {
        open: isArray ? "[" : "{",
        close: isArray ? "]" : "}",
        collapsed: isArray ? "[ ... ]" : "{ ... }",
        empty: isArray ? "[]" : "{}"
      };
      if (isEmpty) {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center", children: [
          name2 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "mr-1 text-gray-600 dark:text-gray-400", children: [
            name2,
            ":"
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500", children: symbolMap.empty })
        ] });
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: "flex items-center mr-1 rounded cursor-pointer group hover:bg-gray-800/10 dark:hover:bg-gray-800/20",
            onClick: () => setIsExpanded(!isExpanded),
            children: [
              name2 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "mr-1 text-gray-600 dark:text-gray-400 dark:group-hover:text-gray-100 group-hover:text-gray-400", children: [
                name2,
                ":"
              ] }),
              isExpanded ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400 dark:group-hover:text-gray-100 group-hover:text-gray-400", children: symbolMap.open }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:group-hover:text-gray-100 group-hover:text-gray-400", children: symbolMap.collapsed }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "ml-1 text-gray-700 dark:group-hover:text-gray-100 group-hover:text-gray-400", children: [
                  itemCount,
                  " ",
                  itemCount === 1 ? "item" : "items"
                ] })
              ] })
            ]
          }
        ),
        isExpanded && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "pl-2 ml-4 border-l border-gray-200 dark:border-gray-800", children: isArray ? items2.map((item, index2) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "my-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            JsonNode,
            {
              data: item,
              name: `${index2}`,
              depth: depth + 1,
              initialExpandDepth
            }
          ) }, index2)) : items2.map(([key, value]) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "my-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            JsonNode,
            {
              data: value,
              name: key,
              depth: depth + 1,
              initialExpandDepth
            }
          ) }, key)) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-gray-600 dark:text-gray-400", children: symbolMap.close })
        ] })
      ] });
    };
    const renderString = (value) => {
      const maxLength = 100;
      const isTooLong = value.length > maxLength;
      if (!isTooLong) {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex mr-1 rounded hover:bg-gray-800/20 group items-start", children: [
          name2 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "mr-1 text-gray-600 dark:text-gray-400", children: [
            name2,
            ":"
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "pre",
            {
              className: clsx(
                isError ? typeStyleMap.error : typeStyleMap.string,
                "break-all whitespace-pre-wrap"
              ),
              children: [
                '"',
                value,
                '"'
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "ghost",
              className: "ml-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100",
              onClick: (e2) => {
                e2.stopPropagation();
                handleCopyValue(value);
              },
              "aria-label": name2 ? `Copy value of ${name2}` : "Copy value",
              title: name2 ? `Copy value of ${name2}` : "Copy value",
              children: copied ? /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCheck, { className: "size-4 dark:text-green-700 text-green-600" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "size-4 text-foreground" })
            }
          )
        ] });
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex mr-1 rounded group hover:bg-gray-800/20 items-start", children: [
        name2 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "mr-1 text-gray-600 dark:text-gray-400 dark:group-hover:text-gray-100 group-hover:text-gray-400", children: [
          name2,
          ":"
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "pre",
          {
            className: clsx(
              isError ? typeStyleMap.error : typeStyleMap.string,
              "cursor-pointer break-all whitespace-pre-wrap"
            ),
            onClick: () => setIsExpanded(!isExpanded),
            title: isExpanded ? "Click to collapse" : "Click to expand",
            children: isExpanded ? `"${value}"` : `"${value.slice(0, maxLength)}..."`
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "ghost",
            className: "ml-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100",
            onClick: (e2) => {
              e2.stopPropagation();
              handleCopyValue(value);
            },
            "aria-label": name2 ? `Copy value of ${name2}` : "Copy value",
            title: name2 ? `Copy value of ${name2}` : "Copy value",
            children: copied ? /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCheck, { className: "size-4 dark:text-green-700 text-green-600" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "size-4 text-foreground" })
          }
        )
      ] });
    };
    switch (dataType2) {
      case "object":
      case "array":
        return renderCollapsible(dataType2 === "array");
      case "string":
        return renderString(data2);
      default:
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center mr-1 rounded hover:bg-gray-800/20 group", children: [
          name2 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "mr-1 text-gray-600 dark:text-gray-400", children: [
            name2,
            ":"
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: typeStyleMap[dataType2] || typeStyleMap.default, children: data2 === null ? "null" : String(data2) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "ghost",
              className: "ml-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100",
              onClick: (e2) => {
                e2.stopPropagation();
                handleCopyValue(data2);
              },
              "aria-label": name2 ? `Copy value of ${name2}` : "Copy value",
              title: name2 ? `Copy value of ${name2}` : "Copy value",
              children: copied ? /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCheck, { className: "size-4 dark:text-green-700 text-green-600" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "size-4 text-foreground" })
            }
          )
        ] });
    }
  }
);
JsonNode.displayName = "JsonNode";
const HistoryAndNotifications = ({
  requestHistory,
  serverNotifications,
  onClearHistory,
  onClearNotifications
}) => {
  const [expandedRequests, setExpandedRequests] = reactExports.useState({});
  const [expandedNotifications, setExpandedNotifications] = reactExports.useState({});
  const toggleRequestExpansion = (index2) => {
    setExpandedRequests((prev) => ({ ...prev, [index2]: !prev[index2] }));
  };
  const toggleNotificationExpansion = (index2) => {
    setExpandedNotifications((prev) => ({ ...prev, [index2]: !prev[index2] }));
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-card overflow-hidden flex h-full", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 overflow-y-auto p-4 border-r", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-lg font-semibold", children: "History" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "outline",
            size: "sm",
            onClick: onClearHistory,
            disabled: requestHistory.length === 0,
            children: "Clear"
          }
        )
      ] }),
      requestHistory.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400 italic", children: "No history yet" }) : /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: "space-y-3", children: requestHistory.slice().reverse().map((request, index2) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "li",
        {
          className: "text-sm text-foreground bg-secondary py-2 px-3 rounded",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "div",
              {
                className: "flex justify-between items-center cursor-pointer",
                onClick: () => toggleRequestExpansion(requestHistory.length - 1 - index2),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "font-mono", children: [
                    requestHistory.length - index2,
                    ".",
                    " ",
                    JSON.parse(request.request).method
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: expandedRequests[requestHistory.length - 1 - index2] ? "▼" : "▶" })
                ]
              }
            ),
            expandedRequests[requestHistory.length - 1 - index2] && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-between items-center mb-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold text-blue-600", children: "Request:" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  JsonView,
                  {
                    data: request.request,
                    className: "bg-background"
                  }
                )
              ] }),
              request.response && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-between items-center mb-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold text-green-600", children: "Response:" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  JsonView,
                  {
                    data: request.response,
                    className: "bg-background"
                  }
                )
              ] })
            ] })
          ]
        },
        index2
      )) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 overflow-y-auto p-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-lg font-semibold", children: "Server Notifications" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "outline",
            size: "sm",
            onClick: onClearNotifications,
            disabled: serverNotifications.length === 0,
            children: "Clear"
          }
        )
      ] }),
      serverNotifications.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400 italic", children: "No notifications yet" }) : /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: "space-y-3", children: serverNotifications.slice().reverse().map((notification, index2) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "li",
        {
          className: "text-sm text-foreground bg-secondary py-2 px-3 rounded",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "div",
              {
                className: "flex justify-between items-center cursor-pointer",
                onClick: () => toggleNotificationExpansion(
                  serverNotifications.length - 1 - index2
                ),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "font-mono", children: [
                    serverNotifications.length - index2,
                    ".",
                    " ",
                    notification.method
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: expandedNotifications[serverNotifications.length - 1 - index2] ? "▼" : "▶" })
                ]
              }
            ),
            expandedNotifications[serverNotifications.length - 1 - index2] && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-between items-center mb-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold text-purple-600", children: "Details:" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                JsonView,
                {
                  data: JSON.stringify(notification, null, 2),
                  className: "bg-background"
                }
              )
            ] })
          ]
        },
        index2
      )) })
    ] })
  ] });
};
const PingTab = ({ onPingClick }) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(TabsContent, { value: "ping", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-2 gap-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "col-span-2 flex justify-center items-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
    Button,
    {
      onClick: onPingClick,
      className: "font-bold py-6 px-12 rounded-full",
      children: "Ping Server"
    }
  ) }) }) });
};
const alertVariants = cva(
  "relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
  {
    variants: {
      variant: {
        default: "bg-background text-foreground",
        destructive: "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"
      }
    },
    defaultVariants: {
      variant: "default"
    }
  }
);
const Alert = reactExports.forwardRef(({ className, variant, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  "div",
  {
    ref: ref2,
    role: "alert",
    className: cn$1(alertVariants({ variant }), className),
    ...props
  }
));
Alert.displayName = "Alert";
const AlertTitle = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  "h5",
  {
    ref: ref2,
    className: cn$1("mb-1 font-medium leading-none tracking-tight", className),
    ...props
  }
));
AlertTitle.displayName = "AlertTitle";
const AlertDescription = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  "div",
  {
    ref: ref2,
    className: cn$1("text-sm [&_p]:leading-relaxed", className),
    ...props
  }
));
AlertDescription.displayName = "AlertDescription";
var U = 1, Y$1 = 0.9, H = 0.8, J = 0.17, p = 0.1, u = 0.999, $ = 0.9999;
var k$2 = 0.99, m = /[\\\/_+.#"@\[\(\{&]/, B$2 = /[\\\/_+.#"@\[\(\{&]/g, K$2 = /[\s-]/, X = /[\s-]/g;
function G(_2, C, h2, P2, A, f2, O2) {
  if (f2 === C.length) return A === _2.length ? U : k$2;
  var T2 = `${A},${f2}`;
  if (O2[T2] !== void 0) return O2[T2];
  for (var L2 = P2.charAt(f2), c = h2.indexOf(L2, A), S2 = 0, E2, N2, R, M2; c >= 0; ) E2 = G(_2, C, h2, P2, c + 1, f2 + 1, O2), E2 > S2 && (c === A ? E2 *= U : m.test(_2.charAt(c - 1)) ? (E2 *= H, R = _2.slice(A, c - 1).match(B$2), R && A > 0 && (E2 *= Math.pow(u, R.length))) : K$2.test(_2.charAt(c - 1)) ? (E2 *= Y$1, M2 = _2.slice(A, c - 1).match(X), M2 && A > 0 && (E2 *= Math.pow(u, M2.length))) : (E2 *= J, A > 0 && (E2 *= Math.pow(u, c - A))), _2.charAt(c) !== C.charAt(f2) && (E2 *= $)), (E2 < p && h2.charAt(c - 1) === P2.charAt(f2 + 1) || P2.charAt(f2 + 1) === P2.charAt(f2) && h2.charAt(c - 1) !== P2.charAt(f2)) && (N2 = G(_2, C, h2, P2, c + 1, f2 + 2, O2), N2 * p > E2 && (E2 = N2 * p)), E2 > S2 && (S2 = E2), c = h2.indexOf(L2, c + 1);
  return O2[T2] = S2, S2;
}
function D(_2) {
  return _2.toLowerCase().replace(X, " ");
}
function W(_2, C, h2) {
  return _2 = h2 && h2.length > 0 ? `${_2 + " " + h2.join(" ")}` : _2, G(_2, C, D(_2), D(C), 0, 0, {});
}
var AUTOFOCUS_ON_MOUNT = "focusScope.autoFocusOnMount";
var AUTOFOCUS_ON_UNMOUNT = "focusScope.autoFocusOnUnmount";
var EVENT_OPTIONS = { bubbles: false, cancelable: true };
var FOCUS_SCOPE_NAME = "FocusScope";
var FocusScope = reactExports.forwardRef((props, forwardedRef) => {
  const {
    loop = false,
    trapped = false,
    onMountAutoFocus: onMountAutoFocusProp,
    onUnmountAutoFocus: onUnmountAutoFocusProp,
    ...scopeProps
  } = props;
  const [container, setContainer] = reactExports.useState(null);
  const onMountAutoFocus = useCallbackRef$1(onMountAutoFocusProp);
  const onUnmountAutoFocus = useCallbackRef$1(onUnmountAutoFocusProp);
  const lastFocusedElementRef = reactExports.useRef(null);
  const composedRefs = useComposedRefs(forwardedRef, (node) => setContainer(node));
  const focusScope = reactExports.useRef({
    paused: false,
    pause() {
      this.paused = true;
    },
    resume() {
      this.paused = false;
    }
  }).current;
  reactExports.useEffect(() => {
    if (trapped) {
      let handleFocusIn2 = function(event) {
        if (focusScope.paused || !container) return;
        const target = event.target;
        if (container.contains(target)) {
          lastFocusedElementRef.current = target;
        } else {
          focus(lastFocusedElementRef.current, { select: true });
        }
      }, handleFocusOut2 = function(event) {
        if (focusScope.paused || !container) return;
        const relatedTarget = event.relatedTarget;
        if (relatedTarget === null) return;
        if (!container.contains(relatedTarget)) {
          focus(lastFocusedElementRef.current, { select: true });
        }
      }, handleMutations2 = function(mutations) {
        const focusedElement = document.activeElement;
        if (focusedElement !== document.body) return;
        for (const mutation of mutations) {
          if (mutation.removedNodes.length > 0) focus(container);
        }
      };
      document.addEventListener("focusin", handleFocusIn2);
      document.addEventListener("focusout", handleFocusOut2);
      const mutationObserver = new MutationObserver(handleMutations2);
      if (container) mutationObserver.observe(container, { childList: true, subtree: true });
      return () => {
        document.removeEventListener("focusin", handleFocusIn2);
        document.removeEventListener("focusout", handleFocusOut2);
        mutationObserver.disconnect();
      };
    }
  }, [trapped, container, focusScope.paused]);
  reactExports.useEffect(() => {
    if (container) {
      focusScopesStack.add(focusScope);
      const previouslyFocusedElement = document.activeElement;
      const hasFocusedCandidate = container.contains(previouslyFocusedElement);
      if (!hasFocusedCandidate) {
        const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);
        container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
        container.dispatchEvent(mountEvent);
        if (!mountEvent.defaultPrevented) {
          focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });
          if (document.activeElement === previouslyFocusedElement) {
            focus(container);
          }
        }
      }
      return () => {
        container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
        setTimeout(() => {
          const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);
          container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
          container.dispatchEvent(unmountEvent);
          if (!unmountEvent.defaultPrevented) {
            focus(previouslyFocusedElement ?? document.body, { select: true });
          }
          container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
          focusScopesStack.remove(focusScope);
        }, 0);
      };
    }
  }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);
  const handleKeyDown = reactExports.useCallback(
    (event) => {
      if (!loop && !trapped) return;
      if (focusScope.paused) return;
      const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey;
      const focusedElement = document.activeElement;
      if (isTabKey && focusedElement) {
        const container2 = event.currentTarget;
        const [first, last] = getTabbableEdges(container2);
        const hasTabbableElementsInside = first && last;
        if (!hasTabbableElementsInside) {
          if (focusedElement === container2) event.preventDefault();
        } else {
          if (!event.shiftKey && focusedElement === last) {
            event.preventDefault();
            if (loop) focus(first, { select: true });
          } else if (event.shiftKey && focusedElement === first) {
            event.preventDefault();
            if (loop) focus(last, { select: true });
          }
        }
      }
    },
    [loop, trapped, focusScope.paused]
  );
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.div, { tabIndex: -1, ...scopeProps, ref: composedRefs, onKeyDown: handleKeyDown });
});
FocusScope.displayName = FOCUS_SCOPE_NAME;
function focusFirst(candidates, { select = false } = {}) {
  const previouslyFocusedElement = document.activeElement;
  for (const candidate of candidates) {
    focus(candidate, { select });
    if (document.activeElement !== previouslyFocusedElement) return;
  }
}
function getTabbableEdges(container) {
  const candidates = getTabbableCandidates(container);
  const first = findVisible(candidates, container);
  const last = findVisible(candidates.reverse(), container);
  return [first, last];
}
function getTabbableCandidates(container) {
  const nodes = [];
  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
    acceptNode: (node) => {
      const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden";
      if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP;
      return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
    }
  });
  while (walker.nextNode()) nodes.push(walker.currentNode);
  return nodes;
}
function findVisible(elements, container) {
  for (const element of elements) {
    if (!isHidden(element, { upTo: container })) return element;
  }
}
function isHidden(node, { upTo }) {
  if (getComputedStyle(node).visibility === "hidden") return true;
  while (node) {
    if (upTo !== void 0 && node === upTo) return false;
    if (getComputedStyle(node).display === "none") return true;
    node = node.parentElement;
  }
  return false;
}
function isSelectableInput(element) {
  return element instanceof HTMLInputElement && "select" in element;
}
function focus(element, { select = false } = {}) {
  if (element && element.focus) {
    const previouslyFocusedElement = document.activeElement;
    element.focus({ preventScroll: true });
    if (element !== previouslyFocusedElement && isSelectableInput(element) && select)
      element.select();
  }
}
var focusScopesStack = createFocusScopesStack();
function createFocusScopesStack() {
  let stack = [];
  return {
    add(focusScope) {
      const activeFocusScope = stack[0];
      if (focusScope !== activeFocusScope) {
        activeFocusScope?.pause();
      }
      stack = arrayRemove(stack, focusScope);
      stack.unshift(focusScope);
    },
    remove(focusScope) {
      stack = arrayRemove(stack, focusScope);
      stack[0]?.resume();
    }
  };
}
function arrayRemove(array2, item) {
  const updatedArray = [...array2];
  const index2 = updatedArray.indexOf(item);
  if (index2 !== -1) {
    updatedArray.splice(index2, 1);
  }
  return updatedArray;
}
function removeLinks(items2) {
  return items2.filter((item) => item.tagName !== "A");
}
var count = 0;
function useFocusGuards() {
  reactExports.useEffect(() => {
    const edgeGuards = document.querySelectorAll("[data-radix-focus-guard]");
    document.body.insertAdjacentElement("afterbegin", edgeGuards[0] ?? createFocusGuard());
    document.body.insertAdjacentElement("beforeend", edgeGuards[1] ?? createFocusGuard());
    count++;
    return () => {
      if (count === 1) {
        document.querySelectorAll("[data-radix-focus-guard]").forEach((node) => node.remove());
      }
      count--;
    };
  }, []);
}
function createFocusGuard() {
  const element = document.createElement("span");
  element.setAttribute("data-radix-focus-guard", "");
  element.tabIndex = 0;
  element.style.outline = "none";
  element.style.opacity = "0";
  element.style.position = "fixed";
  element.style.pointerEvents = "none";
  return element;
}
var __assign = function() {
  __assign = Object.assign || function __assign2(t2) {
    for (var s2, i2 = 1, n = arguments.length; i2 < n; 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);
};
function __rest(s2, e2) {
  var t2 = {};
  for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
    t2[p2] = s2[p2];
  if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i2 = 0, p2 = Object.getOwnPropertySymbols(s2); i2 < p2.length; i2++) {
      if (e2.indexOf(p2[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i2]))
        t2[p2[i2]] = s2[p2[i2]];
    }
  return t2;
}
function __spreadArray(to2, from, pack) {
  if (pack || arguments.length === 2) for (var i2 = 0, l2 = from.length, ar2; i2 < l2; i2++) {
    if (ar2 || !(i2 in from)) {
      if (!ar2) ar2 = Array.prototype.slice.call(from, 0, i2);
      ar2[i2] = from[i2];
    }
  }
  return to2.concat(ar2 || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
  var e2 = new Error(message);
  return e2.name = "SuppressedError", e2.error = error, e2.suppressed = suppressed, e2;
};
var zeroRightClassName = "right-scroll-bar-position";
var fullWidthClassName = "width-before-scroll-bar";
var noScrollbarsClassName = "with-scroll-bars-hidden";
var removedBarSizeVariable = "--removed-body-scroll-bar-size";
function assignRef(ref2, value) {
  if (typeof ref2 === "function") {
    ref2(value);
  } else if (ref2) {
    ref2.current = value;
  }
  return ref2;
}
function useCallbackRef(initialValue, callback) {
  var ref2 = reactExports.useState(function() {
    return {
      // value
      value: initialValue,
      // last callback
      callback,
      // "memoized" public interface
      facade: {
        get current() {
          return ref2.value;
        },
        set current(value) {
          var last = ref2.value;
          if (last !== value) {
            ref2.value = value;
            ref2.callback(value, last);
          }
        }
      }
    };
  })[0];
  ref2.callback = callback;
  return ref2.facade;
}
var useIsomorphicLayoutEffect = typeof window !== "undefined" ? reactExports.useLayoutEffect : reactExports.useEffect;
var currentValues = /* @__PURE__ */ new WeakMap();
function useMergeRefs(refs, defaultValue) {
  var callbackRef = useCallbackRef(null, function(newValue) {
    return refs.forEach(function(ref2) {
      return assignRef(ref2, newValue);
    });
  });
  useIsomorphicLayoutEffect(function() {
    var oldValue = currentValues.get(callbackRef);
    if (oldValue) {
      var prevRefs_1 = new Set(oldValue);
      var nextRefs_1 = new Set(refs);
      var current_1 = callbackRef.current;
      prevRefs_1.forEach(function(ref2) {
        if (!nextRefs_1.has(ref2)) {
          assignRef(ref2, null);
        }
      });
      nextRefs_1.forEach(function(ref2) {
        if (!prevRefs_1.has(ref2)) {
          assignRef(ref2, current_1);
        }
      });
    }
    currentValues.set(callbackRef, refs);
  }, [refs]);
  return callbackRef;
}
function ItoI(a2) {
  return a2;
}
function innerCreateMedium(defaults2, middleware) {
  if (middleware === void 0) {
    middleware = ItoI;
  }
  var buffer = [];
  var assigned = false;
  var medium = {
    read: function() {
      if (assigned) {
        throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");
      }
      if (buffer.length) {
        return buffer[buffer.length - 1];
      }
      return defaults2;
    },
    useMedium: function(data2) {
      var item = middleware(data2, assigned);
      buffer.push(item);
      return function() {
        buffer = buffer.filter(function(x2) {
          return x2 !== item;
        });
      };
    },
    assignSyncMedium: function(cb) {
      assigned = true;
      while (buffer.length) {
        var cbs = buffer;
        buffer = [];
        cbs.forEach(cb);
      }
      buffer = {
        push: function(x2) {
          return cb(x2);
        },
        filter: function() {
          return buffer;
        }
      };
    },
    assignMedium: function(cb) {
      assigned = true;
      var pendingQueue = [];
      if (buffer.length) {
        var cbs = buffer;
        buffer = [];
        cbs.forEach(cb);
        pendingQueue = buffer;
      }
      var executeQueue = function() {
        var cbs2 = pendingQueue;
        pendingQueue = [];
        cbs2.forEach(cb);
      };
      var cycle = function() {
        return Promise.resolve().then(executeQueue);
      };
      cycle();
      buffer = {
        push: function(x2) {
          pendingQueue.push(x2);
          cycle();
        },
        filter: function(filter) {
          pendingQueue = pendingQueue.filter(filter);
          return buffer;
        }
      };
    }
  };
  return medium;
}
function createSidecarMedium(options) {
  if (options === void 0) {
    options = {};
  }
  var medium = innerCreateMedium(null);
  medium.options = __assign({ async: true, ssr: false }, options);
  return medium;
}
var SideCar$1 = function(_a2) {
  var sideCar = _a2.sideCar, rest = __rest(_a2, ["sideCar"]);
  if (!sideCar) {
    throw new Error("Sidecar: please provide `sideCar` property to import the right car");
  }
  var Target = sideCar.read();
  if (!Target) {
    throw new Error("Sidecar medium not found");
  }
  return reactExports.createElement(Target, __assign({}, rest));
};
SideCar$1.isSideCarExport = true;
function exportSidecar(medium, exported) {
  medium.useMedium(exported);
  return SideCar$1;
}
var effectCar = createSidecarMedium();
var nothing = function() {
  return;
};
var RemoveScroll = reactExports.forwardRef(function(props, parentRef) {
  var ref2 = reactExports.useRef(null);
  var _a2 = reactExports.useState({
    onScrollCapture: nothing,
    onWheelCapture: nothing,
    onTouchMoveCapture: nothing
  }), callbacks = _a2[0], setCallbacks = _a2[1];
  var forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noRelative = props.noRelative, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container = _b === void 0 ? "div" : _b, gapMode = props.gapMode, rest = __rest(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noRelative", "noIsolation", "inert", "allowPinchZoom", "as", "gapMode"]);
  var SideCar2 = sideCar;
  var containerRef = useMergeRefs([ref2, parentRef]);
  var containerProps = __assign(__assign({}, rest), callbacks);
  return reactExports.createElement(
    reactExports.Fragment,
    null,
    enabled && reactExports.createElement(SideCar2, { sideCar: effectCar, removeScrollBar, shards, noRelative, noIsolation, inert, setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref2, gapMode }),
    forwardProps ? reactExports.cloneElement(reactExports.Children.only(children), __assign(__assign({}, containerProps), { ref: containerRef })) : reactExports.createElement(Container, __assign({}, containerProps, { className, ref: containerRef }), children)
  );
});
RemoveScroll.defaultProps = {
  enabled: true,
  removeScrollBar: true,
  inert: false
};
RemoveScroll.classNames = {
  fullWidth: fullWidthClassName,
  zeroRight: zeroRightClassName
};
var getNonce = function() {
  if (typeof __webpack_nonce__ !== "undefined") {
    return __webpack_nonce__;
  }
  return void 0;
};
function makeStyleTag() {
  if (!document)
    return null;
  var tag = document.createElement("style");
  tag.type = "text/css";
  var nonce = getNonce();
  if (nonce) {
    tag.setAttribute("nonce", nonce);
  }
  return tag;
}
function injectStyles(tag, css) {
  if (tag.styleSheet) {
    tag.styleSheet.cssText = css;
  } else {
    tag.appendChild(document.createTextNode(css));
  }
}
function insertStyleTag(tag) {
  var head = document.head || document.getElementsByTagName("head")[0];
  head.appendChild(tag);
}
var stylesheetSingleton = function() {
  var counter = 0;
  var stylesheet = null;
  return {
    add: function(style) {
      if (counter == 0) {
        if (stylesheet = makeStyleTag()) {
          injectStyles(stylesheet, style);
          insertStyleTag(stylesheet);
        }
      }
      counter++;
    },
    remove: function() {
      counter--;
      if (!counter && stylesheet) {
        stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet);
        stylesheet = null;
      }
    }
  };
};
var styleHookSingleton = function() {
  var sheet = stylesheetSingleton();
  return function(styles, isDynamic) {
    reactExports.useEffect(function() {
      sheet.add(styles);
      return function() {
        sheet.remove();
      };
    }, [styles && isDynamic]);
  };
};
var styleSingleton = function() {
  var useStyle = styleHookSingleton();
  var Sheet = function(_a2) {
    var styles = _a2.styles, dynamic = _a2.dynamic;
    useStyle(styles, dynamic);
    return null;
  };
  return Sheet;
};
var zeroGap = {
  left: 0,
  top: 0,
  right: 0,
  gap: 0
};
var parse = function(x2) {
  return parseInt(x2 || "", 10) || 0;
};
var getOffset = function(gapMode) {
  var cs2 = window.getComputedStyle(document.body);
  var left = cs2[gapMode === "padding" ? "paddingLeft" : "marginLeft"];
  var top = cs2[gapMode === "padding" ? "paddingTop" : "marginTop"];
  var right = cs2[gapMode === "padding" ? "paddingRight" : "marginRight"];
  return [parse(left), parse(top), parse(right)];
};
var getGapWidth = function(gapMode) {
  if (gapMode === void 0) {
    gapMode = "margin";
  }
  if (typeof window === "undefined") {
    return zeroGap;
  }
  var offsets = getOffset(gapMode);
  var documentWidth = document.documentElement.clientWidth;
  var windowWidth = window.innerWidth;
  return {
    left: offsets[0],
    top: offsets[1],
    right: offsets[2],
    gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0])
  };
};
var Style = styleSingleton();
var lockAttribute = "data-scroll-locked";
var getStyles = function(_a2, allowRelative, gapMode, important) {
  var left = _a2.left, top = _a2.top, right = _a2.right, gap = _a2.gap;
  if (gapMode === void 0) {
    gapMode = "margin";
  }
  return "\n  .".concat(noScrollbarsClassName, " {\n   overflow: hidden ").concat(important, ";\n   padding-right: ").concat(gap, "px ").concat(important, ";\n  }\n  body[").concat(lockAttribute, "] {\n    overflow: hidden ").concat(important, ";\n    overscroll-behavior: contain;\n    ").concat([
    allowRelative && "position: relative ".concat(important, ";"),
    gapMode === "margin" && "\n    padding-left: ".concat(left, "px;\n    padding-top: ").concat(top, "px;\n    padding-right: ").concat(right, "px;\n    margin-left:0;\n    margin-top:0;\n    margin-right: ").concat(gap, "px ").concat(important, ";\n    "),
    gapMode === "padding" && "padding-right: ".concat(gap, "px ").concat(important, ";")
  ].filter(Boolean).join(""), "\n  }\n  \n  .").concat(zeroRightClassName, " {\n    right: ").concat(gap, "px ").concat(important, ";\n  }\n  \n  .").concat(fullWidthClassName, " {\n    margin-right: ").concat(gap, "px ").concat(important, ";\n  }\n  \n  .").concat(zeroRightClassName, " .").concat(zeroRightClassName, " {\n    right: 0 ").concat(important, ";\n  }\n  \n  .").concat(fullWidthClassName, " .").concat(fullWidthClassName, " {\n    margin-right: 0 ").concat(important, ";\n  }\n  \n  body[").concat(lockAttribute, "] {\n    ").concat(removedBarSizeVariable, ": ").concat(gap, "px;\n  }\n");
};
var getCurrentUseCounter = function() {
  var counter = parseInt(document.body.getAttribute(lockAttribute) || "0", 10);
  return isFinite(counter) ? counter : 0;
};
var useLockAttribute = function() {
  reactExports.useEffect(function() {
    document.body.setAttribute(lockAttribute, (getCurrentUseCounter() + 1).toString());
    return function() {
      var newCounter = getCurrentUseCounter() - 1;
      if (newCounter <= 0) {
        document.body.removeAttribute(lockAttribute);
      } else {
        document.body.setAttribute(lockAttribute, newCounter.toString());
      }
    };
  }, []);
};
var RemoveScrollBar = function(_a2) {
  var noRelative = _a2.noRelative, noImportant = _a2.noImportant, _b = _a2.gapMode, gapMode = _b === void 0 ? "margin" : _b;
  useLockAttribute();
  var gap = reactExports.useMemo(function() {
    return getGapWidth(gapMode);
  }, [gapMode]);
  return reactExports.createElement(Style, { styles: getStyles(gap, !noRelative, gapMode, !noImportant ? "!important" : "") });
};
var passiveSupported = false;
if (typeof window !== "undefined") {
  try {
    var options = Object.defineProperty({}, "passive", {
      get: function() {
        passiveSupported = true;
        return true;
      }
    });
    window.addEventListener("test", options, options);
    window.removeEventListener("test", options, options);
  } catch (err) {
    passiveSupported = false;
  }
}
var nonPassive = passiveSupported ? { passive: false } : false;
var alwaysContainsScroll = function(node) {
  return node.tagName === "TEXTAREA";
};
var elementCanBeScrolled = function(node, overflow) {
  if (!(node instanceof Element)) {
    return false;
  }
  var styles = window.getComputedStyle(node);
  return (
    // not-not-scrollable
    styles[overflow] !== "hidden" && // contains scroll inside self
    !(styles.overflowY === styles.overflowX && !alwaysContainsScroll(node) && styles[overflow] === "visible")
  );
};
var elementCouldBeVScrolled = function(node) {
  return elementCanBeScrolled(node, "overflowY");
};
var elementCouldBeHScrolled = function(node) {
  return elementCanBeScrolled(node, "overflowX");
};
var locationCouldBeScrolled = function(axis, node) {
  var ownerDocument = node.ownerDocument;
  var current = node;
  do {
    if (typeof ShadowRoot !== "undefined" && current instanceof ShadowRoot) {
      current = current.host;
    }
    var isScrollable = elementCouldBeScrolled(axis, current);
    if (isScrollable) {
      var _a2 = getScrollVariables(axis, current), scrollHeight = _a2[1], clientHeight = _a2[2];
      if (scrollHeight > clientHeight) {
        return true;
      }
    }
    current = current.parentNode;
  } while (current && current !== ownerDocument.body);
  return false;
};
var getVScrollVariables = function(_a2) {
  var scrollTop = _a2.scrollTop, scrollHeight = _a2.scrollHeight, clientHeight = _a2.clientHeight;
  return [
    scrollTop,
    scrollHeight,
    clientHeight
  ];
};
var getHScrollVariables = function(_a2) {
  var scrollLeft = _a2.scrollLeft, scrollWidth = _a2.scrollWidth, clientWidth = _a2.clientWidth;
  return [
    scrollLeft,
    scrollWidth,
    clientWidth
  ];
};
var elementCouldBeScrolled = function(axis, node) {
  return axis === "v" ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node);
};
var getScrollVariables = function(axis, node) {
  return axis === "v" ? getVScrollVariables(node) : getHScrollVariables(node);
};
var getDirectionFactor = function(axis, direction) {
  return axis === "h" && direction === "rtl" ? -1 : 1;
};
var handleScroll = function(axis, endTarget, event, sourceDelta, noOverscroll) {
  var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction);
  var delta = directionFactor * sourceDelta;
  var target = event.target;
  var targetInLock = endTarget.contains(target);
  var shouldCancelScroll = false;
  var isDeltaPositive = delta > 0;
  var availableScroll = 0;
  var availableScrollTop = 0;
  do {
    if (!target) {
      break;
    }
    var _a2 = getScrollVariables(axis, target), position = _a2[0], scroll_1 = _a2[1], capacity = _a2[2];
    var elementScroll = scroll_1 - capacity - directionFactor * position;
    if (position || elementScroll) {
      if (elementCouldBeScrolled(axis, target)) {
        availableScroll += elementScroll;
        availableScrollTop += position;
      }
    }
    var parent_1 = target.parentNode;
    target = parent_1 && parent_1.nodeType === Node.DOCUMENT_FRAGMENT_NODE ? parent_1.host : parent_1;
  } while (
    // portaled content
    !targetInLock && target !== document.body || // self content
    targetInLock && (endTarget.contains(target) || endTarget === target)
  );
  if (isDeltaPositive && (Math.abs(availableScroll) < 1 || false)) {
    shouldCancelScroll = true;
  } else if (!isDeltaPositive && (Math.abs(availableScrollTop) < 1 || false)) {
    shouldCancelScroll = true;
  }
  return shouldCancelScroll;
};
var getTouchXY = function(event) {
  return "changedTouches" in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0];
};
var getDeltaXY = function(event) {
  return [event.deltaX, event.deltaY];
};
var extractRef = function(ref2) {
  return ref2 && "current" in ref2 ? ref2.current : ref2;
};
var deltaCompare = function(x2, y) {
  return x2[0] === y[0] && x2[1] === y[1];
};
var generateStyle = function(id2) {
  return "\n  .block-interactivity-".concat(id2, " {pointer-events: none;}\n  .allow-interactivity-").concat(id2, " {pointer-events: all;}\n");
};
var idCounter = 0;
var lockStack = [];
function RemoveScrollSideCar(props) {
  var shouldPreventQueue = reactExports.useRef([]);
  var touchStartRef = reactExports.useRef([0, 0]);
  var activeAxis = reactExports.useRef();
  var id2 = reactExports.useState(idCounter++)[0];
  var Style2 = reactExports.useState(styleSingleton)[0];
  var lastProps = reactExports.useRef(props);
  reactExports.useEffect(function() {
    lastProps.current = props;
  }, [props]);
  reactExports.useEffect(function() {
    if (props.inert) {
      document.body.classList.add("block-interactivity-".concat(id2));
      var allow_1 = __spreadArray([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean);
      allow_1.forEach(function(el2) {
        return el2.classList.add("allow-interactivity-".concat(id2));
      });
      return function() {
        document.body.classList.remove("block-interactivity-".concat(id2));
        allow_1.forEach(function(el2) {
          return el2.classList.remove("allow-interactivity-".concat(id2));
        });
      };
    }
    return;
  }, [props.inert, props.lockRef.current, props.shards]);
  var shouldCancelEvent = reactExports.useCallback(function(event, parent) {
    if ("touches" in event && event.touches.length === 2 || event.type === "wheel" && event.ctrlKey) {
      return !lastProps.current.allowPinchZoom;
    }
    var touch = getTouchXY(event);
    var touchStart = touchStartRef.current;
    var deltaX = "deltaX" in event ? event.deltaX : touchStart[0] - touch[0];
    var deltaY = "deltaY" in event ? event.deltaY : touchStart[1] - touch[1];
    var currentAxis;
    var target = event.target;
    var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? "h" : "v";
    if ("touches" in event && moveDirection === "h" && target.type === "range") {
      return false;
    }
    var selection = window.getSelection();
    var anchorNode = selection && selection.anchorNode;
    var isTouchingSelection = anchorNode ? anchorNode === target || anchorNode.contains(target) : false;
    if (isTouchingSelection) {
      return false;
    }
    var canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target);
    if (!canBeScrolledInMainDirection) {
      return true;
    }
    if (canBeScrolledInMainDirection) {
      currentAxis = moveDirection;
    } else {
      currentAxis = moveDirection === "v" ? "h" : "v";
      canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target);
    }
    if (!canBeScrolledInMainDirection) {
      return false;
    }
    if (!activeAxis.current && "changedTouches" in event && (deltaX || deltaY)) {
      activeAxis.current = currentAxis;
    }
    if (!currentAxis) {
      return true;
    }
    var cancelingAxis = activeAxis.current || currentAxis;
    return handleScroll(cancelingAxis, parent, event, cancelingAxis === "h" ? deltaX : deltaY);
  }, []);
  var shouldPrevent = reactExports.useCallback(function(_event) {
    var event = _event;
    if (!lockStack.length || lockStack[lockStack.length - 1] !== Style2) {
      return;
    }
    var delta = "deltaY" in event ? getDeltaXY(event) : getTouchXY(event);
    var sourceEvent = shouldPreventQueue.current.filter(function(e2) {
      return e2.name === event.type && (e2.target === event.target || event.target === e2.shadowParent) && deltaCompare(e2.delta, delta);
    })[0];
    if (sourceEvent && sourceEvent.should) {
      if (event.cancelable) {
        event.preventDefault();
      }
      return;
    }
    if (!sourceEvent) {
      var shardNodes = (lastProps.current.shards || []).map(extractRef).filter(Boolean).filter(function(node) {
        return node.contains(event.target);
      });
      var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation;
      if (shouldStop) {
        if (event.cancelable) {
          event.preventDefault();
        }
      }
    }
  }, []);
  var shouldCancel = reactExports.useCallback(function(name2, delta, target, should) {
    var event = { name: name2, delta, target, should, shadowParent: getOutermostShadowParent(target) };
    shouldPreventQueue.current.push(event);
    setTimeout(function() {
      shouldPreventQueue.current = shouldPreventQueue.current.filter(function(e2) {
        return e2 !== event;
      });
    }, 1);
  }, []);
  var scrollTouchStart = reactExports.useCallback(function(event) {
    touchStartRef.current = getTouchXY(event);
    activeAxis.current = void 0;
  }, []);
  var scrollWheel = reactExports.useCallback(function(event) {
    shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current));
  }, []);
  var scrollTouchMove = reactExports.useCallback(function(event) {
    shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current));
  }, []);
  reactExports.useEffect(function() {
    lockStack.push(Style2);
    props.setCallbacks({
      onScrollCapture: scrollWheel,
      onWheelCapture: scrollWheel,
      onTouchMoveCapture: scrollTouchMove
    });
    document.addEventListener("wheel", shouldPrevent, nonPassive);
    document.addEventListener("touchmove", shouldPrevent, nonPassive);
    document.addEventListener("touchstart", scrollTouchStart, nonPassive);
    return function() {
      lockStack = lockStack.filter(function(inst) {
        return inst !== Style2;
      });
      document.removeEventListener("wheel", shouldPrevent, nonPassive);
      document.removeEventListener("touchmove", shouldPrevent, nonPassive);
      document.removeEventListener("touchstart", scrollTouchStart, nonPassive);
    };
  }, []);
  var removeScrollBar = props.removeScrollBar, inert = props.inert;
  return reactExports.createElement(
    reactExports.Fragment,
    null,
    inert ? reactExports.createElement(Style2, { styles: generateStyle(id2) }) : null,
    removeScrollBar ? reactExports.createElement(RemoveScrollBar, { noRelative: props.noRelative, gapMode: props.gapMode }) : null
  );
}
function getOutermostShadowParent(node) {
  var shadowParent = null;
  while (node !== null) {
    if (node instanceof ShadowRoot) {
      shadowParent = node.host;
      node = node.host;
    }
    node = node.parentNode;
  }
  return shadowParent;
}
const SideCar = exportSidecar(effectCar, RemoveScrollSideCar);
var ReactRemoveScroll = reactExports.forwardRef(function(props, ref2) {
  return reactExports.createElement(RemoveScroll, __assign({}, props, { ref: ref2, sideCar: SideCar }));
});
ReactRemoveScroll.classNames = RemoveScroll.classNames;
var getDefaultParent = function(originalTarget) {
  if (typeof document === "undefined") {
    return null;
  }
  var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget;
  return sampleTarget.ownerDocument.body;
};
var counterMap = /* @__PURE__ */ new WeakMap();
var uncontrolledNodes = /* @__PURE__ */ new WeakMap();
var markerMap = {};
var lockCount = 0;
var unwrapHost = function(node) {
  return node && (node.host || unwrapHost(node.parentNode));
};
var correctTargets = function(parent, targets) {
  return targets.map(function(target) {
    if (parent.contains(target)) {
      return target;
    }
    var correctedTarget = unwrapHost(target);
    if (correctedTarget && parent.contains(correctedTarget)) {
      return correctedTarget;
    }
    console.error("aria-hidden", target, "in not contained inside", parent, ". Doing nothing");
    return null;
  }).filter(function(x2) {
    return Boolean(x2);
  });
};
var applyAttributeToOthers = function(originalTarget, parentNode, markerName, controlAttribute) {
  var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]);
  if (!markerMap[markerName]) {
    markerMap[markerName] = /* @__PURE__ */ new WeakMap();
  }
  var markerCounter = markerMap[markerName];
  var hiddenNodes = [];
  var elementsToKeep = /* @__PURE__ */ new Set();
  var elementsToStop = new Set(targets);
  var keep = function(el2) {
    if (!el2 || elementsToKeep.has(el2)) {
      return;
    }
    elementsToKeep.add(el2);
    keep(el2.parentNode);
  };
  targets.forEach(keep);
  var deep = function(parent) {
    if (!parent || elementsToStop.has(parent)) {
      return;
    }
    Array.prototype.forEach.call(parent.children, function(node) {
      if (elementsToKeep.has(node)) {
        deep(node);
      } else {
        try {
          var attr = node.getAttribute(controlAttribute);
          var alreadyHidden = attr !== null && attr !== "false";
          var counterValue = (counterMap.get(node) || 0) + 1;
          var markerValue = (markerCounter.get(node) || 0) + 1;
          counterMap.set(node, counterValue);
          markerCounter.set(node, markerValue);
          hiddenNodes.push(node);
          if (counterValue === 1 && alreadyHidden) {
            uncontrolledNodes.set(node, true);
          }
          if (markerValue === 1) {
            node.setAttribute(markerName, "true");
          }
          if (!alreadyHidden) {
            node.setAttribute(controlAttribute, "true");
          }
        } catch (e2) {
          console.error("aria-hidden: cannot operate on ", node, e2);
        }
      }
    });
  };
  deep(parentNode);
  elementsToKeep.clear();
  lockCount++;
  return function() {
    hiddenNodes.forEach(function(node) {
      var counterValue = counterMap.get(node) - 1;
      var markerValue = markerCounter.get(node) - 1;
      counterMap.set(node, counterValue);
      markerCounter.set(node, markerValue);
      if (!counterValue) {
        if (!uncontrolledNodes.has(node)) {
          node.removeAttribute(controlAttribute);
        }
        uncontrolledNodes.delete(node);
      }
      if (!markerValue) {
        node.removeAttribute(markerName);
      }
    });
    lockCount--;
    if (!lockCount) {
      counterMap = /* @__PURE__ */ new WeakMap();
      counterMap = /* @__PURE__ */ new WeakMap();
      uncontrolledNodes = /* @__PURE__ */ new WeakMap();
      markerMap = {};
    }
  };
};
var hideOthers = function(originalTarget, parentNode, markerName) {
  if (markerName === void 0) {
    markerName = "data-aria-hidden";
  }
  var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]);
  var activeParentNode = getDefaultParent(originalTarget);
  if (!activeParentNode) {
    return function() {
      return null;
    };
  }
  targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll("[aria-live], script")));
  return applyAttributeToOthers(targets, activeParentNode, markerName, "aria-hidden");
};
// @__NO_SIDE_EFFECTS__
function createSlot$2(ownerName) {
  const SlotClone = /* @__PURE__ */ createSlotClone$2(ownerName);
  const Slot2 = reactExports.forwardRef((props, forwardedRef) => {
    const { children, ...slotProps } = props;
    const childrenArray = reactExports.Children.toArray(children);
    const slottable = childrenArray.find(isSlottable$2);
    if (slottable) {
      const newElement = slottable.props.children;
      const newChildren = childrenArray.map((child) => {
        if (child === slottable) {
          if (reactExports.Children.count(newElement) > 1) return reactExports.Children.only(null);
          return reactExports.isValidElement(newElement) ? newElement.props.children : null;
        } else {
          return child;
        }
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children: reactExports.isValidElement(newElement) ? reactExports.cloneElement(newElement, void 0, newChildren) : null });
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children });
  });
  Slot2.displayName = `${ownerName}.Slot`;
  return Slot2;
}
// @__NO_SIDE_EFFECTS__
function createSlotClone$2(ownerName) {
  const SlotClone = reactExports.forwardRef((props, forwardedRef) => {
    const { children, ...slotProps } = props;
    if (reactExports.isValidElement(children)) {
      const childrenRef = getElementRef$2(children);
      const props2 = mergeProps$2(slotProps, children.props);
      if (children.type !== reactExports.Fragment) {
        props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;
      }
      return reactExports.cloneElement(children, props2);
    }
    return reactExports.Children.count(children) > 1 ? reactExports.Children.only(null) : null;
  });
  SlotClone.displayName = `${ownerName}.SlotClone`;
  return SlotClone;
}
var SLOTTABLE_IDENTIFIER$3 = /* @__PURE__ */ Symbol("radix.slottable");
function isSlottable$2(child) {
  return reactExports.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER$3;
}
function mergeProps$2(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          const result = childPropValue(...args);
          slotPropValue(...args);
          return result;
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef$2(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}
var DIALOG_NAME = "Dialog";
var [createDialogContext] = createContextScope(DIALOG_NAME);
var [DialogProvider, useDialogContext] = createDialogContext(DIALOG_NAME);
var Dialog$1 = (props) => {
  const {
    __scopeDialog,
    children,
    open: openProp,
    defaultOpen,
    onOpenChange,
    modal = true
  } = props;
  const triggerRef = reactExports.useRef(null);
  const contentRef = reactExports.useRef(null);
  const [open, setOpen] = useControllableState({
    prop: openProp,
    defaultProp: defaultOpen ?? false,
    onChange: onOpenChange,
    caller: DIALOG_NAME
  });
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    DialogProvider,
    {
      scope: __scopeDialog,
      triggerRef,
      contentRef,
      contentId: useId(),
      titleId: useId(),
      descriptionId: useId(),
      open,
      onOpenChange: setOpen,
      onOpenToggle: reactExports.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen]),
      modal,
      children
    }
  );
};
Dialog$1.displayName = DIALOG_NAME;
var TRIGGER_NAME$4 = "DialogTrigger";
var DialogTrigger = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDialog, ...triggerProps } = props;
    const context = useDialogContext(TRIGGER_NAME$4, __scopeDialog);
    const composedTriggerRef = useComposedRefs(forwardedRef, context.triggerRef);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.button,
      {
        type: "button",
        "aria-haspopup": "dialog",
        "aria-expanded": context.open,
        "aria-controls": context.contentId,
        "data-state": getState$3(context.open),
        ...triggerProps,
        ref: composedTriggerRef,
        onClick: composeEventHandlers(props.onClick, context.onOpenToggle)
      }
    );
  }
);
DialogTrigger.displayName = TRIGGER_NAME$4;
var PORTAL_NAME$3 = "DialogPortal";
var [PortalProvider$2, usePortalContext$2] = createDialogContext(PORTAL_NAME$3, {
  forceMount: void 0
});
var DialogPortal$1 = (props) => {
  const { __scopeDialog, forceMount, children, container } = props;
  const context = useDialogContext(PORTAL_NAME$3, __scopeDialog);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(PortalProvider$2, { scope: __scopeDialog, forceMount, children: reactExports.Children.map(children, (child) => /* @__PURE__ */ jsxRuntimeExports.jsx(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Portal$3, { asChild: true, container, children: child }) })) });
};
DialogPortal$1.displayName = PORTAL_NAME$3;
var OVERLAY_NAME = "DialogOverlay";
var DialogOverlay$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const portalContext = usePortalContext$2(OVERLAY_NAME, props.__scopeDialog);
    const { forceMount = portalContext.forceMount, ...overlayProps } = props;
    const context = useDialogContext(OVERLAY_NAME, props.__scopeDialog);
    return context.modal ? /* @__PURE__ */ jsxRuntimeExports.jsx(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ jsxRuntimeExports.jsx(DialogOverlayImpl, { ...overlayProps, ref: forwardedRef }) }) : null;
  }
);
DialogOverlay$1.displayName = OVERLAY_NAME;
var Slot$2 = /* @__PURE__ */ createSlot$2("DialogOverlay.RemoveScroll");
var DialogOverlayImpl = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDialog, ...overlayProps } = props;
    const context = useDialogContext(OVERLAY_NAME, __scopeDialog);
    return (
      // Make sure `Content` is scrollable even when it doesn't live inside `RemoveScroll`
      // ie. when `Overlay` and `Content` are siblings
      /* @__PURE__ */ jsxRuntimeExports.jsx(ReactRemoveScroll, { as: Slot$2, allowPinchZoom: true, shards: [context.contentRef], children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Primitive$1.div,
        {
          "data-state": getState$3(context.open),
          ...overlayProps,
          ref: forwardedRef,
          style: { pointerEvents: "auto", ...overlayProps.style }
        }
      ) })
    );
  }
);
var CONTENT_NAME$4 = "DialogContent";
var DialogContent$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const portalContext = usePortalContext$2(CONTENT_NAME$4, props.__scopeDialog);
    const { forceMount = portalContext.forceMount, ...contentProps } = props;
    const context = useDialogContext(CONTENT_NAME$4, props.__scopeDialog);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Presence, { present: forceMount || context.open, children: context.modal ? /* @__PURE__ */ jsxRuntimeExports.jsx(DialogContentModal, { ...contentProps, ref: forwardedRef }) : /* @__PURE__ */ jsxRuntimeExports.jsx(DialogContentNonModal, { ...contentProps, ref: forwardedRef }) });
  }
);
DialogContent$1.displayName = CONTENT_NAME$4;
var DialogContentModal = reactExports.forwardRef(
  (props, forwardedRef) => {
    const context = useDialogContext(CONTENT_NAME$4, props.__scopeDialog);
    const contentRef = reactExports.useRef(null);
    const composedRefs = useComposedRefs(forwardedRef, context.contentRef, contentRef);
    reactExports.useEffect(() => {
      const content = contentRef.current;
      if (content) return hideOthers(content);
    }, []);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      DialogContentImpl,
      {
        ...props,
        ref: composedRefs,
        trapFocus: context.open,
        disableOutsidePointerEvents: true,
        onCloseAutoFocus: composeEventHandlers(props.onCloseAutoFocus, (event) => {
          event.preventDefault();
          context.triggerRef.current?.focus();
        }),
        onPointerDownOutside: composeEventHandlers(props.onPointerDownOutside, (event) => {
          const originalEvent = event.detail.originalEvent;
          const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;
          const isRightClick = originalEvent.button === 2 || ctrlLeftClick;
          if (isRightClick) event.preventDefault();
        }),
        onFocusOutside: composeEventHandlers(
          props.onFocusOutside,
          (event) => event.preventDefault()
        )
      }
    );
  }
);
var DialogContentNonModal = reactExports.forwardRef(
  (props, forwardedRef) => {
    const context = useDialogContext(CONTENT_NAME$4, props.__scopeDialog);
    const hasInteractedOutsideRef = reactExports.useRef(false);
    const hasPointerDownOutsideRef = reactExports.useRef(false);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      DialogContentImpl,
      {
        ...props,
        ref: forwardedRef,
        trapFocus: false,
        disableOutsidePointerEvents: false,
        onCloseAutoFocus: (event) => {
          props.onCloseAutoFocus?.(event);
          if (!event.defaultPrevented) {
            if (!hasInteractedOutsideRef.current) context.triggerRef.current?.focus();
            event.preventDefault();
          }
          hasInteractedOutsideRef.current = false;
          hasPointerDownOutsideRef.current = false;
        },
        onInteractOutside: (event) => {
          props.onInteractOutside?.(event);
          if (!event.defaultPrevented) {
            hasInteractedOutsideRef.current = true;
            if (event.detail.originalEvent.type === "pointerdown") {
              hasPointerDownOutsideRef.current = true;
            }
          }
          const target = event.target;
          const targetIsTrigger = context.triggerRef.current?.contains(target);
          if (targetIsTrigger) event.preventDefault();
          if (event.detail.originalEvent.type === "focusin" && hasPointerDownOutsideRef.current) {
            event.preventDefault();
          }
        }
      }
    );
  }
);
var DialogContentImpl = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDialog, trapFocus, onOpenAutoFocus, onCloseAutoFocus, ...contentProps } = props;
    const context = useDialogContext(CONTENT_NAME$4, __scopeDialog);
    const contentRef = reactExports.useRef(null);
    const composedRefs = useComposedRefs(forwardedRef, contentRef);
    useFocusGuards();
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        FocusScope,
        {
          asChild: true,
          loop: true,
          trapped: trapFocus,
          onMountAutoFocus: onOpenAutoFocus,
          onUnmountAutoFocus: onCloseAutoFocus,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            DismissableLayer,
            {
              role: "dialog",
              id: context.contentId,
              "aria-describedby": context.descriptionId,
              "aria-labelledby": context.titleId,
              "data-state": getState$3(context.open),
              ...contentProps,
              ref: composedRefs,
              onDismiss: () => context.onOpenChange(false)
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(TitleWarning, { titleId: context.titleId }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(DescriptionWarning, { contentRef, descriptionId: context.descriptionId })
      ] })
    ] });
  }
);
var TITLE_NAME = "DialogTitle";
var DialogTitle$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDialog, ...titleProps } = props;
    const context = useDialogContext(TITLE_NAME, __scopeDialog);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.h2, { id: context.titleId, ...titleProps, ref: forwardedRef });
  }
);
DialogTitle$1.displayName = TITLE_NAME;
var DESCRIPTION_NAME = "DialogDescription";
var DialogDescription$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDialog, ...descriptionProps } = props;
    const context = useDialogContext(DESCRIPTION_NAME, __scopeDialog);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.p, { id: context.descriptionId, ...descriptionProps, ref: forwardedRef });
  }
);
DialogDescription$1.displayName = DESCRIPTION_NAME;
var CLOSE_NAME$1 = "DialogClose";
var DialogClose = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDialog, ...closeProps } = props;
    const context = useDialogContext(CLOSE_NAME$1, __scopeDialog);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.button,
      {
        type: "button",
        ...closeProps,
        ref: forwardedRef,
        onClick: composeEventHandlers(props.onClick, () => context.onOpenChange(false))
      }
    );
  }
);
DialogClose.displayName = CLOSE_NAME$1;
function getState$3(open) {
  return open ? "open" : "closed";
}
var TITLE_WARNING_NAME = "DialogTitleWarning";
var [WarningProvider, useWarningContext] = createContext2(TITLE_WARNING_NAME, {
  contentName: CONTENT_NAME$4,
  titleName: TITLE_NAME,
  docsSlug: "dialog"
});
var TitleWarning = ({ titleId }) => {
  const titleWarningContext = useWarningContext(TITLE_WARNING_NAME);
  const MESSAGE = `\`${titleWarningContext.contentName}\` requires a \`${titleWarningContext.titleName}\` for the component to be accessible for screen reader users.

If you want to hide the \`${titleWarningContext.titleName}\`, you can wrap it with our VisuallyHidden component.

For more information, see https://radix-ui.com/primitives/docs/components/${titleWarningContext.docsSlug}`;
  reactExports.useEffect(() => {
    if (titleId) {
      const hasTitle = document.getElementById(titleId);
      if (!hasTitle) console.error(MESSAGE);
    }
  }, [MESSAGE, titleId]);
  return null;
};
var DESCRIPTION_WARNING_NAME = "DialogDescriptionWarning";
var DescriptionWarning = ({ contentRef, descriptionId }) => {
  const descriptionWarningContext = useWarningContext(DESCRIPTION_WARNING_NAME);
  const MESSAGE = `Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${descriptionWarningContext.contentName}}.`;
  reactExports.useEffect(() => {
    const describedById = contentRef.current?.getAttribute("aria-describedby");
    if (descriptionId && describedById) {
      const hasDescription = document.getElementById(descriptionId);
      if (!hasDescription) console.warn(MESSAGE);
    }
  }, [MESSAGE, contentRef, descriptionId]);
  return null;
};
var Root$3 = Dialog$1;
var Portal$2 = DialogPortal$1;
var Overlay = DialogOverlay$1;
var Content$1 = DialogContent$1;
var Title = DialogTitle$1;
var Description = DialogDescription$1;
var Close = DialogClose;
var N$1 = '[cmdk-group=""]', Y = '[cmdk-group-items=""]', be = '[cmdk-group-heading=""]', le$1 = '[cmdk-item=""]', ce$1 = `${le$1}:not([aria-disabled="true"])`, Z$1 = "cmdk-item-select", T = "data-value", Re$1 = (r2, o2, n) => W(r2, o2, n), ue = reactExports.createContext(void 0), K$1 = () => reactExports.useContext(ue), de$1 = reactExports.createContext(void 0), ee$1 = () => reactExports.useContext(de$1), fe$1 = reactExports.createContext(void 0), me = reactExports.forwardRef((r2, o2) => {
  let n = L$1(() => {
    var e2, a2;
    return { search: "", value: (a2 = (e2 = r2.value) != null ? e2 : r2.defaultValue) != null ? a2 : "", selectedItemId: void 0, filtered: { count: 0, items: /* @__PURE__ */ new Map(), groups: /* @__PURE__ */ new Set() } };
  }), u2 = L$1(() => /* @__PURE__ */ new Set()), c = L$1(() => /* @__PURE__ */ new Map()), d = L$1(() => /* @__PURE__ */ new Map()), f2 = L$1(() => /* @__PURE__ */ new Set()), p2 = pe$1(r2), { label: b2, children: m2, value: R, onValueChange: x2, filter: C, shouldFilter: S2, loop: A, disablePointerSelection: ge2 = false, vimBindings: j = true, ...O2 } = r2, $2 = useId(), q2 = useId(), _2 = useId(), I2 = reactExports.useRef(null), v2 = ke$1();
  k$1(() => {
    if (R !== void 0) {
      let e2 = R.trim();
      n.current.value = e2, E2.emit();
    }
  }, [R]), k$1(() => {
    v2(6, ne);
  }, []);
  let E2 = reactExports.useMemo(() => ({ subscribe: (e2) => (f2.current.add(e2), () => f2.current.delete(e2)), snapshot: () => n.current, setState: (e2, a2, s2) => {
    var i2, l2, g2, y;
    if (!Object.is(n.current[e2], a2)) {
      if (n.current[e2] = a2, e2 === "search") J2(), z2(), v2(1, W2);
      else if (e2 === "value") {
        if (document.activeElement.hasAttribute("cmdk-input") || document.activeElement.hasAttribute("cmdk-root")) {
          let h2 = document.getElementById(_2);
          h2 ? h2.focus() : (i2 = document.getElementById($2)) == null || i2.focus();
        }
        if (v2(7, () => {
          var h2;
          n.current.selectedItemId = (h2 = M2()) == null ? void 0 : h2.id, E2.emit();
        }), s2 || v2(5, ne), ((l2 = p2.current) == null ? void 0 : l2.value) !== void 0) {
          let h2 = a2 != null ? a2 : "";
          (y = (g2 = p2.current).onValueChange) == null || y.call(g2, h2);
          return;
        }
      }
      E2.emit();
    }
  }, emit: () => {
    f2.current.forEach((e2) => e2());
  } }), []), U2 = reactExports.useMemo(() => ({ value: (e2, a2, s2) => {
    var i2;
    a2 !== ((i2 = d.current.get(e2)) == null ? void 0 : i2.value) && (d.current.set(e2, { value: a2, keywords: s2 }), n.current.filtered.items.set(e2, te2(a2, s2)), v2(2, () => {
      z2(), E2.emit();
    }));
  }, item: (e2, a2) => (u2.current.add(e2), a2 && (c.current.has(a2) ? c.current.get(a2).add(e2) : c.current.set(a2, /* @__PURE__ */ new Set([e2]))), v2(3, () => {
    J2(), z2(), n.current.value || W2(), E2.emit();
  }), () => {
    d.current.delete(e2), u2.current.delete(e2), n.current.filtered.items.delete(e2);
    let s2 = M2();
    v2(4, () => {
      J2(), (s2 == null ? void 0 : s2.getAttribute("id")) === e2 && W2(), E2.emit();
    });
  }), group: (e2) => (c.current.has(e2) || c.current.set(e2, /* @__PURE__ */ new Set()), () => {
    d.current.delete(e2), c.current.delete(e2);
  }), filter: () => p2.current.shouldFilter, label: b2 || r2["aria-label"], getDisablePointerSelection: () => p2.current.disablePointerSelection, listId: $2, inputId: _2, labelId: q2, listInnerRef: I2 }), []);
  function te2(e2, a2) {
    var i2, l2;
    let s2 = (l2 = (i2 = p2.current) == null ? void 0 : i2.filter) != null ? l2 : Re$1;
    return e2 ? s2(e2, n.current.search, a2) : 0;
  }
  function z2() {
    if (!n.current.search || p2.current.shouldFilter === false) return;
    let e2 = n.current.filtered.items, a2 = [];
    n.current.filtered.groups.forEach((i2) => {
      let l2 = c.current.get(i2), g2 = 0;
      l2.forEach((y) => {
        let h2 = e2.get(y);
        g2 = Math.max(h2, g2);
      }), a2.push([i2, g2]);
    });
    let s2 = I2.current;
    V2().sort((i2, l2) => {
      var h2, F2;
      let g2 = i2.getAttribute("id"), y = l2.getAttribute("id");
      return ((h2 = e2.get(y)) != null ? h2 : 0) - ((F2 = e2.get(g2)) != null ? F2 : 0);
    }).forEach((i2) => {
      let l2 = i2.closest(Y);
      l2 ? l2.appendChild(i2.parentElement === l2 ? i2 : i2.closest(`${Y} > *`)) : s2.appendChild(i2.parentElement === s2 ? i2 : i2.closest(`${Y} > *`));
    }), a2.sort((i2, l2) => l2[1] - i2[1]).forEach((i2) => {
      var g2;
      let l2 = (g2 = I2.current) == null ? void 0 : g2.querySelector(`${N$1}[${T}="${encodeURIComponent(i2[0])}"]`);
      l2 == null || l2.parentElement.appendChild(l2);
    });
  }
  function W2() {
    let e2 = V2().find((s2) => s2.getAttribute("aria-disabled") !== "true"), a2 = e2 == null ? void 0 : e2.getAttribute(T);
    E2.setState("value", a2 || void 0);
  }
  function J2() {
    var a2, s2, i2, l2;
    if (!n.current.search || p2.current.shouldFilter === false) {
      n.current.filtered.count = u2.current.size;
      return;
    }
    n.current.filtered.groups = /* @__PURE__ */ new Set();
    let e2 = 0;
    for (let g2 of u2.current) {
      let y = (s2 = (a2 = d.current.get(g2)) == null ? void 0 : a2.value) != null ? s2 : "", h2 = (l2 = (i2 = d.current.get(g2)) == null ? void 0 : i2.keywords) != null ? l2 : [], F2 = te2(y, h2);
      n.current.filtered.items.set(g2, F2), F2 > 0 && e2++;
    }
    for (let [g2, y] of c.current) for (let h2 of y) if (n.current.filtered.items.get(h2) > 0) {
      n.current.filtered.groups.add(g2);
      break;
    }
    n.current.filtered.count = e2;
  }
  function ne() {
    var a2, s2, i2;
    let e2 = M2();
    e2 && (((a2 = e2.parentElement) == null ? void 0 : a2.firstChild) === e2 && ((i2 = (s2 = e2.closest(N$1)) == null ? void 0 : s2.querySelector(be)) == null || i2.scrollIntoView({ block: "nearest" })), e2.scrollIntoView({ block: "nearest" }));
  }
  function M2() {
    var e2;
    return (e2 = I2.current) == null ? void 0 : e2.querySelector(`${le$1}[aria-selected="true"]`);
  }
  function V2() {
    var e2;
    return Array.from(((e2 = I2.current) == null ? void 0 : e2.querySelectorAll(ce$1)) || []);
  }
  function X2(e2) {
    let s2 = V2()[e2];
    s2 && E2.setState("value", s2.getAttribute(T));
  }
  function Q2(e2) {
    var g2;
    let a2 = M2(), s2 = V2(), i2 = s2.findIndex((y) => y === a2), l2 = s2[i2 + e2];
    (g2 = p2.current) != null && g2.loop && (l2 = i2 + e2 < 0 ? s2[s2.length - 1] : i2 + e2 === s2.length ? s2[0] : s2[i2 + e2]), l2 && E2.setState("value", l2.getAttribute(T));
  }
  function re2(e2) {
    let a2 = M2(), s2 = a2 == null ? void 0 : a2.closest(N$1), i2;
    for (; s2 && !i2; ) s2 = e2 > 0 ? we$1(s2, N$1) : De$1(s2, N$1), i2 = s2 == null ? void 0 : s2.querySelector(ce$1);
    i2 ? E2.setState("value", i2.getAttribute(T)) : Q2(e2);
  }
  let oe2 = () => X2(V2().length - 1), ie2 = (e2) => {
    e2.preventDefault(), e2.metaKey ? oe2() : e2.altKey ? re2(1) : Q2(1);
  }, se2 = (e2) => {
    e2.preventDefault(), e2.metaKey ? X2(0) : e2.altKey ? re2(-1) : Q2(-1);
  };
  return reactExports.createElement(Primitive$1.div, { ref: o2, tabIndex: -1, ...O2, "cmdk-root": "", onKeyDown: (e2) => {
    var s2;
    (s2 = O2.onKeyDown) == null || s2.call(O2, e2);
    let a2 = e2.nativeEvent.isComposing || e2.keyCode === 229;
    if (!(e2.defaultPrevented || a2)) switch (e2.key) {
      case "n":
      case "j": {
        j && e2.ctrlKey && ie2(e2);
        break;
      }
      case "ArrowDown": {
        ie2(e2);
        break;
      }
      case "p":
      case "k": {
        j && e2.ctrlKey && se2(e2);
        break;
      }
      case "ArrowUp": {
        se2(e2);
        break;
      }
      case "Home": {
        e2.preventDefault(), X2(0);
        break;
      }
      case "End": {
        e2.preventDefault(), oe2();
        break;
      }
      case "Enter": {
        e2.preventDefault();
        let i2 = M2();
        if (i2) {
          let l2 = new Event(Z$1);
          i2.dispatchEvent(l2);
        }
      }
    }
  } }, reactExports.createElement("label", { "cmdk-label": "", htmlFor: U2.inputId, id: U2.labelId, style: Te$1 }, b2), B$1(r2, (e2) => reactExports.createElement(de$1.Provider, { value: E2 }, reactExports.createElement(ue.Provider, { value: U2 }, e2))));
}), he = reactExports.forwardRef((r2, o2) => {
  var _2, I2;
  let n = useId(), u2 = reactExports.useRef(null), c = reactExports.useContext(fe$1), d = K$1(), f2 = pe$1(r2), p2 = (I2 = (_2 = f2.current) == null ? void 0 : _2.forceMount) != null ? I2 : c == null ? void 0 : c.forceMount;
  k$1(() => {
    if (!p2) return d.item(n, c == null ? void 0 : c.id);
  }, [p2]);
  let b2 = ve$1(n, u2, [r2.value, r2.children, u2], r2.keywords), m2 = ee$1(), R = P((v2) => v2.value && v2.value === b2.current), x2 = P((v2) => p2 || d.filter() === false ? true : v2.search ? v2.filtered.items.get(n) > 0 : true);
  reactExports.useEffect(() => {
    let v2 = u2.current;
    if (!(!v2 || r2.disabled)) return v2.addEventListener(Z$1, C), () => v2.removeEventListener(Z$1, C);
  }, [x2, r2.onSelect, r2.disabled]);
  function C() {
    var v2, E2;
    S2(), (E2 = (v2 = f2.current).onSelect) == null || E2.call(v2, b2.current);
  }
  function S2() {
    m2.setState("value", b2.current, true);
  }
  if (!x2) return null;
  let { disabled: A, value: ge2, onSelect: j, forceMount: O2, keywords: $2, ...q2 } = r2;
  return reactExports.createElement(Primitive$1.div, { ref: composeRefs(u2, o2), ...q2, id: n, "cmdk-item": "", role: "option", "aria-disabled": !!A, "aria-selected": !!R, "data-disabled": !!A, "data-selected": !!R, onPointerMove: A || d.getDisablePointerSelection() ? void 0 : S2, onClick: A ? void 0 : C }, r2.children);
}), Ee$1 = reactExports.forwardRef((r2, o2) => {
  let { heading: n, children: u2, forceMount: c, ...d } = r2, f2 = useId(), p2 = reactExports.useRef(null), b2 = reactExports.useRef(null), m2 = useId(), R = K$1(), x2 = P((S2) => c || R.filter() === false ? true : S2.search ? S2.filtered.groups.has(f2) : true);
  k$1(() => R.group(f2), []), ve$1(f2, p2, [r2.value, r2.heading, b2]);
  let C = reactExports.useMemo(() => ({ id: f2, forceMount: c }), [c]);
  return reactExports.createElement(Primitive$1.div, { ref: composeRefs(p2, o2), ...d, "cmdk-group": "", role: "presentation", hidden: x2 ? void 0 : true }, n && reactExports.createElement("div", { ref: b2, "cmdk-group-heading": "", "aria-hidden": true, id: m2 }, n), B$1(r2, (S2) => reactExports.createElement("div", { "cmdk-group-items": "", role: "group", "aria-labelledby": n ? m2 : void 0 }, reactExports.createElement(fe$1.Provider, { value: C }, S2))));
}), ye = reactExports.forwardRef((r2, o2) => {
  let { alwaysRender: n, ...u2 } = r2, c = reactExports.useRef(null), d = P((f2) => !f2.search);
  return !n && !d ? null : reactExports.createElement(Primitive$1.div, { ref: composeRefs(c, o2), ...u2, "cmdk-separator": "", role: "separator" });
}), Se$1 = reactExports.forwardRef((r2, o2) => {
  let { onValueChange: n, ...u2 } = r2, c = r2.value != null, d = ee$1(), f2 = P((m2) => m2.search), p2 = P((m2) => m2.selectedItemId), b2 = K$1();
  return reactExports.useEffect(() => {
    r2.value != null && d.setState("search", r2.value);
  }, [r2.value]), reactExports.createElement(Primitive$1.input, { ref: o2, ...u2, "cmdk-input": "", autoComplete: "off", autoCorrect: "off", spellCheck: false, "aria-autocomplete": "list", role: "combobox", "aria-expanded": true, "aria-controls": b2.listId, "aria-labelledby": b2.labelId, "aria-activedescendant": p2, id: b2.inputId, type: "text", value: c ? r2.value : f2, onChange: (m2) => {
    c || d.setState("search", m2.target.value), n == null || n(m2.target.value);
  } });
}), Ce$1 = reactExports.forwardRef((r2, o2) => {
  let { children: n, label: u2 = "Suggestions", ...c } = r2, d = reactExports.useRef(null), f2 = reactExports.useRef(null), p2 = P((m2) => m2.selectedItemId), b2 = K$1();
  return reactExports.useEffect(() => {
    if (f2.current && d.current) {
      let m2 = f2.current, R = d.current, x2, C = new ResizeObserver(() => {
        x2 = requestAnimationFrame(() => {
          let S2 = m2.offsetHeight;
          R.style.setProperty("--cmdk-list-height", S2.toFixed(1) + "px");
        });
      });
      return C.observe(m2), () => {
        cancelAnimationFrame(x2), C.unobserve(m2);
      };
    }
  }, []), reactExports.createElement(Primitive$1.div, { ref: composeRefs(d, o2), ...c, "cmdk-list": "", role: "listbox", tabIndex: -1, "aria-activedescendant": p2, "aria-label": u2, id: b2.listId }, B$1(r2, (m2) => reactExports.createElement("div", { ref: composeRefs(f2, b2.listInnerRef), "cmdk-list-sizer": "" }, m2)));
}), xe$1 = reactExports.forwardRef((r2, o2) => {
  let { open: n, onOpenChange: u2, overlayClassName: c, contentClassName: d, container: f2, ...p2 } = r2;
  return reactExports.createElement(Root$3, { open: n, onOpenChange: u2 }, reactExports.createElement(Portal$2, { container: f2 }, reactExports.createElement(Overlay, { "cmdk-overlay": "", className: c }), reactExports.createElement(Content$1, { "aria-label": r2.label, "cmdk-dialog": "", className: d }, reactExports.createElement(me, { ref: o2, ...p2 }))));
}), Ie$1 = reactExports.forwardRef((r2, o2) => P((u2) => u2.filtered.count === 0) ? reactExports.createElement(Primitive$1.div, { ref: o2, ...r2, "cmdk-empty": "", role: "presentation" }) : null), Pe = reactExports.forwardRef((r2, o2) => {
  let { progress: n, children: u2, label: c = "Loading...", ...d } = r2;
  return reactExports.createElement(Primitive$1.div, { ref: o2, ...d, "cmdk-loading": "", role: "progressbar", "aria-valuenow": n, "aria-valuemin": 0, "aria-valuemax": 100, "aria-label": c }, B$1(r2, (f2) => reactExports.createElement("div", { "aria-hidden": true }, f2)));
}), _e$1 = Object.assign(me, { List: Ce$1, Item: he, Input: Se$1, Group: Ee$1, Separator: ye, Dialog: xe$1, Empty: Ie$1, Loading: Pe });
function we$1(r2, o2) {
  let n = r2.nextElementSibling;
  for (; n; ) {
    if (n.matches(o2)) return n;
    n = n.nextElementSibling;
  }
}
function De$1(r2, o2) {
  let n = r2.previousElementSibling;
  for (; n; ) {
    if (n.matches(o2)) return n;
    n = n.previousElementSibling;
  }
}
function pe$1(r2) {
  let o2 = reactExports.useRef(r2);
  return k$1(() => {
    o2.current = r2;
  }), o2;
}
var k$1 = typeof window == "undefined" ? reactExports.useEffect : reactExports.useLayoutEffect;
function L$1(r2) {
  let o2 = reactExports.useRef();
  return o2.current === void 0 && (o2.current = r2()), o2;
}
function P(r2) {
  let o2 = ee$1(), n = () => r2(o2.snapshot());
  return reactExports.useSyncExternalStore(o2.subscribe, n, n);
}
function ve$1(r2, o2, n, u2 = []) {
  let c = reactExports.useRef(), d = K$1();
  return k$1(() => {
    var b2;
    let f2 = (() => {
      var m2;
      for (let R of n) {
        if (typeof R == "string") return R.trim();
        if (typeof R == "object" && "current" in R) return R.current ? (m2 = R.current.textContent) == null ? void 0 : m2.trim() : c.current;
      }
    })(), p2 = u2.map((m2) => m2.trim());
    d.value(r2, f2, p2), (b2 = o2.current) == null || b2.setAttribute(T, f2), c.current = f2;
  }), c;
}
var ke$1 = () => {
  let [r2, o2] = reactExports.useState(), n = L$1(() => /* @__PURE__ */ new Map());
  return k$1(() => {
    n.current.forEach((u2) => u2()), n.current = /* @__PURE__ */ new Map();
  }, [r2]), (u2, c) => {
    n.current.set(u2, c), o2({});
  };
};
function Me$1(r2) {
  let o2 = r2.type;
  return typeof o2 == "function" ? o2(r2.props) : "render" in o2 ? o2.render(r2.props) : r2;
}
function B$1({ asChild: r2, children: o2 }, n) {
  return r2 && reactExports.isValidElement(o2) ? reactExports.cloneElement(Me$1(o2), { ref: o2.ref }, n(o2.props.children)) : n(o2);
}
var Te$1 = { position: "absolute", width: "1px", height: "1px", padding: "0", margin: "-1px", overflow: "hidden", clip: "rect(0, 0, 0, 0)", whiteSpace: "nowrap", borderWidth: "0" };
const Dialog = Root$3;
const DialogPortal = Portal$2;
const DialogOverlay = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Overlay,
  {
    ref: ref2,
    className: cn$1(
      "fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
      className
    ),
    ...props
  }
));
DialogOverlay.displayName = Overlay.displayName;
const DialogContent = reactExports.forwardRef(({ className, children, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogPortal, { children: [
  /* @__PURE__ */ jsxRuntimeExports.jsx(DialogOverlay, {}),
  /* @__PURE__ */ jsxRuntimeExports.jsxs(
    Content$1,
    {
      ref: ref2,
      className: cn$1(
        "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
        className
      ),
      ...props,
      children: [
        children,
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Close, { className: "absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Cross2Icon, { className: "h-4 w-4" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "sr-only", children: "Close" })
        ] })
      ]
    }
  )
] }));
DialogContent.displayName = Content$1.displayName;
const DialogHeader = ({
  className,
  ...props
}) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  "div",
  {
    className: cn$1(
      "flex flex-col space-y-1.5 text-center sm:text-left",
      className
    ),
    ...props
  }
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({
  className,
  ...props
}) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  "div",
  {
    className: cn$1(
      "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
      className
    ),
    ...props
  }
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Title,
  {
    ref: ref2,
    className: cn$1(
      "text-lg font-semibold leading-none tracking-tight",
      className
    ),
    ...props
  }
));
DialogTitle.displayName = Title.displayName;
const DialogDescription = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Description,
  {
    ref: ref2,
    className: cn$1("text-sm text-muted-foreground", className),
    ...props
  }
));
DialogDescription.displayName = Description.displayName;
const Command = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  _e$1,
  {
    ref: ref2,
    className: cn$1(
      "flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
      className
    ),
    ...props
  }
));
Command.displayName = _e$1.displayName;
const CommandInput = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center border-b px-3", "cmdk-input-wrapper": "", children: [
  /* @__PURE__ */ jsxRuntimeExports.jsx(MagnifyingGlassIcon, { className: "mr-2 h-4 w-4 shrink-0 opacity-50" }),
  /* @__PURE__ */ jsxRuntimeExports.jsx(
    _e$1.Input,
    {
      ref: ref2,
      className: cn$1(
        "flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
        className
      ),
      ...props
    }
  )
] }));
CommandInput.displayName = _e$1.Input.displayName;
const CommandList = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  _e$1.List,
  {
    ref: ref2,
    className: cn$1("max-h-[300px] overflow-y-auto overflow-x-hidden", className),
    ...props
  }
));
CommandList.displayName = _e$1.List.displayName;
const CommandEmpty = reactExports.forwardRef((props, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  _e$1.Empty,
  {
    ref: ref2,
    className: "py-6 text-center text-sm",
    ...props
  }
));
CommandEmpty.displayName = _e$1.Empty.displayName;
const CommandGroup = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  _e$1.Group,
  {
    ref: ref2,
    className: cn$1(
      "overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
      className
    ),
    ...props
  }
));
CommandGroup.displayName = _e$1.Group.displayName;
const CommandSeparator = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  _e$1.Separator,
  {
    ref: ref2,
    className: cn$1("-mx-1 h-px bg-border", className),
    ...props
  }
));
CommandSeparator.displayName = _e$1.Separator.displayName;
const CommandItem = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  _e$1.Item,
  {
    ref: ref2,
    className: cn$1(
      "relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
      className
    ),
    ...props
  }
));
CommandItem.displayName = _e$1.Item.displayName;
const sides = ["top", "right", "bottom", "left"];
const min = Math.min;
const max = Math.max;
const round = Math.round;
const floor = Math.floor;
const createCoords = (v2) => ({
  x: v2,
  y: v2
});
const oppositeSideMap = {
  left: "right",
  right: "left",
  bottom: "top",
  top: "bottom"
};
function clamp$1(start, value, end) {
  return max(start, min(value, end));
}
function evaluate(value, param) {
  return typeof value === "function" ? value(param) : value;
}
function getSide(placement) {
  return placement.split("-")[0];
}
function getAlignment(placement) {
  return placement.split("-")[1];
}
function getOppositeAxis(axis) {
  return axis === "x" ? "y" : "x";
}
function getAxisLength(axis) {
  return axis === "y" ? "height" : "width";
}
function getSideAxis(placement) {
  const firstChar = placement[0];
  return firstChar === "t" || firstChar === "b" ? "y" : "x";
}
function getAlignmentAxis(placement) {
  return getOppositeAxis(getSideAxis(placement));
}
function getAlignmentSides(placement, rects, rtl) {
  if (rtl === void 0) {
    rtl = false;
  }
  const alignment = getAlignment(placement);
  const alignmentAxis = getAlignmentAxis(placement);
  const length = getAxisLength(alignmentAxis);
  let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top";
  if (rects.reference[length] > rects.floating[length]) {
    mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
  }
  return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
}
function getExpandedPlacements(placement) {
  const oppositePlacement = getOppositePlacement(placement);
  return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
}
function getOppositeAlignmentPlacement(placement) {
  return placement.includes("start") ? placement.replace("start", "end") : placement.replace("end", "start");
}
const lrPlacement = ["left", "right"];
const rlPlacement = ["right", "left"];
const tbPlacement = ["top", "bottom"];
const btPlacement = ["bottom", "top"];
function getSideList(side, isStart, rtl) {
  switch (side) {
    case "top":
    case "bottom":
      if (rtl) return isStart ? rlPlacement : lrPlacement;
      return isStart ? lrPlacement : rlPlacement;
    case "left":
    case "right":
      return isStart ? tbPlacement : btPlacement;
    default:
      return [];
  }
}
function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
  const alignment = getAlignment(placement);
  let list = getSideList(getSide(placement), direction === "start", rtl);
  if (alignment) {
    list = list.map((side) => side + "-" + alignment);
    if (flipAlignment) {
      list = list.concat(list.map(getOppositeAlignmentPlacement));
    }
  }
  return list;
}
function getOppositePlacement(placement) {
  const side = getSide(placement);
  return oppositeSideMap[side] + placement.slice(side.length);
}
function expandPaddingObject(padding) {
  return {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    ...padding
  };
}
function getPaddingObject(padding) {
  return typeof padding !== "number" ? expandPaddingObject(padding) : {
    top: padding,
    right: padding,
    bottom: padding,
    left: padding
  };
}
function rectToClientRect(rect) {
  const {
    x: x2,
    y,
    width,
    height
  } = rect;
  return {
    width,
    height,
    top: y,
    left: x2,
    right: x2 + width,
    bottom: y + height,
    x: x2,
    y
  };
}
function computeCoordsFromPlacement(_ref, placement, rtl) {
  let {
    reference,
    floating
  } = _ref;
  const sideAxis = getSideAxis(placement);
  const alignmentAxis = getAlignmentAxis(placement);
  const alignLength = getAxisLength(alignmentAxis);
  const side = getSide(placement);
  const isVertical = sideAxis === "y";
  const commonX = reference.x + reference.width / 2 - floating.width / 2;
  const commonY = reference.y + reference.height / 2 - floating.height / 2;
  const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
  let coords;
  switch (side) {
    case "top":
      coords = {
        x: commonX,
        y: reference.y - floating.height
      };
      break;
    case "bottom":
      coords = {
        x: commonX,
        y: reference.y + reference.height
      };
      break;
    case "right":
      coords = {
        x: reference.x + reference.width,
        y: commonY
      };
      break;
    case "left":
      coords = {
        x: reference.x - floating.width,
        y: commonY
      };
      break;
    default:
      coords = {
        x: reference.x,
        y: reference.y
      };
  }
  switch (getAlignment(placement)) {
    case "start":
      coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
      break;
    case "end":
      coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
      break;
  }
  return coords;
}
async function detectOverflow(state, options) {
  var _await$platform$isEle;
  if (options === void 0) {
    options = {};
  }
  const {
    x: x2,
    y,
    platform: platform2,
    rects,
    elements,
    strategy
  } = state;
  const {
    boundary = "clippingAncestors",
    rootBoundary = "viewport",
    elementContext = "floating",
    altBoundary = false,
    padding = 0
  } = evaluate(options, state);
  const paddingObject = getPaddingObject(padding);
  const altContext = elementContext === "floating" ? "reference" : "floating";
  const element = elements[altBoundary ? altContext : elementContext];
  const clippingClientRect = rectToClientRect(await platform2.getClippingRect({
    element: ((_await$platform$isEle = await (platform2.isElement == null ? void 0 : platform2.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || await (platform2.getDocumentElement == null ? void 0 : platform2.getDocumentElement(elements.floating)),
    boundary,
    rootBoundary,
    strategy
  }));
  const rect = elementContext === "floating" ? {
    x: x2,
    y,
    width: rects.floating.width,
    height: rects.floating.height
  } : rects.reference;
  const offsetParent = await (platform2.getOffsetParent == null ? void 0 : platform2.getOffsetParent(elements.floating));
  const offsetScale = await (platform2.isElement == null ? void 0 : platform2.isElement(offsetParent)) ? await (platform2.getScale == null ? void 0 : platform2.getScale(offsetParent)) || {
    x: 1,
    y: 1
  } : {
    x: 1,
    y: 1
  };
  const elementClientRect = rectToClientRect(platform2.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform2.convertOffsetParentRelativeRectToViewportRelativeRect({
    elements,
    rect,
    offsetParent,
    strategy
  }) : rect);
  return {
    top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
    bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
    left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
    right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
  };
}
const MAX_RESET_COUNT = 50;
const computePosition$1 = async (reference, floating, config2) => {
  const {
    placement = "bottom",
    strategy = "absolute",
    middleware = [],
    platform: platform2
  } = config2;
  const platformWithDetectOverflow = platform2.detectOverflow ? platform2 : {
    ...platform2,
    detectOverflow
  };
  const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(floating));
  let rects = await platform2.getElementRects({
    reference,
    floating,
    strategy
  });
  let {
    x: x2,
    y
  } = computeCoordsFromPlacement(rects, placement, rtl);
  let statefulPlacement = placement;
  let resetCount = 0;
  const middlewareData = {};
  for (let i2 = 0; i2 < middleware.length; i2++) {
    const currentMiddleware = middleware[i2];
    if (!currentMiddleware) {
      continue;
    }
    const {
      name: name2,
      fn: fn2
    } = currentMiddleware;
    const {
      x: nextX,
      y: nextY,
      data: data2,
      reset
    } = await fn2({
      x: x2,
      y,
      initialPlacement: placement,
      placement: statefulPlacement,
      strategy,
      middlewareData,
      rects,
      platform: platformWithDetectOverflow,
      elements: {
        reference,
        floating
      }
    });
    x2 = nextX != null ? nextX : x2;
    y = nextY != null ? nextY : y;
    middlewareData[name2] = {
      ...middlewareData[name2],
      ...data2
    };
    if (reset && resetCount < MAX_RESET_COUNT) {
      resetCount++;
      if (typeof reset === "object") {
        if (reset.placement) {
          statefulPlacement = reset.placement;
        }
        if (reset.rects) {
          rects = reset.rects === true ? await platform2.getElementRects({
            reference,
            floating,
            strategy
          }) : reset.rects;
        }
        ({
          x: x2,
          y
        } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
      }
      i2 = -1;
    }
  }
  return {
    x: x2,
    y,
    placement: statefulPlacement,
    strategy,
    middlewareData
  };
};
const arrow$3 = (options) => ({
  name: "arrow",
  options,
  async fn(state) {
    const {
      x: x2,
      y,
      placement,
      rects,
      platform: platform2,
      elements,
      middlewareData
    } = state;
    const {
      element,
      padding = 0
    } = evaluate(options, state) || {};
    if (element == null) {
      return {};
    }
    const paddingObject = getPaddingObject(padding);
    const coords = {
      x: x2,
      y
    };
    const axis = getAlignmentAxis(placement);
    const length = getAxisLength(axis);
    const arrowDimensions = await platform2.getDimensions(element);
    const isYAxis = axis === "y";
    const minProp = isYAxis ? "top" : "left";
    const maxProp = isYAxis ? "bottom" : "right";
    const clientProp = isYAxis ? "clientHeight" : "clientWidth";
    const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];
    const startDiff = coords[axis] - rects.reference[axis];
    const arrowOffsetParent = await (platform2.getOffsetParent == null ? void 0 : platform2.getOffsetParent(element));
    let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;
    if (!clientSize || !await (platform2.isElement == null ? void 0 : platform2.isElement(arrowOffsetParent))) {
      clientSize = elements.floating[clientProp] || rects.floating[length];
    }
    const centerToReference = endDiff / 2 - startDiff / 2;
    const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;
    const minPadding = min(paddingObject[minProp], largestPossiblePadding);
    const maxPadding = min(paddingObject[maxProp], largestPossiblePadding);
    const min$1 = minPadding;
    const max2 = clientSize - arrowDimensions[length] - maxPadding;
    const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;
    const offset2 = clamp$1(min$1, center, max2);
    const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset2 && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;
    const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max2 : 0;
    return {
      [axis]: coords[axis] + alignmentOffset,
      data: {
        [axis]: offset2,
        centerOffset: center - offset2 - alignmentOffset,
        ...shouldAddOffset && {
          alignmentOffset
        }
      },
      reset: shouldAddOffset
    };
  }
});
const flip$2 = function(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    name: "flip",
    options,
    async fn(state) {
      var _middlewareData$arrow, _middlewareData$flip;
      const {
        placement,
        middlewareData,
        rects,
        initialPlacement,
        platform: platform2,
        elements
      } = state;
      const {
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = true,
        fallbackPlacements: specifiedFallbackPlacements,
        fallbackStrategy = "bestFit",
        fallbackAxisSideDirection = "none",
        flipAlignment = true,
        ...detectOverflowOptions
      } = evaluate(options, state);
      if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
        return {};
      }
      const side = getSide(placement);
      const initialSideAxis = getSideAxis(initialPlacement);
      const isBasePlacement = getSide(initialPlacement) === initialPlacement;
      const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
      const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
      const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== "none";
      if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {
        fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
      }
      const placements = [initialPlacement, ...fallbackPlacements];
      const overflow = await platform2.detectOverflow(state, detectOverflowOptions);
      const overflows = [];
      let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
      if (checkMainAxis) {
        overflows.push(overflow[side]);
      }
      if (checkCrossAxis) {
        const sides2 = getAlignmentSides(placement, rects, rtl);
        overflows.push(overflow[sides2[0]], overflow[sides2[1]]);
      }
      overflowsData = [...overflowsData, {
        placement,
        overflows
      }];
      if (!overflows.every((side2) => side2 <= 0)) {
        var _middlewareData$flip2, _overflowsData$filter;
        const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
        const nextPlacement = placements[nextIndex];
        if (nextPlacement) {
          const ignoreCrossAxisOverflow = checkCrossAxis === "alignment" ? initialSideAxis !== getSideAxis(nextPlacement) : false;
          if (!ignoreCrossAxisOverflow || // We leave the current main axis only if every placement on that axis
          // overflows the main axis.
          overflowsData.every((d) => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) {
            return {
              data: {
                index: nextIndex,
                overflows: overflowsData
              },
              reset: {
                placement: nextPlacement
              }
            };
          }
        }
        let resetPlacement = (_overflowsData$filter = overflowsData.filter((d) => d.overflows[0] <= 0).sort((a2, b2) => a2.overflows[1] - b2.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
        if (!resetPlacement) {
          switch (fallbackStrategy) {
            case "bestFit": {
              var _overflowsData$filter2;
              const placement2 = (_overflowsData$filter2 = overflowsData.filter((d) => {
                if (hasFallbackAxisSideDirection) {
                  const currentSideAxis = getSideAxis(d.placement);
                  return currentSideAxis === initialSideAxis || // Create a bias to the `y` side axis due to horizontal
                  // reading directions favoring greater width.
                  currentSideAxis === "y";
                }
                return true;
              }).map((d) => [d.placement, d.overflows.filter((overflow2) => overflow2 > 0).reduce((acc, overflow2) => acc + overflow2, 0)]).sort((a2, b2) => a2[1] - b2[1])[0]) == null ? void 0 : _overflowsData$filter2[0];
              if (placement2) {
                resetPlacement = placement2;
              }
              break;
            }
            case "initialPlacement":
              resetPlacement = initialPlacement;
              break;
          }
        }
        if (placement !== resetPlacement) {
          return {
            reset: {
              placement: resetPlacement
            }
          };
        }
      }
      return {};
    }
  };
};
function getSideOffsets(overflow, rect) {
  return {
    top: overflow.top - rect.height,
    right: overflow.right - rect.width,
    bottom: overflow.bottom - rect.height,
    left: overflow.left - rect.width
  };
}
function isAnySideFullyClipped(overflow) {
  return sides.some((side) => overflow[side] >= 0);
}
const hide$2 = function(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    name: "hide",
    options,
    async fn(state) {
      const {
        rects,
        platform: platform2
      } = state;
      const {
        strategy = "referenceHidden",
        ...detectOverflowOptions
      } = evaluate(options, state);
      switch (strategy) {
        case "referenceHidden": {
          const overflow = await platform2.detectOverflow(state, {
            ...detectOverflowOptions,
            elementContext: "reference"
          });
          const offsets = getSideOffsets(overflow, rects.reference);
          return {
            data: {
              referenceHiddenOffsets: offsets,
              referenceHidden: isAnySideFullyClipped(offsets)
            }
          };
        }
        case "escaped": {
          const overflow = await platform2.detectOverflow(state, {
            ...detectOverflowOptions,
            altBoundary: true
          });
          const offsets = getSideOffsets(overflow, rects.floating);
          return {
            data: {
              escapedOffsets: offsets,
              escaped: isAnySideFullyClipped(offsets)
            }
          };
        }
        default: {
          return {};
        }
      }
    }
  };
};
const originSides = /* @__PURE__ */ new Set(["left", "top"]);
async function convertValueToCoords(state, options) {
  const {
    placement,
    platform: platform2,
    elements
  } = state;
  const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
  const side = getSide(placement);
  const alignment = getAlignment(placement);
  const isVertical = getSideAxis(placement) === "y";
  const mainAxisMulti = originSides.has(side) ? -1 : 1;
  const crossAxisMulti = rtl && isVertical ? -1 : 1;
  const rawValue = evaluate(options, state);
  let {
    mainAxis,
    crossAxis,
    alignmentAxis
  } = typeof rawValue === "number" ? {
    mainAxis: rawValue,
    crossAxis: 0,
    alignmentAxis: null
  } : {
    mainAxis: rawValue.mainAxis || 0,
    crossAxis: rawValue.crossAxis || 0,
    alignmentAxis: rawValue.alignmentAxis
  };
  if (alignment && typeof alignmentAxis === "number") {
    crossAxis = alignment === "end" ? alignmentAxis * -1 : alignmentAxis;
  }
  return isVertical ? {
    x: crossAxis * crossAxisMulti,
    y: mainAxis * mainAxisMulti
  } : {
    x: mainAxis * mainAxisMulti,
    y: crossAxis * crossAxisMulti
  };
}
const offset$2 = function(options) {
  if (options === void 0) {
    options = 0;
  }
  return {
    name: "offset",
    options,
    async fn(state) {
      var _middlewareData$offse, _middlewareData$arrow;
      const {
        x: x2,
        y,
        placement,
        middlewareData
      } = state;
      const diffCoords = await convertValueToCoords(state, options);
      if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
        return {};
      }
      return {
        x: x2 + diffCoords.x,
        y: y + diffCoords.y,
        data: {
          ...diffCoords,
          placement
        }
      };
    }
  };
};
const shift$2 = function(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    name: "shift",
    options,
    async fn(state) {
      const {
        x: x2,
        y,
        placement,
        platform: platform2
      } = state;
      const {
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = false,
        limiter = {
          fn: (_ref) => {
            let {
              x: x3,
              y: y2
            } = _ref;
            return {
              x: x3,
              y: y2
            };
          }
        },
        ...detectOverflowOptions
      } = evaluate(options, state);
      const coords = {
        x: x2,
        y
      };
      const overflow = await platform2.detectOverflow(state, detectOverflowOptions);
      const crossAxis = getSideAxis(getSide(placement));
      const mainAxis = getOppositeAxis(crossAxis);
      let mainAxisCoord = coords[mainAxis];
      let crossAxisCoord = coords[crossAxis];
      if (checkMainAxis) {
        const minSide = mainAxis === "y" ? "top" : "left";
        const maxSide = mainAxis === "y" ? "bottom" : "right";
        const min2 = mainAxisCoord + overflow[minSide];
        const max2 = mainAxisCoord - overflow[maxSide];
        mainAxisCoord = clamp$1(min2, mainAxisCoord, max2);
      }
      if (checkCrossAxis) {
        const minSide = crossAxis === "y" ? "top" : "left";
        const maxSide = crossAxis === "y" ? "bottom" : "right";
        const min2 = crossAxisCoord + overflow[minSide];
        const max2 = crossAxisCoord - overflow[maxSide];
        crossAxisCoord = clamp$1(min2, crossAxisCoord, max2);
      }
      const limitedCoords = limiter.fn({
        ...state,
        [mainAxis]: mainAxisCoord,
        [crossAxis]: crossAxisCoord
      });
      return {
        ...limitedCoords,
        data: {
          x: limitedCoords.x - x2,
          y: limitedCoords.y - y,
          enabled: {
            [mainAxis]: checkMainAxis,
            [crossAxis]: checkCrossAxis
          }
        }
      };
    }
  };
};
const limitShift$2 = function(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    options,
    fn(state) {
      const {
        x: x2,
        y,
        placement,
        rects,
        middlewareData
      } = state;
      const {
        offset: offset2 = 0,
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = true
      } = evaluate(options, state);
      const coords = {
        x: x2,
        y
      };
      const crossAxis = getSideAxis(placement);
      const mainAxis = getOppositeAxis(crossAxis);
      let mainAxisCoord = coords[mainAxis];
      let crossAxisCoord = coords[crossAxis];
      const rawOffset = evaluate(offset2, state);
      const computedOffset = typeof rawOffset === "number" ? {
        mainAxis: rawOffset,
        crossAxis: 0
      } : {
        mainAxis: 0,
        crossAxis: 0,
        ...rawOffset
      };
      if (checkMainAxis) {
        const len = mainAxis === "y" ? "height" : "width";
        const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;
        const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;
        if (mainAxisCoord < limitMin) {
          mainAxisCoord = limitMin;
        } else if (mainAxisCoord > limitMax) {
          mainAxisCoord = limitMax;
        }
      }
      if (checkCrossAxis) {
        var _middlewareData$offse, _middlewareData$offse2;
        const len = mainAxis === "y" ? "width" : "height";
        const isOriginSide = originSides.has(getSide(placement));
        const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);
        const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);
        if (crossAxisCoord < limitMin) {
          crossAxisCoord = limitMin;
        } else if (crossAxisCoord > limitMax) {
          crossAxisCoord = limitMax;
        }
      }
      return {
        [mainAxis]: mainAxisCoord,
        [crossAxis]: crossAxisCoord
      };
    }
  };
};
const size$2 = function(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    name: "size",
    options,
    async fn(state) {
      var _state$middlewareData, _state$middlewareData2;
      const {
        placement,
        rects,
        platform: platform2,
        elements
      } = state;
      const {
        apply = () => {
        },
        ...detectOverflowOptions
      } = evaluate(options, state);
      const overflow = await platform2.detectOverflow(state, detectOverflowOptions);
      const side = getSide(placement);
      const alignment = getAlignment(placement);
      const isYAxis = getSideAxis(placement) === "y";
      const {
        width,
        height
      } = rects.floating;
      let heightSide;
      let widthSide;
      if (side === "top" || side === "bottom") {
        heightSide = side;
        widthSide = alignment === (await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating)) ? "start" : "end") ? "left" : "right";
      } else {
        widthSide = side;
        heightSide = alignment === "end" ? "top" : "bottom";
      }
      const maximumClippingHeight = height - overflow.top - overflow.bottom;
      const maximumClippingWidth = width - overflow.left - overflow.right;
      const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight);
      const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth);
      const noShift = !state.middlewareData.shift;
      let availableHeight = overflowAvailableHeight;
      let availableWidth = overflowAvailableWidth;
      if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) {
        availableWidth = maximumClippingWidth;
      }
      if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) {
        availableHeight = maximumClippingHeight;
      }
      if (noShift && !alignment) {
        const xMin = max(overflow.left, 0);
        const xMax = max(overflow.right, 0);
        const yMin = max(overflow.top, 0);
        const yMax = max(overflow.bottom, 0);
        if (isYAxis) {
          availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));
        } else {
          availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));
        }
      }
      await apply({
        ...state,
        availableWidth,
        availableHeight
      });
      const nextDimensions = await platform2.getDimensions(elements.floating);
      if (width !== nextDimensions.width || height !== nextDimensions.height) {
        return {
          reset: {
            rects: true
          }
        };
      }
      return {};
    }
  };
};
function hasWindow() {
  return typeof window !== "undefined";
}
function getNodeName(node) {
  if (isNode(node)) {
    return (node.nodeName || "").toLowerCase();
  }
  return "#document";
}
function getWindow(node) {
  var _node$ownerDocument;
  return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
}
function getDocumentElement(node) {
  var _ref;
  return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
}
function isNode(value) {
  if (!hasWindow()) {
    return false;
  }
  return value instanceof Node || value instanceof getWindow(value).Node;
}
function isElement(value) {
  if (!hasWindow()) {
    return false;
  }
  return value instanceof Element || value instanceof getWindow(value).Element;
}
function isHTMLElement(value) {
  if (!hasWindow()) {
    return false;
  }
  return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
}
function isShadowRoot(value) {
  if (!hasWindow() || typeof ShadowRoot === "undefined") {
    return false;
  }
  return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
}
function isOverflowElement(element) {
  const {
    overflow,
    overflowX,
    overflowY,
    display
  } = getComputedStyle$1(element);
  return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && display !== "inline" && display !== "contents";
}
function isTableElement(element) {
  return /^(table|td|th)$/.test(getNodeName(element));
}
function isTopLayer(element) {
  try {
    if (element.matches(":popover-open")) {
      return true;
    }
  } catch (_e2) {
  }
  try {
    return element.matches(":modal");
  } catch (_e2) {
    return false;
  }
}
const willChangeRe = /transform|translate|scale|rotate|perspective|filter/;
const containRe = /paint|layout|strict|content/;
const isNotNone = (value) => !!value && value !== "none";
let isWebKitValue;
function isContainingBlock(elementOrCss) {
  const css = isElement(elementOrCss) ? getComputedStyle$1(elementOrCss) : elementOrCss;
  return isNotNone(css.transform) || isNotNone(css.translate) || isNotNone(css.scale) || isNotNone(css.rotate) || isNotNone(css.perspective) || !isWebKit() && (isNotNone(css.backdropFilter) || isNotNone(css.filter)) || willChangeRe.test(css.willChange || "") || containRe.test(css.contain || "");
}
function getContainingBlock(element) {
  let currentNode = getParentNode(element);
  while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
    if (isContainingBlock(currentNode)) {
      return currentNode;
    } else if (isTopLayer(currentNode)) {
      return null;
    }
    currentNode = getParentNode(currentNode);
  }
  return null;
}
function isWebKit() {
  if (isWebKitValue == null) {
    isWebKitValue = typeof CSS !== "undefined" && CSS.supports && CSS.supports("-webkit-backdrop-filter", "none");
  }
  return isWebKitValue;
}
function isLastTraversableNode(node) {
  return /^(html|body|#document)$/.test(getNodeName(node));
}
function getComputedStyle$1(element) {
  return getWindow(element).getComputedStyle(element);
}
function getNodeScroll(element) {
  if (isElement(element)) {
    return {
      scrollLeft: element.scrollLeft,
      scrollTop: element.scrollTop
    };
  }
  return {
    scrollLeft: element.scrollX,
    scrollTop: element.scrollY
  };
}
function getParentNode(node) {
  if (getNodeName(node) === "html") {
    return node;
  }
  const result = (
    // Step into the shadow DOM of the parent of a slotted node.
    node.assignedSlot || // DOM Element detected.
    node.parentNode || // ShadowRoot detected.
    isShadowRoot(node) && node.host || // Fallback.
    getDocumentElement(node)
  );
  return isShadowRoot(result) ? result.host : result;
}
function getNearestOverflowAncestor(node) {
  const parentNode = getParentNode(node);
  if (isLastTraversableNode(parentNode)) {
    return node.ownerDocument ? node.ownerDocument.body : node.body;
  }
  if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
    return parentNode;
  }
  return getNearestOverflowAncestor(parentNode);
}
function getOverflowAncestors(node, list, traverseIframes) {
  var _node$ownerDocument2;
  if (list === void 0) {
    list = [];
  }
  if (traverseIframes === void 0) {
    traverseIframes = true;
  }
  const scrollableAncestor = getNearestOverflowAncestor(node);
  const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
  const win = getWindow(scrollableAncestor);
  if (isBody) {
    const frameElement = getFrameElement(win);
    return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);
  } else {
    return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
  }
}
function getFrameElement(win) {
  return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;
}
function getCssDimensions(element) {
  const css = getComputedStyle$1(element);
  let width = parseFloat(css.width) || 0;
  let height = parseFloat(css.height) || 0;
  const hasOffset = isHTMLElement(element);
  const offsetWidth = hasOffset ? element.offsetWidth : width;
  const offsetHeight = hasOffset ? element.offsetHeight : height;
  const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
  if (shouldFallback) {
    width = offsetWidth;
    height = offsetHeight;
  }
  return {
    width,
    height,
    $: shouldFallback
  };
}
function unwrapElement(element) {
  return !isElement(element) ? element.contextElement : element;
}
function getScale(element) {
  const domElement = unwrapElement(element);
  if (!isHTMLElement(domElement)) {
    return createCoords(1);
  }
  const rect = domElement.getBoundingClientRect();
  const {
    width,
    height,
    $: $2
  } = getCssDimensions(domElement);
  let x2 = ($2 ? round(rect.width) : rect.width) / width;
  let y = ($2 ? round(rect.height) : rect.height) / height;
  if (!x2 || !Number.isFinite(x2)) {
    x2 = 1;
  }
  if (!y || !Number.isFinite(y)) {
    y = 1;
  }
  return {
    x: x2,
    y
  };
}
const noOffsets = /* @__PURE__ */ createCoords(0);
function getVisualOffsets(element) {
  const win = getWindow(element);
  if (!isWebKit() || !win.visualViewport) {
    return noOffsets;
  }
  return {
    x: win.visualViewport.offsetLeft,
    y: win.visualViewport.offsetTop
  };
}
function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {
  if (isFixed === void 0) {
    isFixed = false;
  }
  if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {
    return false;
  }
  return isFixed;
}
function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {
  if (includeScale === void 0) {
    includeScale = false;
  }
  if (isFixedStrategy === void 0) {
    isFixedStrategy = false;
  }
  const clientRect = element.getBoundingClientRect();
  const domElement = unwrapElement(element);
  let scale = createCoords(1);
  if (includeScale) {
    if (offsetParent) {
      if (isElement(offsetParent)) {
        scale = getScale(offsetParent);
      }
    } else {
      scale = getScale(element);
    }
  }
  const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
  let x2 = (clientRect.left + visualOffsets.x) / scale.x;
  let y = (clientRect.top + visualOffsets.y) / scale.y;
  let width = clientRect.width / scale.x;
  let height = clientRect.height / scale.y;
  if (domElement) {
    const win = getWindow(domElement);
    const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;
    let currentWin = win;
    let currentIFrame = getFrameElement(currentWin);
    while (currentIFrame && offsetParent && offsetWin !== currentWin) {
      const iframeScale = getScale(currentIFrame);
      const iframeRect = currentIFrame.getBoundingClientRect();
      const css = getComputedStyle$1(currentIFrame);
      const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
      const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
      x2 *= iframeScale.x;
      y *= iframeScale.y;
      width *= iframeScale.x;
      height *= iframeScale.y;
      x2 += left;
      y += top;
      currentWin = getWindow(currentIFrame);
      currentIFrame = getFrameElement(currentWin);
    }
  }
  return rectToClientRect({
    width,
    height,
    x: x2,
    y
  });
}
function getWindowScrollBarX(element, rect) {
  const leftScroll = getNodeScroll(element).scrollLeft;
  if (!rect) {
    return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;
  }
  return rect.left + leftScroll;
}
function getHTMLOffset(documentElement, scroll) {
  const htmlRect = documentElement.getBoundingClientRect();
  const x2 = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect);
  const y = htmlRect.top + scroll.scrollTop;
  return {
    x: x2,
    y
  };
}
function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
  let {
    elements,
    rect,
    offsetParent,
    strategy
  } = _ref;
  const isFixed = strategy === "fixed";
  const documentElement = getDocumentElement(offsetParent);
  const topLayer = elements ? isTopLayer(elements.floating) : false;
  if (offsetParent === documentElement || topLayer && isFixed) {
    return rect;
  }
  let scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  let scale = createCoords(1);
  const offsets = createCoords(0);
  const isOffsetParentAnElement = isHTMLElement(offsetParent);
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isOffsetParentAnElement) {
      const offsetRect = getBoundingClientRect(offsetParent);
      scale = getScale(offsetParent);
      offsets.x = offsetRect.x + offsetParent.clientLeft;
      offsets.y = offsetRect.y + offsetParent.clientTop;
    }
  }
  const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
  return {
    width: rect.width * scale.x,
    height: rect.height * scale.y,
    x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,
    y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y
  };
}
function getClientRects(element) {
  return Array.from(element.getClientRects());
}
function getDocumentRect(element) {
  const html = getDocumentElement(element);
  const scroll = getNodeScroll(element);
  const body = element.ownerDocument.body;
  const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
  const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
  let x2 = -scroll.scrollLeft + getWindowScrollBarX(element);
  const y = -scroll.scrollTop;
  if (getComputedStyle$1(body).direction === "rtl") {
    x2 += max(html.clientWidth, body.clientWidth) - width;
  }
  return {
    width,
    height,
    x: x2,
    y
  };
}
const SCROLLBAR_MAX = 25;
function getViewportRect(element, strategy) {
  const win = getWindow(element);
  const html = getDocumentElement(element);
  const visualViewport = win.visualViewport;
  let width = html.clientWidth;
  let height = html.clientHeight;
  let x2 = 0;
  let y = 0;
  if (visualViewport) {
    width = visualViewport.width;
    height = visualViewport.height;
    const visualViewportBased = isWebKit();
    if (!visualViewportBased || visualViewportBased && strategy === "fixed") {
      x2 = visualViewport.offsetLeft;
      y = visualViewport.offsetTop;
    }
  }
  const windowScrollbarX = getWindowScrollBarX(html);
  if (windowScrollbarX <= 0) {
    const doc = html.ownerDocument;
    const body = doc.body;
    const bodyStyles = getComputedStyle(body);
    const bodyMarginInline = doc.compatMode === "CSS1Compat" ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;
    const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline);
    if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) {
      width -= clippingStableScrollbarWidth;
    }
  } else if (windowScrollbarX <= SCROLLBAR_MAX) {
    width += windowScrollbarX;
  }
  return {
    width,
    height,
    x: x2,
    y
  };
}
function getInnerBoundingClientRect(element, strategy) {
  const clientRect = getBoundingClientRect(element, true, strategy === "fixed");
  const top = clientRect.top + element.clientTop;
  const left = clientRect.left + element.clientLeft;
  const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);
  const width = element.clientWidth * scale.x;
  const height = element.clientHeight * scale.y;
  const x2 = left * scale.x;
  const y = top * scale.y;
  return {
    width,
    height,
    x: x2,
    y
  };
}
function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {
  let rect;
  if (clippingAncestor === "viewport") {
    rect = getViewportRect(element, strategy);
  } else if (clippingAncestor === "document") {
    rect = getDocumentRect(getDocumentElement(element));
  } else if (isElement(clippingAncestor)) {
    rect = getInnerBoundingClientRect(clippingAncestor, strategy);
  } else {
    const visualOffsets = getVisualOffsets(element);
    rect = {
      x: clippingAncestor.x - visualOffsets.x,
      y: clippingAncestor.y - visualOffsets.y,
      width: clippingAncestor.width,
      height: clippingAncestor.height
    };
  }
  return rectToClientRect(rect);
}
function hasFixedPositionAncestor(element, stopNode) {
  const parentNode = getParentNode(element);
  if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {
    return false;
  }
  return getComputedStyle$1(parentNode).position === "fixed" || hasFixedPositionAncestor(parentNode, stopNode);
}
function getClippingElementAncestors(element, cache2) {
  const cachedResult = cache2.get(element);
  if (cachedResult) {
    return cachedResult;
  }
  let result = getOverflowAncestors(element, [], false).filter((el2) => isElement(el2) && getNodeName(el2) !== "body");
  let currentContainingBlockComputedStyle = null;
  const elementIsFixed = getComputedStyle$1(element).position === "fixed";
  let currentNode = elementIsFixed ? getParentNode(element) : element;
  while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
    const computedStyle = getComputedStyle$1(currentNode);
    const currentNodeIsContaining = isContainingBlock(currentNode);
    if (!currentNodeIsContaining && computedStyle.position === "fixed") {
      currentContainingBlockComputedStyle = null;
    }
    const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === "static" && !!currentContainingBlockComputedStyle && (currentContainingBlockComputedStyle.position === "absolute" || currentContainingBlockComputedStyle.position === "fixed") || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);
    if (shouldDropCurrentNode) {
      result = result.filter((ancestor) => ancestor !== currentNode);
    } else {
      currentContainingBlockComputedStyle = computedStyle;
    }
    currentNode = getParentNode(currentNode);
  }
  cache2.set(element, result);
  return result;
}
function getClippingRect(_ref) {
  let {
    element,
    boundary,
    rootBoundary,
    strategy
  } = _ref;
  const elementClippingAncestors = boundary === "clippingAncestors" ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);
  const clippingAncestors = [...elementClippingAncestors, rootBoundary];
  const firstRect = getClientRectFromClippingAncestor(element, clippingAncestors[0], strategy);
  let top = firstRect.top;
  let right = firstRect.right;
  let bottom = firstRect.bottom;
  let left = firstRect.left;
  for (let i2 = 1; i2 < clippingAncestors.length; i2++) {
    const rect = getClientRectFromClippingAncestor(element, clippingAncestors[i2], strategy);
    top = max(rect.top, top);
    right = min(rect.right, right);
    bottom = min(rect.bottom, bottom);
    left = max(rect.left, left);
  }
  return {
    width: right - left,
    height: bottom - top,
    x: left,
    y: top
  };
}
function getDimensions(element) {
  const {
    width,
    height
  } = getCssDimensions(element);
  return {
    width,
    height
  };
}
function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
  const isOffsetParentAnElement = isHTMLElement(offsetParent);
  const documentElement = getDocumentElement(offsetParent);
  const isFixed = strategy === "fixed";
  const rect = getBoundingClientRect(element, true, isFixed, offsetParent);
  let scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  const offsets = createCoords(0);
  function setLeftRTLScrollbarOffset() {
    offsets.x = getWindowScrollBarX(documentElement);
  }
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isOffsetParentAnElement) {
      const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
      offsets.x = offsetRect.x + offsetParent.clientLeft;
      offsets.y = offsetRect.y + offsetParent.clientTop;
    } else if (documentElement) {
      setLeftRTLScrollbarOffset();
    }
  }
  if (isFixed && !isOffsetParentAnElement && documentElement) {
    setLeftRTLScrollbarOffset();
  }
  const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
  const x2 = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;
  const y = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;
  return {
    x: x2,
    y,
    width: rect.width,
    height: rect.height
  };
}
function isStaticPositioned(element) {
  return getComputedStyle$1(element).position === "static";
}
function getTrueOffsetParent(element, polyfill2) {
  if (!isHTMLElement(element) || getComputedStyle$1(element).position === "fixed") {
    return null;
  }
  if (polyfill2) {
    return polyfill2(element);
  }
  let rawOffsetParent = element.offsetParent;
  if (getDocumentElement(element) === rawOffsetParent) {
    rawOffsetParent = rawOffsetParent.ownerDocument.body;
  }
  return rawOffsetParent;
}
function getOffsetParent(element, polyfill2) {
  const win = getWindow(element);
  if (isTopLayer(element)) {
    return win;
  }
  if (!isHTMLElement(element)) {
    let svgOffsetParent = getParentNode(element);
    while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {
      if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {
        return svgOffsetParent;
      }
      svgOffsetParent = getParentNode(svgOffsetParent);
    }
    return win;
  }
  let offsetParent = getTrueOffsetParent(element, polyfill2);
  while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {
    offsetParent = getTrueOffsetParent(offsetParent, polyfill2);
  }
  if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {
    return win;
  }
  return offsetParent || getContainingBlock(element) || win;
}
const getElementRects = async function(data2) {
  const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
  const getDimensionsFn = this.getDimensions;
  const floatingDimensions = await getDimensionsFn(data2.floating);
  return {
    reference: getRectRelativeToOffsetParent(data2.reference, await getOffsetParentFn(data2.floating), data2.strategy),
    floating: {
      x: 0,
      y: 0,
      width: floatingDimensions.width,
      height: floatingDimensions.height
    }
  };
};
function isRTL(element) {
  return getComputedStyle$1(element).direction === "rtl";
}
const platform = {
  convertOffsetParentRelativeRectToViewportRelativeRect,
  getDocumentElement,
  getClippingRect,
  getOffsetParent,
  getElementRects,
  getClientRects,
  getDimensions,
  getScale,
  isElement,
  isRTL
};
function rectsAreEqual(a2, b2) {
  return a2.x === b2.x && a2.y === b2.y && a2.width === b2.width && a2.height === b2.height;
}
function observeMove(element, onMove) {
  let io2 = null;
  let timeoutId;
  const root = getDocumentElement(element);
  function cleanup() {
    var _io;
    clearTimeout(timeoutId);
    (_io = io2) == null || _io.disconnect();
    io2 = null;
  }
  function refresh(skip, threshold) {
    if (skip === void 0) {
      skip = false;
    }
    if (threshold === void 0) {
      threshold = 1;
    }
    cleanup();
    const elementRectForRootMargin = element.getBoundingClientRect();
    const {
      left,
      top,
      width,
      height
    } = elementRectForRootMargin;
    if (!skip) {
      onMove();
    }
    if (!width || !height) {
      return;
    }
    const insetTop = floor(top);
    const insetRight = floor(root.clientWidth - (left + width));
    const insetBottom = floor(root.clientHeight - (top + height));
    const insetLeft = floor(left);
    const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px";
    const options = {
      rootMargin,
      threshold: max(0, min(1, threshold)) || 1
    };
    let isFirstUpdate = true;
    function handleObserve(entries) {
      const ratio = entries[0].intersectionRatio;
      if (ratio !== threshold) {
        if (!isFirstUpdate) {
          return refresh();
        }
        if (!ratio) {
          timeoutId = setTimeout(() => {
            refresh(false, 1e-7);
          }, 1e3);
        } else {
          refresh(false, ratio);
        }
      }
      if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) {
        refresh();
      }
      isFirstUpdate = false;
    }
    try {
      io2 = new IntersectionObserver(handleObserve, {
        ...options,
        // Handle <iframe>s
        root: root.ownerDocument
      });
    } catch (_e2) {
      io2 = new IntersectionObserver(handleObserve, options);
    }
    io2.observe(element);
  }
  refresh(true);
  return cleanup;
}
function autoUpdate(reference, floating, update, options) {
  if (options === void 0) {
    options = {};
  }
  const {
    ancestorScroll = true,
    ancestorResize = true,
    elementResize = typeof ResizeObserver === "function",
    layoutShift = typeof IntersectionObserver === "function",
    animationFrame = false
  } = options;
  const referenceEl = unwrapElement(reference);
  const ancestors = ancestorScroll || ancestorResize ? [...referenceEl ? getOverflowAncestors(referenceEl) : [], ...floating ? getOverflowAncestors(floating) : []] : [];
  ancestors.forEach((ancestor) => {
    ancestorScroll && ancestor.addEventListener("scroll", update, {
      passive: true
    });
    ancestorResize && ancestor.addEventListener("resize", update);
  });
  const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;
  let reobserveFrame = -1;
  let resizeObserver = null;
  if (elementResize) {
    resizeObserver = new ResizeObserver((_ref) => {
      let [firstEntry] = _ref;
      if (firstEntry && firstEntry.target === referenceEl && resizeObserver && floating) {
        resizeObserver.unobserve(floating);
        cancelAnimationFrame(reobserveFrame);
        reobserveFrame = requestAnimationFrame(() => {
          var _resizeObserver;
          (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);
        });
      }
      update();
    });
    if (referenceEl && !animationFrame) {
      resizeObserver.observe(referenceEl);
    }
    if (floating) {
      resizeObserver.observe(floating);
    }
  }
  let frameId;
  let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
  if (animationFrame) {
    frameLoop();
  }
  function frameLoop() {
    const nextRefRect = getBoundingClientRect(reference);
    if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) {
      update();
    }
    prevRefRect = nextRefRect;
    frameId = requestAnimationFrame(frameLoop);
  }
  update();
  return () => {
    var _resizeObserver2;
    ancestors.forEach((ancestor) => {
      ancestorScroll && ancestor.removeEventListener("scroll", update);
      ancestorResize && ancestor.removeEventListener("resize", update);
    });
    cleanupIo == null || cleanupIo();
    (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();
    resizeObserver = null;
    if (animationFrame) {
      cancelAnimationFrame(frameId);
    }
  };
}
const offset$1 = offset$2;
const shift$1 = shift$2;
const flip$1 = flip$2;
const size$1 = size$2;
const hide$1 = hide$2;
const arrow$2 = arrow$3;
const limitShift$1 = limitShift$2;
const computePosition = (reference, floating, options) => {
  const cache2 = /* @__PURE__ */ new Map();
  const mergedOptions = {
    platform,
    ...options
  };
  const platformWithCache = {
    ...mergedOptions.platform,
    _c: cache2
  };
  return computePosition$1(reference, floating, {
    ...mergedOptions,
    platform: platformWithCache
  });
};
var isClient = typeof document !== "undefined";
var noop = function noop2() {
};
var index = isClient ? reactExports.useLayoutEffect : noop;
function deepEqual(a2, b2) {
  if (a2 === b2) {
    return true;
  }
  if (typeof a2 !== typeof b2) {
    return false;
  }
  if (typeof a2 === "function" && a2.toString() === b2.toString()) {
    return true;
  }
  let length;
  let i2;
  let keys;
  if (a2 && b2 && typeof a2 === "object") {
    if (Array.isArray(a2)) {
      length = a2.length;
      if (length !== b2.length) return false;
      for (i2 = length; i2-- !== 0; ) {
        if (!deepEqual(a2[i2], b2[i2])) {
          return false;
        }
      }
      return true;
    }
    keys = Object.keys(a2);
    length = keys.length;
    if (length !== Object.keys(b2).length) {
      return false;
    }
    for (i2 = length; i2-- !== 0; ) {
      if (!{}.hasOwnProperty.call(b2, keys[i2])) {
        return false;
      }
    }
    for (i2 = length; i2-- !== 0; ) {
      const key = keys[i2];
      if (key === "_owner" && a2.$$typeof) {
        continue;
      }
      if (!deepEqual(a2[key], b2[key])) {
        return false;
      }
    }
    return true;
  }
  return a2 !== a2 && b2 !== b2;
}
function getDPR(element) {
  if (typeof window === "undefined") {
    return 1;
  }
  const win = element.ownerDocument.defaultView || window;
  return win.devicePixelRatio || 1;
}
function roundByDPR(element, value) {
  const dpr = getDPR(element);
  return Math.round(value * dpr) / dpr;
}
function useLatestRef(value) {
  const ref2 = reactExports.useRef(value);
  index(() => {
    ref2.current = value;
  });
  return ref2;
}
function useFloating(options) {
  if (options === void 0) {
    options = {};
  }
  const {
    placement = "bottom",
    strategy = "absolute",
    middleware = [],
    platform: platform2,
    elements: {
      reference: externalReference,
      floating: externalFloating
    } = {},
    transform: transform2 = true,
    whileElementsMounted,
    open
  } = options;
  const [data2, setData] = reactExports.useState({
    x: 0,
    y: 0,
    strategy,
    placement,
    middlewareData: {},
    isPositioned: false
  });
  const [latestMiddleware, setLatestMiddleware] = reactExports.useState(middleware);
  if (!deepEqual(latestMiddleware, middleware)) {
    setLatestMiddleware(middleware);
  }
  const [_reference, _setReference] = reactExports.useState(null);
  const [_floating, _setFloating] = reactExports.useState(null);
  const setReference = reactExports.useCallback((node) => {
    if (node !== referenceRef.current) {
      referenceRef.current = node;
      _setReference(node);
    }
  }, []);
  const setFloating = reactExports.useCallback((node) => {
    if (node !== floatingRef.current) {
      floatingRef.current = node;
      _setFloating(node);
    }
  }, []);
  const referenceEl = externalReference || _reference;
  const floatingEl = externalFloating || _floating;
  const referenceRef = reactExports.useRef(null);
  const floatingRef = reactExports.useRef(null);
  const dataRef = reactExports.useRef(data2);
  const hasWhileElementsMounted = whileElementsMounted != null;
  const whileElementsMountedRef = useLatestRef(whileElementsMounted);
  const platformRef = useLatestRef(platform2);
  const openRef = useLatestRef(open);
  const update = reactExports.useCallback(() => {
    if (!referenceRef.current || !floatingRef.current) {
      return;
    }
    const config2 = {
      placement,
      strategy,
      middleware: latestMiddleware
    };
    if (platformRef.current) {
      config2.platform = platformRef.current;
    }
    computePosition(referenceRef.current, floatingRef.current, config2).then((data3) => {
      const fullData = {
        ...data3,
        // The floating element's position may be recomputed while it's closed
        // but still mounted (such as when transitioning out). To ensure
        // `isPositioned` will be `false` initially on the next open, avoid
        // setting it to `true` when `open === false` (must be specified).
        isPositioned: openRef.current !== false
      };
      if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {
        dataRef.current = fullData;
        reactDomExports.flushSync(() => {
          setData(fullData);
        });
      }
    });
  }, [latestMiddleware, placement, strategy, platformRef, openRef]);
  index(() => {
    if (open === false && dataRef.current.isPositioned) {
      dataRef.current.isPositioned = false;
      setData((data3) => ({
        ...data3,
        isPositioned: false
      }));
    }
  }, [open]);
  const isMountedRef = reactExports.useRef(false);
  index(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);
  index(() => {
    if (referenceEl) referenceRef.current = referenceEl;
    if (floatingEl) floatingRef.current = floatingEl;
    if (referenceEl && floatingEl) {
      if (whileElementsMountedRef.current) {
        return whileElementsMountedRef.current(referenceEl, floatingEl, update);
      }
      update();
    }
  }, [referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted]);
  const refs = reactExports.useMemo(() => ({
    reference: referenceRef,
    floating: floatingRef,
    setReference,
    setFloating
  }), [setReference, setFloating]);
  const elements = reactExports.useMemo(() => ({
    reference: referenceEl,
    floating: floatingEl
  }), [referenceEl, floatingEl]);
  const floatingStyles = reactExports.useMemo(() => {
    const initialStyles = {
      position: strategy,
      left: 0,
      top: 0
    };
    if (!elements.floating) {
      return initialStyles;
    }
    const x2 = roundByDPR(elements.floating, data2.x);
    const y = roundByDPR(elements.floating, data2.y);
    if (transform2) {
      return {
        ...initialStyles,
        transform: "translate(" + x2 + "px, " + y + "px)",
        ...getDPR(elements.floating) >= 1.5 && {
          willChange: "transform"
        }
      };
    }
    return {
      position: strategy,
      left: x2,
      top: y
    };
  }, [strategy, transform2, elements.floating, data2.x, data2.y]);
  return reactExports.useMemo(() => ({
    ...data2,
    update,
    refs,
    elements,
    floatingStyles
  }), [data2, update, refs, elements, floatingStyles]);
}
const arrow$1 = (options) => {
  function isRef(value) {
    return {}.hasOwnProperty.call(value, "current");
  }
  return {
    name: "arrow",
    options,
    fn(state) {
      const {
        element,
        padding
      } = typeof options === "function" ? options(state) : options;
      if (element && isRef(element)) {
        if (element.current != null) {
          return arrow$2({
            element: element.current,
            padding
          }).fn(state);
        }
        return {};
      }
      if (element) {
        return arrow$2({
          element,
          padding
        }).fn(state);
      }
      return {};
    }
  };
};
const offset = (options, deps) => {
  const result = offset$1(options);
  return {
    name: result.name,
    fn: result.fn,
    options: [options, deps]
  };
};
const shift = (options, deps) => {
  const result = shift$1(options);
  return {
    name: result.name,
    fn: result.fn,
    options: [options, deps]
  };
};
const limitShift = (options, deps) => {
  const result = limitShift$1(options);
  return {
    fn: result.fn,
    options: [options, deps]
  };
};
const flip = (options, deps) => {
  const result = flip$1(options);
  return {
    name: result.name,
    fn: result.fn,
    options: [options, deps]
  };
};
const size = (options, deps) => {
  const result = size$1(options);
  return {
    name: result.name,
    fn: result.fn,
    options: [options, deps]
  };
};
const hide = (options, deps) => {
  const result = hide$1(options);
  return {
    name: result.name,
    fn: result.fn,
    options: [options, deps]
  };
};
const arrow = (options, deps) => {
  const result = arrow$1(options);
  return {
    name: result.name,
    fn: result.fn,
    options: [options, deps]
  };
};
var NAME$1 = "Arrow";
var Arrow$1 = reactExports.forwardRef((props, forwardedRef) => {
  const { children, width = 10, height = 5, ...arrowProps } = props;
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    Primitive$1.svg,
    {
      ...arrowProps,
      ref: forwardedRef,
      width,
      height,
      viewBox: "0 0 30 10",
      preserveAspectRatio: "none",
      children: props.asChild ? children : /* @__PURE__ */ jsxRuntimeExports.jsx("polygon", { points: "0,0 30,0 15,10" })
    }
  );
});
Arrow$1.displayName = NAME$1;
var Root$2 = Arrow$1;
function useSize(element) {
  const [size2, setSize] = reactExports.useState(void 0);
  useLayoutEffect2(() => {
    if (element) {
      setSize({ width: element.offsetWidth, height: element.offsetHeight });
      const resizeObserver = new ResizeObserver((entries) => {
        if (!Array.isArray(entries)) {
          return;
        }
        if (!entries.length) {
          return;
        }
        const entry = entries[0];
        let width;
        let height;
        if ("borderBoxSize" in entry) {
          const borderSizeEntry = entry["borderBoxSize"];
          const borderSize = Array.isArray(borderSizeEntry) ? borderSizeEntry[0] : borderSizeEntry;
          width = borderSize["inlineSize"];
          height = borderSize["blockSize"];
        } else {
          width = element.offsetWidth;
          height = element.offsetHeight;
        }
        setSize({ width, height });
      });
      resizeObserver.observe(element, { box: "border-box" });
      return () => resizeObserver.unobserve(element);
    } else {
      setSize(void 0);
    }
  }, [element]);
  return size2;
}
var POPPER_NAME = "Popper";
var [createPopperContext, createPopperScope] = createContextScope(POPPER_NAME);
var [PopperProvider, usePopperContext] = createPopperContext(POPPER_NAME);
var Popper = (props) => {
  const { __scopePopper, children } = props;
  const [anchor, setAnchor] = reactExports.useState(null);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(PopperProvider, { scope: __scopePopper, anchor, onAnchorChange: setAnchor, children });
};
Popper.displayName = POPPER_NAME;
var ANCHOR_NAME$1 = "PopperAnchor";
var PopperAnchor = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopper, virtualRef, ...anchorProps } = props;
    const context = usePopperContext(ANCHOR_NAME$1, __scopePopper);
    const ref2 = reactExports.useRef(null);
    const composedRefs = useComposedRefs(forwardedRef, ref2);
    const anchorRef = reactExports.useRef(null);
    reactExports.useEffect(() => {
      const previousAnchor = anchorRef.current;
      anchorRef.current = virtualRef?.current || ref2.current;
      if (previousAnchor !== anchorRef.current) {
        context.onAnchorChange(anchorRef.current);
      }
    });
    return virtualRef ? null : /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.div, { ...anchorProps, ref: composedRefs });
  }
);
PopperAnchor.displayName = ANCHOR_NAME$1;
var CONTENT_NAME$3 = "PopperContent";
var [PopperContentProvider, useContentContext] = createPopperContext(CONTENT_NAME$3);
var PopperContent = reactExports.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopePopper,
      side = "bottom",
      sideOffset = 0,
      align = "center",
      alignOffset = 0,
      arrowPadding = 0,
      avoidCollisions = true,
      collisionBoundary = [],
      collisionPadding: collisionPaddingProp = 0,
      sticky = "partial",
      hideWhenDetached = false,
      updatePositionStrategy = "optimized",
      onPlaced,
      ...contentProps
    } = props;
    const context = usePopperContext(CONTENT_NAME$3, __scopePopper);
    const [content, setContent] = reactExports.useState(null);
    const composedRefs = useComposedRefs(forwardedRef, (node) => setContent(node));
    const [arrow$12, setArrow] = reactExports.useState(null);
    const arrowSize = useSize(arrow$12);
    const arrowWidth = arrowSize?.width ?? 0;
    const arrowHeight = arrowSize?.height ?? 0;
    const desiredPlacement = side + (align !== "center" ? "-" + align : "");
    const collisionPadding = typeof collisionPaddingProp === "number" ? collisionPaddingProp : { top: 0, right: 0, bottom: 0, left: 0, ...collisionPaddingProp };
    const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [collisionBoundary];
    const hasExplicitBoundaries = boundary.length > 0;
    const detectOverflowOptions = {
      padding: collisionPadding,
      boundary: boundary.filter(isNotNull),
      // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries
      altBoundary: hasExplicitBoundaries
    };
    const { refs, floatingStyles, placement, isPositioned, middlewareData } = useFloating({
      // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues
      strategy: "fixed",
      placement: desiredPlacement,
      whileElementsMounted: (...args) => {
        const cleanup = autoUpdate(...args, {
          animationFrame: updatePositionStrategy === "always"
        });
        return cleanup;
      },
      elements: {
        reference: context.anchor
      },
      middleware: [
        offset({ mainAxis: sideOffset + arrowHeight, alignmentAxis: alignOffset }),
        avoidCollisions && shift({
          mainAxis: true,
          crossAxis: false,
          limiter: sticky === "partial" ? limitShift() : void 0,
          ...detectOverflowOptions
        }),
        avoidCollisions && flip({ ...detectOverflowOptions }),
        size({
          ...detectOverflowOptions,
          apply: ({ elements, rects, availableWidth, availableHeight }) => {
            const { width: anchorWidth, height: anchorHeight } = rects.reference;
            const contentStyle = elements.floating.style;
            contentStyle.setProperty("--radix-popper-available-width", `${availableWidth}px`);
            contentStyle.setProperty("--radix-popper-available-height", `${availableHeight}px`);
            contentStyle.setProperty("--radix-popper-anchor-width", `${anchorWidth}px`);
            contentStyle.setProperty("--radix-popper-anchor-height", `${anchorHeight}px`);
          }
        }),
        arrow$12 && arrow({ element: arrow$12, padding: arrowPadding }),
        transformOrigin({ arrowWidth, arrowHeight }),
        hideWhenDetached && hide({ strategy: "referenceHidden", ...detectOverflowOptions })
      ]
    });
    const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement);
    const handlePlaced = useCallbackRef$1(onPlaced);
    useLayoutEffect2(() => {
      if (isPositioned) {
        handlePlaced?.();
      }
    }, [isPositioned, handlePlaced]);
    const arrowX = middlewareData.arrow?.x;
    const arrowY = middlewareData.arrow?.y;
    const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;
    const [contentZIndex, setContentZIndex] = reactExports.useState();
    useLayoutEffect2(() => {
      if (content) setContentZIndex(window.getComputedStyle(content).zIndex);
    }, [content]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        ref: refs.setFloating,
        "data-radix-popper-content-wrapper": "",
        style: {
          ...floatingStyles,
          transform: isPositioned ? floatingStyles.transform : "translate(0, -200%)",
          // keep off the page when measuring
          minWidth: "max-content",
          zIndex: contentZIndex,
          ["--radix-popper-transform-origin"]: [
            middlewareData.transformOrigin?.x,
            middlewareData.transformOrigin?.y
          ].join(" "),
          // hide the content if using the hide middleware and should be hidden
          // set visibility to hidden and disable pointer events so the UI behaves
          // as if the PopperContent isn't there at all
          ...middlewareData.hide?.referenceHidden && {
            visibility: "hidden",
            pointerEvents: "none"
          }
        },
        dir: props.dir,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          PopperContentProvider,
          {
            scope: __scopePopper,
            placedSide,
            onArrowChange: setArrow,
            arrowX,
            arrowY,
            shouldHideArrow: cannotCenterArrow,
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              Primitive$1.div,
              {
                "data-side": placedSide,
                "data-align": placedAlign,
                ...contentProps,
                ref: composedRefs,
                style: {
                  ...contentProps.style,
                  // if the PopperContent hasn't been placed yet (not all measurements done)
                  // we prevent animations so that users's animation don't kick in too early referring wrong sides
                  animation: !isPositioned ? "none" : void 0
                }
              }
            )
          }
        )
      }
    );
  }
);
PopperContent.displayName = CONTENT_NAME$3;
var ARROW_NAME$3 = "PopperArrow";
var OPPOSITE_SIDE = {
  top: "bottom",
  right: "left",
  bottom: "top",
  left: "right"
};
var PopperArrow = reactExports.forwardRef(function PopperArrow2(props, forwardedRef) {
  const { __scopePopper, ...arrowProps } = props;
  const contentContext = useContentContext(ARROW_NAME$3, __scopePopper);
  const baseSide = OPPOSITE_SIDE[contentContext.placedSide];
  return (
    // we have to use an extra wrapper because `ResizeObserver` (used by `useSize`)
    // doesn't report size as we'd expect on SVG elements.
    // it reports their bounding box which is effectively the largest path inside the SVG.
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        ref: contentContext.onArrowChange,
        style: {
          position: "absolute",
          left: contentContext.arrowX,
          top: contentContext.arrowY,
          [baseSide]: 0,
          transformOrigin: {
            top: "",
            right: "0 0",
            bottom: "center 0",
            left: "100% 0"
          }[contentContext.placedSide],
          transform: {
            top: "translateY(100%)",
            right: "translateY(50%) rotate(90deg) translateX(-50%)",
            bottom: `rotate(180deg)`,
            left: "translateY(50%) rotate(-90deg) translateX(50%)"
          }[contentContext.placedSide],
          visibility: contentContext.shouldHideArrow ? "hidden" : void 0
        },
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Root$2,
          {
            ...arrowProps,
            ref: forwardedRef,
            style: {
              ...arrowProps.style,
              // ensures the element can be measured correctly (mostly for if SVG)
              display: "block"
            }
          }
        )
      }
    )
  );
});
PopperArrow.displayName = ARROW_NAME$3;
function isNotNull(value) {
  return value !== null;
}
var transformOrigin = (options) => ({
  name: "transformOrigin",
  options,
  fn(data2) {
    const { placement, rects, middlewareData } = data2;
    const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;
    const isArrowHidden = cannotCenterArrow;
    const arrowWidth = isArrowHidden ? 0 : options.arrowWidth;
    const arrowHeight = isArrowHidden ? 0 : options.arrowHeight;
    const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement);
    const noArrowAlign = { start: "0%", center: "50%", end: "100%" }[placedAlign];
    const arrowXCenter = (middlewareData.arrow?.x ?? 0) + arrowWidth / 2;
    const arrowYCenter = (middlewareData.arrow?.y ?? 0) + arrowHeight / 2;
    let x2 = "";
    let y = "";
    if (placedSide === "bottom") {
      x2 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;
      y = `${-arrowHeight}px`;
    } else if (placedSide === "top") {
      x2 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;
      y = `${rects.floating.height + arrowHeight}px`;
    } else if (placedSide === "right") {
      x2 = `${-arrowHeight}px`;
      y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;
    } else if (placedSide === "left") {
      x2 = `${rects.floating.width + arrowHeight}px`;
      y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;
    }
    return { data: { x: x2, y } };
  }
});
function getSideAndAlignFromPlacement(placement) {
  const [side, align = "center"] = placement.split("-");
  return [side, align];
}
var Root2$2 = Popper;
var Anchor = PopperAnchor;
var Content = PopperContent;
var Arrow = PopperArrow;
// @__NO_SIDE_EFFECTS__
function createSlot$1(ownerName) {
  const SlotClone = /* @__PURE__ */ createSlotClone$1(ownerName);
  const Slot2 = reactExports.forwardRef((props, forwardedRef) => {
    const { children, ...slotProps } = props;
    const childrenArray = reactExports.Children.toArray(children);
    const slottable = childrenArray.find(isSlottable$1);
    if (slottable) {
      const newElement = slottable.props.children;
      const newChildren = childrenArray.map((child) => {
        if (child === slottable) {
          if (reactExports.Children.count(newElement) > 1) return reactExports.Children.only(null);
          return reactExports.isValidElement(newElement) ? newElement.props.children : null;
        } else {
          return child;
        }
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children: reactExports.isValidElement(newElement) ? reactExports.cloneElement(newElement, void 0, newChildren) : null });
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children });
  });
  Slot2.displayName = `${ownerName}.Slot`;
  return Slot2;
}
// @__NO_SIDE_EFFECTS__
function createSlotClone$1(ownerName) {
  const SlotClone = reactExports.forwardRef((props, forwardedRef) => {
    const { children, ...slotProps } = props;
    if (reactExports.isValidElement(children)) {
      const childrenRef = getElementRef$1(children);
      const props2 = mergeProps$1(slotProps, children.props);
      if (children.type !== reactExports.Fragment) {
        props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;
      }
      return reactExports.cloneElement(children, props2);
    }
    return reactExports.Children.count(children) > 1 ? reactExports.Children.only(null) : null;
  });
  SlotClone.displayName = `${ownerName}.SlotClone`;
  return SlotClone;
}
var SLOTTABLE_IDENTIFIER$2 = /* @__PURE__ */ Symbol("radix.slottable");
function isSlottable$1(child) {
  return reactExports.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER$2;
}
function mergeProps$1(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          const result = childPropValue(...args);
          slotPropValue(...args);
          return result;
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef$1(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}
var POPOVER_NAME = "Popover";
var [createPopoverContext] = createContextScope(POPOVER_NAME, [
  createPopperScope
]);
var usePopperScope$2 = createPopperScope();
var [PopoverProvider, usePopoverContext] = createPopoverContext(POPOVER_NAME);
var Popover$1 = (props) => {
  const {
    __scopePopover,
    children,
    open: openProp,
    defaultOpen,
    onOpenChange,
    modal = false
  } = props;
  const popperScope = usePopperScope$2(__scopePopover);
  const triggerRef = reactExports.useRef(null);
  const [hasCustomAnchor, setHasCustomAnchor] = reactExports.useState(false);
  const [open, setOpen] = useControllableState({
    prop: openProp,
    defaultProp: defaultOpen ?? false,
    onChange: onOpenChange,
    caller: POPOVER_NAME
  });
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Root2$2, { ...popperScope, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
    PopoverProvider,
    {
      scope: __scopePopover,
      contentId: useId(),
      triggerRef,
      open,
      onOpenChange: setOpen,
      onOpenToggle: reactExports.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen]),
      hasCustomAnchor,
      onCustomAnchorAdd: reactExports.useCallback(() => setHasCustomAnchor(true), []),
      onCustomAnchorRemove: reactExports.useCallback(() => setHasCustomAnchor(false), []),
      modal,
      children
    }
  ) });
};
Popover$1.displayName = POPOVER_NAME;
var ANCHOR_NAME = "PopoverAnchor";
var PopoverAnchor = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopover, ...anchorProps } = props;
    const context = usePopoverContext(ANCHOR_NAME, __scopePopover);
    const popperScope = usePopperScope$2(__scopePopover);
    const { onCustomAnchorAdd, onCustomAnchorRemove } = context;
    reactExports.useEffect(() => {
      onCustomAnchorAdd();
      return () => onCustomAnchorRemove();
    }, [onCustomAnchorAdd, onCustomAnchorRemove]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Anchor, { ...popperScope, ...anchorProps, ref: forwardedRef });
  }
);
PopoverAnchor.displayName = ANCHOR_NAME;
var TRIGGER_NAME$3 = "PopoverTrigger";
var PopoverTrigger$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopover, ...triggerProps } = props;
    const context = usePopoverContext(TRIGGER_NAME$3, __scopePopover);
    const popperScope = usePopperScope$2(__scopePopover);
    const composedTriggerRef = useComposedRefs(forwardedRef, context.triggerRef);
    const trigger = /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.button,
      {
        type: "button",
        "aria-haspopup": "dialog",
        "aria-expanded": context.open,
        "aria-controls": context.contentId,
        "data-state": getState$2(context.open),
        ...triggerProps,
        ref: composedTriggerRef,
        onClick: composeEventHandlers(props.onClick, context.onOpenToggle)
      }
    );
    return context.hasCustomAnchor ? trigger : /* @__PURE__ */ jsxRuntimeExports.jsx(Anchor, { asChild: true, ...popperScope, children: trigger });
  }
);
PopoverTrigger$1.displayName = TRIGGER_NAME$3;
var PORTAL_NAME$2 = "PopoverPortal";
var [PortalProvider$1, usePortalContext$1] = createPopoverContext(PORTAL_NAME$2, {
  forceMount: void 0
});
var PopoverPortal = (props) => {
  const { __scopePopover, forceMount, children, container } = props;
  const context = usePopoverContext(PORTAL_NAME$2, __scopePopover);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(PortalProvider$1, { scope: __scopePopover, forceMount, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Portal$3, { asChild: true, container, children }) }) });
};
PopoverPortal.displayName = PORTAL_NAME$2;
var CONTENT_NAME$2 = "PopoverContent";
var PopoverContent$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const portalContext = usePortalContext$1(CONTENT_NAME$2, props.__scopePopover);
    const { forceMount = portalContext.forceMount, ...contentProps } = props;
    const context = usePopoverContext(CONTENT_NAME$2, props.__scopePopover);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Presence, { present: forceMount || context.open, children: context.modal ? /* @__PURE__ */ jsxRuntimeExports.jsx(PopoverContentModal, { ...contentProps, ref: forwardedRef }) : /* @__PURE__ */ jsxRuntimeExports.jsx(PopoverContentNonModal, { ...contentProps, ref: forwardedRef }) });
  }
);
PopoverContent$1.displayName = CONTENT_NAME$2;
var Slot$1 = /* @__PURE__ */ createSlot$1("PopoverContent.RemoveScroll");
var PopoverContentModal = reactExports.forwardRef(
  (props, forwardedRef) => {
    const context = usePopoverContext(CONTENT_NAME$2, props.__scopePopover);
    const contentRef = reactExports.useRef(null);
    const composedRefs = useComposedRefs(forwardedRef, contentRef);
    const isRightClickOutsideRef = reactExports.useRef(false);
    reactExports.useEffect(() => {
      const content = contentRef.current;
      if (content) return hideOthers(content);
    }, []);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(ReactRemoveScroll, { as: Slot$1, allowPinchZoom: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      PopoverContentImpl,
      {
        ...props,
        ref: composedRefs,
        trapFocus: context.open,
        disableOutsidePointerEvents: true,
        onCloseAutoFocus: composeEventHandlers(props.onCloseAutoFocus, (event) => {
          event.preventDefault();
          if (!isRightClickOutsideRef.current) context.triggerRef.current?.focus();
        }),
        onPointerDownOutside: composeEventHandlers(
          props.onPointerDownOutside,
          (event) => {
            const originalEvent = event.detail.originalEvent;
            const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;
            const isRightClick = originalEvent.button === 2 || ctrlLeftClick;
            isRightClickOutsideRef.current = isRightClick;
          },
          { checkForDefaultPrevented: false }
        ),
        onFocusOutside: composeEventHandlers(
          props.onFocusOutside,
          (event) => event.preventDefault(),
          { checkForDefaultPrevented: false }
        )
      }
    ) });
  }
);
var PopoverContentNonModal = reactExports.forwardRef(
  (props, forwardedRef) => {
    const context = usePopoverContext(CONTENT_NAME$2, props.__scopePopover);
    const hasInteractedOutsideRef = reactExports.useRef(false);
    const hasPointerDownOutsideRef = reactExports.useRef(false);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      PopoverContentImpl,
      {
        ...props,
        ref: forwardedRef,
        trapFocus: false,
        disableOutsidePointerEvents: false,
        onCloseAutoFocus: (event) => {
          props.onCloseAutoFocus?.(event);
          if (!event.defaultPrevented) {
            if (!hasInteractedOutsideRef.current) context.triggerRef.current?.focus();
            event.preventDefault();
          }
          hasInteractedOutsideRef.current = false;
          hasPointerDownOutsideRef.current = false;
        },
        onInteractOutside: (event) => {
          props.onInteractOutside?.(event);
          if (!event.defaultPrevented) {
            hasInteractedOutsideRef.current = true;
            if (event.detail.originalEvent.type === "pointerdown") {
              hasPointerDownOutsideRef.current = true;
            }
          }
          const target = event.target;
          const targetIsTrigger = context.triggerRef.current?.contains(target);
          if (targetIsTrigger) event.preventDefault();
          if (event.detail.originalEvent.type === "focusin" && hasPointerDownOutsideRef.current) {
            event.preventDefault();
          }
        }
      }
    );
  }
);
var PopoverContentImpl = reactExports.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopePopover,
      trapFocus,
      onOpenAutoFocus,
      onCloseAutoFocus,
      disableOutsidePointerEvents,
      onEscapeKeyDown,
      onPointerDownOutside,
      onFocusOutside,
      onInteractOutside,
      ...contentProps
    } = props;
    const context = usePopoverContext(CONTENT_NAME$2, __scopePopover);
    const popperScope = usePopperScope$2(__scopePopover);
    useFocusGuards();
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      FocusScope,
      {
        asChild: true,
        loop: true,
        trapped: trapFocus,
        onMountAutoFocus: onOpenAutoFocus,
        onUnmountAutoFocus: onCloseAutoFocus,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          DismissableLayer,
          {
            asChild: true,
            disableOutsidePointerEvents,
            onInteractOutside,
            onEscapeKeyDown,
            onPointerDownOutside,
            onFocusOutside,
            onDismiss: () => context.onOpenChange(false),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              Content,
              {
                "data-state": getState$2(context.open),
                role: "dialog",
                id: context.contentId,
                ...popperScope,
                ...contentProps,
                ref: forwardedRef,
                style: {
                  ...contentProps.style,
                  // re-namespace exposed content custom properties
                  ...{
                    "--radix-popover-content-transform-origin": "var(--radix-popper-transform-origin)",
                    "--radix-popover-content-available-width": "var(--radix-popper-available-width)",
                    "--radix-popover-content-available-height": "var(--radix-popper-available-height)",
                    "--radix-popover-trigger-width": "var(--radix-popper-anchor-width)",
                    "--radix-popover-trigger-height": "var(--radix-popper-anchor-height)"
                  }
                }
              }
            )
          }
        )
      }
    );
  }
);
var CLOSE_NAME = "PopoverClose";
var PopoverClose = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopover, ...closeProps } = props;
    const context = usePopoverContext(CLOSE_NAME, __scopePopover);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.button,
      {
        type: "button",
        ...closeProps,
        ref: forwardedRef,
        onClick: composeEventHandlers(props.onClick, () => context.onOpenChange(false))
      }
    );
  }
);
PopoverClose.displayName = CLOSE_NAME;
var ARROW_NAME$2 = "PopoverArrow";
var PopoverArrow = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopover, ...arrowProps } = props;
    const popperScope = usePopperScope$2(__scopePopover);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Arrow, { ...popperScope, ...arrowProps, ref: forwardedRef });
  }
);
PopoverArrow.displayName = ARROW_NAME$2;
function getState$2(open) {
  return open ? "open" : "closed";
}
var Root2$1 = Popover$1;
var Trigger$2 = PopoverTrigger$1;
var Portal$1 = PopoverPortal;
var Content2$2 = PopoverContent$1;
const Popover = Root2$1;
const PopoverTrigger = Trigger$2;
const PopoverContent = reactExports.forwardRef(({ className, align = "center", sideOffset = 4, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(Portal$1, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
  Content2$2,
  {
    ref: ref2,
    align,
    sideOffset,
    className: cn$1(
      "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
      className
    ),
    ...props
  }
) }));
PopoverContent.displayName = Content2$2.displayName;
function Combobox({
  value,
  onChange,
  onInputChange,
  onFocus,
  options = [],
  placeholder = "Select...",
  emptyMessage = "No results found.",
  id: id2
}) {
  const [open, setOpen] = React.useState(false);
  const handleOpenChange = React.useCallback(
    (newOpen) => {
      setOpen(newOpen);
      if (newOpen && onFocus) {
        onFocus();
      }
    },
    [onFocus]
  );
  const handleSelect = React.useCallback(
    (option) => {
      onChange(option);
      setOpen(false);
    },
    [onChange]
  );
  const handleInputChange = React.useCallback(
    (value2) => {
      onInputChange(value2);
    },
    [onInputChange]
  );
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Popover, { open, onOpenChange: handleOpenChange, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Button,
      {
        variant: "outline",
        role: "combobox",
        "aria-expanded": open,
        "aria-controls": id2,
        className: "w-full justify-between",
        children: [
          value || placeholder,
          /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronsUpDown, { className: "ml-2 h-4 w-4 shrink-0 opacity-50" })
        ]
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(PopoverContent, { className: "w-full p-0", align: "start", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Command, { shouldFilter: false, id: id2, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        CommandInput,
        {
          placeholder,
          value,
          onValueChange: handleInputChange
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CommandEmpty, { children: emptyMessage }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CommandGroup, { children: options.map((option) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
        CommandItem,
        {
          value: option,
          onSelect: () => handleSelect(option),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Check,
              {
                className: cn$1(
                  "mr-2 h-4 w-4",
                  value === option ? "opacity-100" : "opacity-0"
                )
              }
            ),
            option
          ]
        },
        option
      )) })
    ] }) })
  ] });
}
var NODES = [
  "a",
  "button",
  "div",
  "form",
  "h2",
  "h3",
  "img",
  "input",
  "label",
  "li",
  "nav",
  "ol",
  "p",
  "select",
  "span",
  "svg",
  "ul"
];
var Primitive = NODES.reduce((primitive, node) => {
  const Slot2 = /* @__PURE__ */ createSlot$3(`Primitive.${node}`);
  const Node2 = reactExports.forwardRef((props, forwardedRef) => {
    const { asChild, ...primitiveProps } = props;
    const Comp = asChild ? Slot2 : node;
    if (typeof window !== "undefined") {
      window[/* @__PURE__ */ Symbol.for("radix-ui")] = true;
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Comp, { ...primitiveProps, ref: forwardedRef });
  });
  Node2.displayName = `Primitive.${node}`;
  return { ...primitive, [node]: Node2 };
}, {});
var NAME = "Label";
var Label$2 = reactExports.forwardRef((props, forwardedRef) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    Primitive.label,
    {
      ...props,
      ref: forwardedRef,
      onMouseDown: (event) => {
        const target = event.target;
        if (target.closest("button, input, select, textarea")) return;
        props.onMouseDown?.(event);
        if (!event.defaultPrevented && event.detail > 1) event.preventDefault();
      }
    }
  );
});
Label$2.displayName = NAME;
var Root$1 = Label$2;
const labelVariants = cva(
  "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
);
const Label$1 = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Root$1,
  {
    ref: ref2,
    className: cn$1(labelVariants(), className),
    ...props
  }
));
Label$1.displayName = Root$1.displayName;
const Input = reactExports.forwardRef(
  ({ className, type: type2, ...props }, ref2) => {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        type: type2,
        className: cn$1(
          "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
          className
        ),
        ref: ref2,
        ...props
      }
    );
  }
);
Input.displayName = "Input";
const ListPane = ({
  items: items2,
  listItems,
  clearItems,
  setSelectedItem,
  renderItem,
  title: title2,
  buttonText,
  isButtonDisabled
}) => {
  const [searchQuery, setSearchQuery] = reactExports.useState("");
  const [isSearchExpanded, setIsSearchExpanded] = reactExports.useState(false);
  const searchInputRef = reactExports.useRef(null);
  const filteredItems = reactExports.useMemo(() => {
    if (!searchQuery.trim()) return items2;
    return items2.filter((item) => {
      const searchableText = [
        item.name || "",
        item.description || ""
      ].join(" ").toLowerCase();
      return searchableText.includes(searchQuery.toLowerCase());
    });
  }, [items2, searchQuery]);
  const handleSearchClick = () => {
    setIsSearchExpanded(true);
    setTimeout(() => {
      searchInputRef.current?.focus();
    }, 100);
  };
  const handleSearchBlur = () => {
    if (!searchQuery.trim()) {
      setIsSearchExpanded(false);
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-card border border-border rounded-lg shadow", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4 border-b border-gray-200 dark:border-border", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between gap-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "font-semibold dark:text-white flex-shrink-0", children: title2 }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-end min-w-0 flex-1", children: !isSearchExpanded ? /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          name: "search",
          "aria-label": "Search",
          onClick: handleSearchClick,
          className: "p-2 hover:bg-gray-100 dark:hover:bg-secondary rounded-md transition-all duration-300 ease-in-out",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "w-4 h-4 text-muted-foreground" })
        }
      ) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center w-full max-w-xs", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none z-10" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            ref: searchInputRef,
            name: "search",
            type: "text",
            placeholder: "Search...",
            value: searchQuery,
            onChange: (e2) => setSearchQuery(e2.target.value),
            onBlur: handleSearchBlur,
            className: "pl-10 w-full transition-all duration-300 ease-in-out"
          }
        )
      ] }) }) })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          variant: "outline",
          className: "w-full mb-4",
          onClick: listItems,
          disabled: isButtonDisabled,
          children: buttonText
        }
      ),
      clearItems && /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          variant: "outline",
          className: "w-full mb-4",
          onClick: clearItems,
          disabled: items2.length === 0,
          children: "Clear"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2 overflow-y-auto max-h-96", children: [
        filteredItems.map((item, index2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: "flex items-center py-2 px-4 rounded hover:bg-gray-50 dark:hover:bg-secondary cursor-pointer",
            onClick: () => setSelectedItem(item),
            children: renderItem(item)
          },
          index2
        )),
        filteredItems.length === 0 && searchQuery && items2.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-4 text-muted-foreground", children: [
          'No items found matching "',
          searchQuery,
          '"'
        ] })
      ] })
    ] })
  ] });
};
function debounce(func, wait) {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      void func(...args);
    }, wait);
  };
}
function useCompletionState(handleCompletion, completionsSupported = true, debounceMs = 300) {
  const [state, setState] = reactExports.useState({
    completions: {},
    loading: {}
  });
  const abortControllerRef = reactExports.useRef(null);
  const cleanup = reactExports.useCallback(() => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
    }
  }, []);
  reactExports.useEffect(() => {
    return cleanup;
  }, [cleanup]);
  const clearCompletions = reactExports.useCallback(() => {
    cleanup();
    setState({
      completions: {},
      loading: {}
    });
  }, [cleanup]);
  const requestCompletions = reactExports.useMemo(() => {
    return debounce(
      async (ref2, argName, value, context) => {
        if (!completionsSupported) {
          return;
        }
        cleanup();
        const abortController = new AbortController();
        abortControllerRef.current = abortController;
        setState((prev) => ({
          ...prev,
          loading: { ...prev.loading, [argName]: true }
        }));
        try {
          if (context !== void 0) {
            delete context[argName];
          }
          const values = await handleCompletion(
            ref2,
            argName,
            value,
            context,
            abortController.signal
          );
          if (!abortController.signal.aborted) {
            setState((prev) => ({
              ...prev,
              completions: { ...prev.completions, [argName]: values },
              loading: { ...prev.loading, [argName]: false }
            }));
          }
        } catch {
          console.error("completion failed");
          if (!abortController.signal.aborted) {
            setState((prev) => ({
              ...prev,
              loading: { ...prev.loading, [argName]: false }
            }));
          }
        } finally {
          if (abortControllerRef.current === abortController) {
            abortControllerRef.current = null;
          }
        }
      },
      debounceMs
    );
  }, [handleCompletion, completionsSupported, cleanup, debounceMs]);
  reactExports.useEffect(() => {
    if (!completionsSupported) {
      clearCompletions();
    }
  }, [completionsSupported, clearCompletions]);
  return {
    ...state,
    clearCompletions,
    requestCompletions,
    completionsSupported
  };
}
const IconDisplay = ({
  icons,
  className = "",
  size: size2 = "md"
}) => {
  if (!icons || icons.length === 0) {
    return null;
  }
  const sizeClasses = {
    sm: "w-4 h-4",
    md: "w-6 h-6",
    lg: "w-8 h-8"
  };
  const sizeClass = sizeClasses[size2];
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: `flex gap-1 ${className}`, children: icons.map((icon, index2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "img",
    {
      src: icon.src,
      alt: "",
      className: `${sizeClass} object-contain flex-shrink-0`,
      style: {
        imageRendering: "auto"
      },
      onError: (e2) => {
        e2.currentTarget.style.display = "none";
      }
    },
    index2
  )) });
};
const PromptsTab = ({
  prompts,
  listPrompts,
  clearPrompts,
  getPrompt,
  selectedPrompt,
  setSelectedPrompt,
  handleCompletion,
  completionsSupported,
  promptContent,
  nextCursor,
  error
}) => {
  const [promptArgs, setPromptArgs] = reactExports.useState({});
  const { completions, clearCompletions, requestCompletions } = useCompletionState(handleCompletion, completionsSupported);
  reactExports.useEffect(() => {
    clearCompletions();
  }, [clearCompletions, selectedPrompt]);
  const triggerCompletions = (argName, value) => {
    if (selectedPrompt) {
      requestCompletions(
        {
          type: "ref/prompt",
          name: selectedPrompt.name
        },
        argName,
        value,
        promptArgs
      );
    }
  };
  const handleInputChange = async (argName, value) => {
    setPromptArgs((prev) => ({ ...prev, [argName]: value }));
    triggerCompletions(argName, value);
  };
  const handleFocus = async (argName) => {
    const currentValue = promptArgs[argName] || "";
    triggerCompletions(argName, currentValue);
  };
  const handleGetPrompt = () => {
    if (selectedPrompt) {
      getPrompt(selectedPrompt.name, promptArgs);
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(TabsContent, { value: "prompts", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ListPane,
      {
        items: prompts,
        listItems: listPrompts,
        clearItems: () => {
          clearPrompts();
          setSelectedPrompt(null);
        },
        setSelectedItem: (prompt) => {
          setSelectedPrompt(prompt);
          setPromptArgs({});
        },
        renderItem: (prompt) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start w-full gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-shrink-0 mt-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx(IconDisplay, { icons: prompt.icons, size: "sm" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col flex-1 min-w-0", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "truncate", children: prompt.name }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-500 text-left line-clamp-2", children: prompt.description })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "w-4 h-4 flex-shrink-0 text-gray-400 mt-1" })
        ] }),
        title: "Prompts",
        buttonText: nextCursor ? "List More Prompts" : "List Prompts",
        isButtonDisabled: !nextCursor && prompts.length > 0
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-card border border-border rounded-lg shadow", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4 border-b border-gray-200 dark:border-border", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        selectedPrompt && /* @__PURE__ */ jsxRuntimeExports.jsx(
          IconDisplay,
          {
            icons: selectedPrompt.icons,
            size: "md"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "font-semibold", children: selectedPrompt ? selectedPrompt.name : "Select a prompt" })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4", children: error ? /* @__PURE__ */ jsxRuntimeExports.jsxs(Alert, { variant: "destructive", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CircleAlert, { className: "h-4 w-4" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTitle, { children: "Error" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { className: "break-all", children: error })
      ] }) : selectedPrompt ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
        selectedPrompt.description && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: selectedPrompt.description }),
        selectedPrompt.arguments?.map((arg) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label$1, { htmlFor: arg.name, children: arg.name }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Combobox,
            {
              id: arg.name,
              placeholder: `Enter ${arg.name}`,
              value: promptArgs[arg.name] || "",
              onChange: (value) => handleInputChange(arg.name, value),
              onInputChange: (value) => handleInputChange(arg.name, value),
              onFocus: () => handleFocus(arg.name),
              options: completions[arg.name] || []
            }
          ),
          arg.description && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-gray-500 mt-1", children: [
            arg.description,
            arg.required && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs mt-1 ml-1", children: "(Required)" })
          ] })
        ] }, arg.name)),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { onClick: handleGetPrompt, className: "w-full", children: "Get Prompt" }),
        promptContent && /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: promptContent, withCopyButton: false })
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Alert, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { children: "Select a prompt from the list to view and use it" }) }) })
    ] })
  ] }) });
};
const MAX_TEMPLATE_LENGTH = 1e6;
const MAX_VARIABLE_LENGTH = 1e6;
const MAX_TEMPLATE_EXPRESSIONS = 1e4;
const MAX_REGEX_LENGTH = 1e6;
class UriTemplate {
  /**
   * Returns true if the given string contains any URI template expressions.
   * A template expression is a sequence of characters enclosed in curly braces,
   * like {foo} or {?bar}.
   */
  static isTemplate(str) {
    return /\{[^}\s]+\}/.test(str);
  }
  static validateLength(str, max2, context) {
    if (str.length > max2) {
      throw new Error(`${context} exceeds maximum length of ${max2} characters (got ${str.length})`);
    }
  }
  get variableNames() {
    return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names);
  }
  constructor(template) {
    UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template");
    this.template = template;
    this.parts = this.parse(template);
  }
  toString() {
    return this.template;
  }
  parse(template) {
    const parts = [];
    let currentText = "";
    let i2 = 0;
    let expressionCount = 0;
    while (i2 < template.length) {
      if (template[i2] === "{") {
        if (currentText) {
          parts.push(currentText);
          currentText = "";
        }
        const end = template.indexOf("}", i2);
        if (end === -1)
          throw new Error("Unclosed template expression");
        expressionCount++;
        if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) {
          throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);
        }
        const expr = template.slice(i2 + 1, end);
        const operator = this.getOperator(expr);
        const exploded = expr.includes("*");
        const names2 = this.getNames(expr);
        const name2 = names2[0];
        for (const name3 of names2) {
          UriTemplate.validateLength(name3, MAX_VARIABLE_LENGTH, "Variable name");
        }
        parts.push({ name: name2, operator, names: names2, exploded });
        i2 = end + 1;
      } else {
        currentText += template[i2];
        i2++;
      }
    }
    if (currentText) {
      parts.push(currentText);
    }
    return parts;
  }
  getOperator(expr) {
    const operators = ["+", "#", ".", "/", "?", "&"];
    return operators.find((op2) => expr.startsWith(op2)) || "";
  }
  getNames(expr) {
    const operator = this.getOperator(expr);
    return expr.slice(operator.length).split(",").map((name2) => name2.replace("*", "").trim()).filter((name2) => name2.length > 0);
  }
  encodeValue(value, operator) {
    UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value");
    if (operator === "+" || operator === "#") {
      return encodeURI(value);
    }
    return encodeURIComponent(value);
  }
  expandPart(part, variables) {
    if (part.operator === "?" || part.operator === "&") {
      const pairs = part.names.map((name2) => {
        const value2 = variables[name2];
        if (value2 === void 0)
          return "";
        const encoded2 = Array.isArray(value2) ? value2.map((v2) => this.encodeValue(v2, part.operator)).join(",") : this.encodeValue(value2.toString(), part.operator);
        return `${name2}=${encoded2}`;
      }).filter((pair) => pair.length > 0);
      if (pairs.length === 0)
        return "";
      const separator = part.operator === "?" ? "?" : "&";
      return separator + pairs.join("&");
    }
    if (part.names.length > 1) {
      const values2 = part.names.map((name2) => variables[name2]).filter((v2) => v2 !== void 0);
      if (values2.length === 0)
        return "";
      return values2.map((v2) => Array.isArray(v2) ? v2[0] : v2).join(",");
    }
    const value = variables[part.name];
    if (value === void 0)
      return "";
    const values = Array.isArray(value) ? value : [value];
    const encoded = values.map((v2) => this.encodeValue(v2, part.operator));
    switch (part.operator) {
      case "":
        return encoded.join(",");
      case "+":
        return encoded.join(",");
      case "#":
        return "#" + encoded.join(",");
      case ".":
        return "." + encoded.join(".");
      case "/":
        return "/" + encoded.join("/");
      default:
        return encoded.join(",");
    }
  }
  expand(variables) {
    let result = "";
    let hasQueryParam = false;
    for (const part of this.parts) {
      if (typeof part === "string") {
        result += part;
        continue;
      }
      const expanded = this.expandPart(part, variables);
      if (!expanded)
        continue;
      if ((part.operator === "?" || part.operator === "&") && hasQueryParam) {
        result += expanded.replace("?", "&");
      } else {
        result += expanded;
      }
      if (part.operator === "?" || part.operator === "&") {
        hasQueryParam = true;
      }
    }
    return result;
  }
  escapeRegExp(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  }
  partToRegExp(part) {
    const patterns = [];
    for (const name3 of part.names) {
      UriTemplate.validateLength(name3, MAX_VARIABLE_LENGTH, "Variable name");
    }
    if (part.operator === "?" || part.operator === "&") {
      for (let i2 = 0; i2 < part.names.length; i2++) {
        const name3 = part.names[i2];
        const prefix = i2 === 0 ? "\\" + part.operator : "&";
        patterns.push({
          pattern: prefix + this.escapeRegExp(name3) + "=([^&]+)",
          name: name3
        });
      }
      return patterns;
    }
    let pattern2;
    const name2 = part.name;
    switch (part.operator) {
      case "":
        pattern2 = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)";
        break;
      case "+":
      case "#":
        pattern2 = "(.+)";
        break;
      case ".":
        pattern2 = "\\.([^/,]+)";
        break;
      case "/":
        pattern2 = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)");
        break;
      default:
        pattern2 = "([^/]+)";
    }
    patterns.push({ pattern: pattern2, name: name2 });
    return patterns;
  }
  match(uri2) {
    UriTemplate.validateLength(uri2, MAX_TEMPLATE_LENGTH, "URI");
    let pattern2 = "^";
    const names2 = [];
    for (const part of this.parts) {
      if (typeof part === "string") {
        pattern2 += this.escapeRegExp(part);
      } else {
        const patterns = this.partToRegExp(part);
        for (const { pattern: partPattern, name: name2 } of patterns) {
          pattern2 += partPattern;
          names2.push({ name: name2, exploded: part.exploded });
        }
      }
    }
    pattern2 += "$";
    UriTemplate.validateLength(pattern2, MAX_REGEX_LENGTH, "Generated regex pattern");
    const regex = new RegExp(pattern2);
    const match = uri2.match(regex);
    if (!match)
      return null;
    const result = {};
    for (let i2 = 0; i2 < names2.length; i2++) {
      const { name: name2, exploded } = names2[i2];
      const value = match[i2 + 1];
      const cleanName = name2.replace("*", "");
      if (exploded && value.includes(",")) {
        result[cleanName] = value.split(",");
      } else {
        result[cleanName] = value;
      }
    }
    return result;
  }
}
const ResourcesTab = ({
  resources,
  resourceTemplates,
  listResources,
  clearResources,
  listResourceTemplates,
  clearResourceTemplates,
  readResource,
  selectedResource,
  setSelectedResource,
  resourceSubscriptionsSupported,
  resourceSubscriptions,
  subscribeToResource,
  unsubscribeFromResource,
  handleCompletion,
  completionsSupported,
  resourceContent,
  nextCursor,
  nextTemplateCursor,
  error
}) => {
  const [selectedTemplate, setSelectedTemplate] = reactExports.useState(null);
  const [templateValues, setTemplateValues] = reactExports.useState(
    {}
  );
  const { completions, clearCompletions, requestCompletions } = useCompletionState(handleCompletion, completionsSupported);
  reactExports.useEffect(() => {
    clearCompletions();
  }, [clearCompletions]);
  const fillTemplate = (template, values) => {
    return new UriTemplate(template).expand(values);
  };
  const handleTemplateValueChange = async (key, value) => {
    setTemplateValues((prev) => ({ ...prev, [key]: value }));
    if (selectedTemplate?.uriTemplate) {
      requestCompletions(
        {
          type: "ref/resource",
          uri: selectedTemplate.uriTemplate
        },
        key,
        value,
        templateValues
      );
    }
  };
  const handleReadTemplateResource = () => {
    if (selectedTemplate) {
      const uri2 = fillTemplate(selectedTemplate.uriTemplate, templateValues);
      readResource(uri2);
      setSelectedResource({ uri: uri2, name: uri2 });
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(TabsContent, { value: "resources", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-3 gap-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ListPane,
      {
        items: resources,
        listItems: listResources,
        clearItems: () => {
          clearResources();
          if (!selectedTemplate) {
            setSelectedResource(null);
          }
        },
        setSelectedItem: (resource) => {
          setSelectedResource(resource);
          readResource(resource.uri);
          setSelectedTemplate(null);
        },
        renderItem: (resource) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center w-full", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(IconDisplay, { icons: resource.icons, size: "sm" }),
          !resource.icons && /* @__PURE__ */ jsxRuntimeExports.jsx(FileText, { className: "w-4 h-4 mr-2 flex-shrink-0 text-gray-500" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "flex-1 truncate", title: resource.uri.toString(), children: resource.name }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "w-4 h-4 flex-shrink-0 text-gray-400" })
        ] }),
        title: "Resources",
        buttonText: nextCursor ? "List More Resources" : "List Resources",
        isButtonDisabled: !nextCursor && resources.length > 0
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ListPane,
      {
        items: resourceTemplates,
        listItems: listResourceTemplates,
        clearItems: () => {
          clearResourceTemplates();
          if (selectedTemplate) {
            setSelectedResource(null);
          }
          setSelectedTemplate(null);
        },
        setSelectedItem: (template) => {
          setSelectedTemplate(template);
          setSelectedResource(null);
          setTemplateValues({});
        },
        renderItem: (template) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center w-full", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(IconDisplay, { icons: template.icons, size: "sm" }),
          !template.icons && /* @__PURE__ */ jsxRuntimeExports.jsx(FileText, { className: "w-4 h-4 mr-2 flex-shrink-0 text-gray-500" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "flex-1 truncate", title: template.uriTemplate, children: template.name }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "w-4 h-4 flex-shrink-0 text-gray-400" })
        ] }),
        title: "Resource Templates",
        buttonText: nextTemplateCursor ? "List More Templates" : "List Templates",
        isButtonDisabled: !nextTemplateCursor && resourceTemplates.length > 0
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-card border border-border rounded-lg shadow", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-4 border-b border-gray-200 dark:border-border flex justify-between items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 truncate", children: [
          (selectedResource || selectedTemplate) && /* @__PURE__ */ jsxRuntimeExports.jsx(
            IconDisplay,
            {
              icons: (selectedResource || selectedTemplate).icons,
              size: "md"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "h3",
            {
              className: "font-semibold truncate",
              title: selectedResource?.name || selectedTemplate?.name,
              children: selectedResource ? selectedResource.name : selectedTemplate ? selectedTemplate.name : "Select a resource or template"
            }
          )
        ] }),
        selectedResource && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex row-auto gap-1 justify-end w-2/5", children: [
          resourceSubscriptionsSupported && !resourceSubscriptions.has(selectedResource.uri) && /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: () => subscribeToResource(selectedResource.uri),
              children: "Subscribe"
            }
          ),
          resourceSubscriptionsSupported && resourceSubscriptions.has(selectedResource.uri) && /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: () => unsubscribeFromResource(selectedResource.uri),
              children: "Unsubscribe"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: () => readResource(selectedResource.uri),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-4 h-4 mr-2" }),
                "Refresh"
              ]
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4", children: error ? /* @__PURE__ */ jsxRuntimeExports.jsxs(Alert, { variant: "destructive", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CircleAlert, { className: "h-4 w-4" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTitle, { children: "Error" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { className: "break-all", children: error })
      ] }) : selectedResource ? /* @__PURE__ */ jsxRuntimeExports.jsx(
        JsonView,
        {
          data: resourceContent,
          className: "bg-gray-50 dark:bg-gray-800 p-4 rounded text-sm overflow-auto max-h-96 text-gray-900 dark:text-gray-100"
        }
      ) : selectedTemplate ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: selectedTemplate.description }),
        new UriTemplate(
          selectedTemplate.uriTemplate
        ).variableNames?.map((key) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Label$1, { htmlFor: key, children: key }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Combobox,
              {
                id: key,
                placeholder: `Enter ${key}`,
                value: templateValues[key] || "",
                onChange: (value) => handleTemplateValueChange(key, value),
                onInputChange: (value) => handleTemplateValueChange(key, value),
                options: completions[key] || []
              }
            )
          ] }, key);
        }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            onClick: handleReadTemplateResource,
            disabled: Object.keys(templateValues).length === 0,
            children: "Read Resource"
          }
        )
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Alert, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { children: "Select a resource or template from the list to view its contents" }) }) })
    ] })
  ] }) });
};
const RootsTab = ({
  roots,
  setRoots,
  onRootsChange
}) => {
  const addRoot = () => {
    setRoots((currentRoots) => [...currentRoots, { uri: "file://", name: "" }]);
  };
  const removeRoot = (index2) => {
    setRoots((currentRoots) => currentRoots.filter((_2, i2) => i2 !== index2));
  };
  const updateRoot = (index2, field, value) => {
    setRoots(
      (currentRoots) => currentRoots.map(
        (root, i2) => i2 === index2 ? { ...root, [field]: value } : root
      )
    );
  };
  const handleSave = () => {
    onRootsChange();
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(TabsContent, { value: "roots", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Alert, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { children: "Configure the root directories that the server can access" }) }),
    roots.map((root, index2) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2 items-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Input,
        {
          placeholder: "file:// URI",
          value: root.uri,
          onChange: (e2) => updateRoot(index2, "uri", e2.target.value),
          className: "flex-1"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          variant: "destructive",
          size: "sm",
          onClick: () => removeRoot(index2),
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(Minus, { className: "h-4 w-4" })
        }
      )
    ] }, index2)),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { variant: "outline", onClick: addRoot, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "h-4 w-4 mr-2" }),
        "Add Root"
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: handleSave, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "h-4 w-4 mr-2" }),
        "Save Changes"
      ] })
    ] })
  ] }) });
};
var lib = {};
var hasRequiredLib;
function requireLib() {
  if (hasRequiredLib) return lib;
  hasRequiredLib = 1;
  var __assign2 = lib && lib.__assign || function() {
    __assign2 = Object.assign || function(t2) {
      for (var s2, i2 = 1, n = arguments.length; i2 < n; i2++) {
        s2 = arguments[i2];
        for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2))
          t2[p2] = s2[p2];
      }
      return t2;
    };
    return __assign2.apply(this, arguments);
  };
  var __createBinding = lib && lib.__createBinding || (Object.create ? (function(o2, m2, k2, k22) {
    if (k22 === void 0) k22 = k2;
    var desc = Object.getOwnPropertyDescriptor(m2, k2);
    if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() {
        return m2[k2];
      } };
    }
    Object.defineProperty(o2, k22, desc);
  }) : (function(o2, m2, k2, k22) {
    if (k22 === void 0) k22 = k2;
    o2[k22] = m2[k2];
  }));
  var __setModuleDefault = lib && lib.__setModuleDefault || (Object.create ? (function(o2, v2) {
    Object.defineProperty(o2, "default", { enumerable: true, value: v2 });
  }) : function(o2, v2) {
    o2["default"] = v2;
  });
  var __importStar = lib && lib.__importStar || function(mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) {
      for (var k2 in mod) if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2)) __createBinding(result, mod, k2);
    }
    __setModuleDefault(result, mod);
    return result;
  };
  var __rest2 = lib && lib.__rest || function(s2, e2) {
    var t2 = {};
    for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
      t2[p2] = s2[p2];
    if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
      for (var i2 = 0, p2 = Object.getOwnPropertySymbols(s2); i2 < p2.length; i2++) {
        if (e2.indexOf(p2[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i2]))
          t2[p2[i2]] = s2[p2[i2]];
      }
    return t2;
  };
  Object.defineProperty(lib, "__esModule", { value: true });
  var React2 = __importStar(requireReact());
  var KEYCODE_Y = 89;
  var KEYCODE_Z = 90;
  var KEYCODE_M = 77;
  var KEYCODE_PARENS = 57;
  var KEYCODE_BRACKETS = 219;
  var KEYCODE_QUOTE = 222;
  var KEYCODE_BACK_QUOTE = 192;
  var HISTORY_LIMIT = 100;
  var HISTORY_TIME_GAP = 3e3;
  var isWindows = typeof window !== "undefined" && "navigator" in window && /Win/i.test(navigator.platform);
  var isMacLike = typeof window !== "undefined" && "navigator" in window && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
  var className = "npm__react-simple-code-editor__textarea";
  var cssText = (
    /* CSS */
    "\n/**\n * Reset the text fill color so that placeholder is visible\n */\n.".concat(className, ":empty {\n  -webkit-text-fill-color: inherit !important;\n}\n\n/**\n * Hack to apply on some CSS on IE10 and IE11\n */\n@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {\n  /**\n    * IE doesn't support '-webkit-text-fill-color'\n    * So we use 'color: transparent' to make the text transparent on IE\n    * Unlike other browsers, it doesn't affect caret color in IE\n    */\n  .").concat(className, " {\n    color: transparent !important;\n  }\n\n  .").concat(className, "::selection {\n    background-color: #accef7 !important;\n    color: transparent !important;\n  }\n}\n")
  );
  var Editor2 = React2.forwardRef(function Editor3(props, ref2) {
    var autoFocus = props.autoFocus, disabled = props.disabled, form = props.form, highlight = props.highlight, _a2 = props.ignoreTabKey, ignoreTabKey = _a2 === void 0 ? false : _a2, _b = props.insertSpaces, insertSpaces = _b === void 0 ? true : _b, maxLength = props.maxLength, minLength = props.minLength, name2 = props.name, onBlur = props.onBlur, onClick = props.onClick, onFocus = props.onFocus, onKeyDown = props.onKeyDown, onKeyUp = props.onKeyUp, onValueChange = props.onValueChange, _c = props.padding, padding = _c === void 0 ? 0 : _c, placeholder = props.placeholder, preClassName = props.preClassName, readOnly = props.readOnly, required2 = props.required, style = props.style, _d2 = props.tabSize, tabSize = _d2 === void 0 ? 2 : _d2, textareaClassName = props.textareaClassName, textareaId = props.textareaId, value = props.value, rest = __rest2(props, ["autoFocus", "disabled", "form", "highlight", "ignoreTabKey", "insertSpaces", "maxLength", "minLength", "name", "onBlur", "onClick", "onFocus", "onKeyDown", "onKeyUp", "onValueChange", "padding", "placeholder", "preClassName", "readOnly", "required", "style", "tabSize", "textareaClassName", "textareaId", "value"]);
    var historyRef = React2.useRef({
      stack: [],
      offset: -1
    });
    var inputRef = React2.useRef(null);
    var _e2 = React2.useState(true), capture = _e2[0], setCapture = _e2[1];
    var contentStyle = {
      paddingTop: typeof padding === "object" ? padding.top : padding,
      paddingRight: typeof padding === "object" ? padding.right : padding,
      paddingBottom: typeof padding === "object" ? padding.bottom : padding,
      paddingLeft: typeof padding === "object" ? padding.left : padding
    };
    var highlighted = highlight(value);
    var getLines = function(text, position) {
      return text.substring(0, position).split("\n");
    };
    var recordChange = React2.useCallback(function(record2, overwrite) {
      var _a3, _b2, _c2;
      if (overwrite === void 0) {
        overwrite = false;
      }
      var _d3 = historyRef.current, stack = _d3.stack, offset2 = _d3.offset;
      if (stack.length && offset2 > -1) {
        historyRef.current.stack = stack.slice(0, offset2 + 1);
        var count2 = historyRef.current.stack.length;
        if (count2 > HISTORY_LIMIT) {
          var extras = count2 - HISTORY_LIMIT;
          historyRef.current.stack = stack.slice(extras, count2);
          historyRef.current.offset = Math.max(historyRef.current.offset - extras, 0);
        }
      }
      var timestamp = Date.now();
      if (overwrite) {
        var last = historyRef.current.stack[historyRef.current.offset];
        if (last && timestamp - last.timestamp < HISTORY_TIME_GAP) {
          var re2 = /[^a-z0-9]([a-z0-9]+)$/i;
          var previous = (_a3 = getLines(last.value, last.selectionStart).pop()) === null || _a3 === void 0 ? void 0 : _a3.match(re2);
          var current = (_b2 = getLines(record2.value, record2.selectionStart).pop()) === null || _b2 === void 0 ? void 0 : _b2.match(re2);
          if ((previous === null || previous === void 0 ? void 0 : previous[1]) && ((_c2 = current === null || current === void 0 ? void 0 : current[1]) === null || _c2 === void 0 ? void 0 : _c2.startsWith(previous[1]))) {
            historyRef.current.stack[historyRef.current.offset] = __assign2(__assign2({}, record2), { timestamp });
            return;
          }
        }
      }
      historyRef.current.stack.push(__assign2(__assign2({}, record2), { timestamp }));
      historyRef.current.offset++;
    }, []);
    var recordCurrentState = React2.useCallback(function() {
      var input = inputRef.current;
      if (!input)
        return;
      var value2 = input.value, selectionStart = input.selectionStart, selectionEnd = input.selectionEnd;
      recordChange({
        value: value2,
        selectionStart,
        selectionEnd
      });
    }, [recordChange]);
    var updateInput = function(record2) {
      var input = inputRef.current;
      if (!input)
        return;
      input.value = record2.value;
      input.selectionStart = record2.selectionStart;
      input.selectionEnd = record2.selectionEnd;
      onValueChange === null || onValueChange === void 0 ? void 0 : onValueChange(record2.value);
    };
    var applyEdits = function(record2) {
      var input = inputRef.current;
      var last = historyRef.current.stack[historyRef.current.offset];
      if (last && input) {
        historyRef.current.stack[historyRef.current.offset] = __assign2(__assign2({}, last), { selectionStart: input.selectionStart, selectionEnd: input.selectionEnd });
      }
      recordChange(record2);
      updateInput(record2);
    };
    var undoEdit = function() {
      var _a3 = historyRef.current, stack = _a3.stack, offset2 = _a3.offset;
      var record2 = stack[offset2 - 1];
      if (record2) {
        updateInput(record2);
        historyRef.current.offset = Math.max(offset2 - 1, 0);
      }
    };
    var redoEdit = function() {
      var _a3 = historyRef.current, stack = _a3.stack, offset2 = _a3.offset;
      var record2 = stack[offset2 + 1];
      if (record2) {
        updateInput(record2);
        historyRef.current.offset = Math.min(offset2 + 1, stack.length - 1);
      }
    };
    var handleKeyDown = function(e2) {
      if (onKeyDown) {
        onKeyDown(e2);
        if (e2.defaultPrevented) {
          return;
        }
      }
      if (e2.key === "Escape") {
        e2.currentTarget.blur();
      }
      var _a3 = e2.currentTarget, value2 = _a3.value, selectionStart = _a3.selectionStart, selectionEnd = _a3.selectionEnd;
      var tabCharacter = (insertSpaces ? " " : "	").repeat(tabSize);
      if (e2.key === "Tab" && !ignoreTabKey && capture) {
        e2.preventDefault();
        if (e2.shiftKey) {
          var linesBeforeCaret = getLines(value2, selectionStart);
          var startLine_1 = linesBeforeCaret.length - 1;
          var endLine_1 = getLines(value2, selectionEnd).length - 1;
          var nextValue = value2.split("\n").map(function(line2, i2) {
            if (i2 >= startLine_1 && i2 <= endLine_1 && line2.startsWith(tabCharacter)) {
              return line2.substring(tabCharacter.length);
            }
            return line2;
          }).join("\n");
          if (value2 !== nextValue) {
            var startLineText = linesBeforeCaret[startLine_1];
            applyEdits({
              value: nextValue,
              // Move the start cursor if first line in selection was modified
              // It was modified only if it started with a tab
              selectionStart: (startLineText === null || startLineText === void 0 ? void 0 : startLineText.startsWith(tabCharacter)) ? selectionStart - tabCharacter.length : selectionStart,
              // Move the end cursor by total number of characters removed
              selectionEnd: selectionEnd - (value2.length - nextValue.length)
            });
          }
        } else if (selectionStart !== selectionEnd) {
          var linesBeforeCaret = getLines(value2, selectionStart);
          var startLine_2 = linesBeforeCaret.length - 1;
          var endLine_2 = getLines(value2, selectionEnd).length - 1;
          var startLineText = linesBeforeCaret[startLine_2];
          applyEdits({
            value: value2.split("\n").map(function(line2, i2) {
              if (i2 >= startLine_2 && i2 <= endLine_2) {
                return tabCharacter + line2;
              }
              return line2;
            }).join("\n"),
            // Move the start cursor by number of characters added in first line of selection
            // Don't move it if it there was no text before cursor
            selectionStart: startLineText && /\S/.test(startLineText) ? selectionStart + tabCharacter.length : selectionStart,
            // Move the end cursor by total number of characters added
            selectionEnd: selectionEnd + tabCharacter.length * (endLine_2 - startLine_2 + 1)
          });
        } else {
          var updatedSelection = selectionStart + tabCharacter.length;
          applyEdits({
            // Insert tab character at caret
            value: value2.substring(0, selectionStart) + tabCharacter + value2.substring(selectionEnd),
            // Update caret position
            selectionStart: updatedSelection,
            selectionEnd: updatedSelection
          });
        }
      } else if (e2.key === "Backspace") {
        var hasSelection = selectionStart !== selectionEnd;
        var textBeforeCaret = value2.substring(0, selectionStart);
        if (textBeforeCaret.endsWith(tabCharacter) && !hasSelection) {
          e2.preventDefault();
          var updatedSelection = selectionStart - tabCharacter.length;
          applyEdits({
            // Remove tab character at caret
            value: value2.substring(0, selectionStart - tabCharacter.length) + value2.substring(selectionEnd),
            // Update caret position
            selectionStart: updatedSelection,
            selectionEnd: updatedSelection
          });
        }
      } else if (e2.key === "Enter") {
        if (selectionStart === selectionEnd) {
          var line = getLines(value2, selectionStart).pop();
          var matches = line === null || line === void 0 ? void 0 : line.match(/^\s+/);
          if (matches === null || matches === void 0 ? void 0 : matches[0]) {
            e2.preventDefault();
            var indent = "\n" + matches[0];
            var updatedSelection = selectionStart + indent.length;
            applyEdits({
              // Insert indentation character at caret
              value: value2.substring(0, selectionStart) + indent + value2.substring(selectionEnd),
              // Update caret position
              selectionStart: updatedSelection,
              selectionEnd: updatedSelection
            });
          }
        }
      } else if (e2.keyCode === KEYCODE_PARENS || e2.keyCode === KEYCODE_BRACKETS || e2.keyCode === KEYCODE_QUOTE || e2.keyCode === KEYCODE_BACK_QUOTE) {
        var chars = void 0;
        if (e2.keyCode === KEYCODE_PARENS && e2.shiftKey) {
          chars = ["(", ")"];
        } else if (e2.keyCode === KEYCODE_BRACKETS) {
          if (e2.shiftKey) {
            chars = ["{", "}"];
          } else {
            chars = ["[", "]"];
          }
        } else if (e2.keyCode === KEYCODE_QUOTE) {
          if (e2.shiftKey) {
            chars = ['"', '"'];
          } else {
            chars = ["'", "'"];
          }
        } else if (e2.keyCode === KEYCODE_BACK_QUOTE && !e2.shiftKey) {
          chars = ["`", "`"];
        }
        if (selectionStart !== selectionEnd && chars) {
          e2.preventDefault();
          applyEdits({
            value: value2.substring(0, selectionStart) + chars[0] + value2.substring(selectionStart, selectionEnd) + chars[1] + value2.substring(selectionEnd),
            // Update caret position
            selectionStart,
            selectionEnd: selectionEnd + 2
          });
        }
      } else if ((isMacLike ? (
        // Trigger undo with ⌘+Z on Mac
        e2.metaKey && e2.keyCode === KEYCODE_Z
      ) : (
        // Trigger undo with Ctrl+Z on other platforms
        e2.ctrlKey && e2.keyCode === KEYCODE_Z
      )) && !e2.shiftKey && !e2.altKey) {
        e2.preventDefault();
        undoEdit();
      } else if ((isMacLike ? (
        // Trigger redo with ⌘+Shift+Z on Mac
        e2.metaKey && e2.keyCode === KEYCODE_Z && e2.shiftKey
      ) : isWindows ? (
        // Trigger redo with Ctrl+Y on Windows
        e2.ctrlKey && e2.keyCode === KEYCODE_Y
      ) : (
        // Trigger redo with Ctrl+Shift+Z on other platforms
        e2.ctrlKey && e2.keyCode === KEYCODE_Z && e2.shiftKey
      )) && !e2.altKey) {
        e2.preventDefault();
        redoEdit();
      } else if (e2.keyCode === KEYCODE_M && e2.ctrlKey && (isMacLike ? e2.shiftKey : true)) {
        e2.preventDefault();
        setCapture(function(prev) {
          return !prev;
        });
      }
    };
    var handleChange = function(e2) {
      var _a3 = e2.currentTarget, value2 = _a3.value, selectionStart = _a3.selectionStart, selectionEnd = _a3.selectionEnd;
      recordChange({
        value: value2,
        selectionStart,
        selectionEnd
      }, true);
      onValueChange(value2);
    };
    React2.useEffect(function() {
      recordCurrentState();
    }, [recordCurrentState]);
    React2.useImperativeHandle(ref2, function() {
      return {
        get session() {
          return {
            history: historyRef.current
          };
        },
        set session(session) {
          historyRef.current = session.history;
        }
      };
    }, []);
    return React2.createElement(
      "div",
      __assign2({}, rest, { style: __assign2(__assign2({}, styles.container), style) }),
      React2.createElement("pre", __assign2({ className: preClassName, "aria-hidden": "true", style: __assign2(__assign2(__assign2({}, styles.editor), styles.highlight), contentStyle) }, typeof highlighted === "string" ? { dangerouslySetInnerHTML: { __html: highlighted + "<br />" } } : { children: highlighted })),
      React2.createElement("textarea", { ref: function(c) {
        return inputRef.current = c;
      }, style: __assign2(__assign2(__assign2({}, styles.editor), styles.textarea), contentStyle), className: className + (textareaClassName ? " ".concat(textareaClassName) : ""), id: textareaId, value, onChange: handleChange, onKeyDown: handleKeyDown, onClick, onKeyUp, onFocus, onBlur, disabled, form, maxLength, minLength, name: name2, placeholder, readOnly, required: required2, autoFocus, autoCapitalize: "off", autoComplete: "off", autoCorrect: "off", spellCheck: false, "data-gramm": false }),
      React2.createElement("style", { dangerouslySetInnerHTML: { __html: cssText } })
    );
  });
  var styles = {
    container: {
      position: "relative",
      textAlign: "left",
      boxSizing: "border-box",
      padding: 0,
      overflow: "hidden"
    },
    textarea: {
      position: "absolute",
      top: 0,
      left: 0,
      height: "100%",
      width: "100%",
      resize: "none",
      color: "inherit",
      overflow: "hidden",
      MozOsxFontSmoothing: "grayscale",
      WebkitFontSmoothing: "antialiased",
      WebkitTextFillColor: "transparent"
    },
    highlight: {
      position: "relative",
      pointerEvents: "none"
    },
    editor: {
      margin: 0,
      border: 0,
      background: "none",
      boxSizing: "inherit",
      display: "inherit",
      fontFamily: "inherit",
      fontSize: "inherit",
      fontStyle: "inherit",
      fontVariantLigatures: "inherit",
      fontWeight: "inherit",
      letterSpacing: "inherit",
      lineHeight: "inherit",
      tabSize: "inherit",
      textIndent: "inherit",
      textRendering: "inherit",
      textTransform: "inherit",
      whiteSpace: "pre-wrap",
      wordBreak: "keep-all",
      overflowWrap: "break-word"
    }
  };
  lib.default = Editor2;
  return lib;
}
var libExports = requireLib();
const Editor = /* @__PURE__ */ getDefaultExportFromCjs(libExports);
var prism = { exports: {} };
var hasRequiredPrism;
function requirePrism() {
  if (hasRequiredPrism) return prism.exports;
  hasRequiredPrism = 1;
  (function(module) {
    var _self = typeof window !== "undefined" ? window : typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope ? self : {};
    var Prism2 = (function(_self2) {
      var lang = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i;
      var uniqueId = 0;
      var plainTextGrammar = {};
      var _2 = {
        /**
         * By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the
         * current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load
         * additional languages or plugins yourself.
         *
         * By setting this value to `true`, Prism will not automatically highlight all code elements on the page.
         *
         * You obviously have to change this value before the automatic highlighting started. To do this, you can add an
         * empty Prism object into the global scope before loading the Prism script like this:
         *
         * ```js
         * window.Prism = window.Prism || {};
         * Prism.manual = true;
         * // add a new <script> to load Prism's script
         * ```
         *
         * @default false
         * @type {boolean}
         * @memberof Prism
         * @public
         */
        manual: _self2.Prism && _self2.Prism.manual,
        /**
         * By default, if Prism is in a web worker, it assumes that it is in a worker it created itself, so it uses
         * `addEventListener` to communicate with its parent instance. However, if you're using Prism manually in your
         * own worker, you don't want it to do this.
         *
         * By setting this value to `true`, Prism will not add its own listeners to the worker.
         *
         * You obviously have to change this value before Prism executes. To do this, you can add an
         * empty Prism object into the global scope before loading the Prism script like this:
         *
         * ```js
         * window.Prism = window.Prism || {};
         * Prism.disableWorkerMessageHandler = true;
         * // Load Prism's script
         * ```
         *
         * @default false
         * @type {boolean}
         * @memberof Prism
         * @public
         */
        disableWorkerMessageHandler: _self2.Prism && _self2.Prism.disableWorkerMessageHandler,
        /**
         * A namespace for utility methods.
         *
         * All function in this namespace that are not explicitly marked as _public_ are for __internal use only__ and may
         * change or disappear at any time.
         *
         * @namespace
         * @memberof Prism
         */
        util: {
          encode: function encode(tokens) {
            if (tokens instanceof Token) {
              return new Token(tokens.type, encode(tokens.content), tokens.alias);
            } else if (Array.isArray(tokens)) {
              return tokens.map(encode);
            } else {
              return tokens.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/\u00a0/g, " ");
            }
          },
          /**
           * Returns the name of the type of the given value.
           *
           * @param {any} o
           * @returns {string}
           * @example
           * type(null)      === 'Null'
           * type(undefined) === 'Undefined'
           * type(123)       === 'Number'
           * type('foo')     === 'String'
           * type(true)      === 'Boolean'
           * type([1, 2])    === 'Array'
           * type({})        === 'Object'
           * type(String)    === 'Function'
           * type(/abc+/)    === 'RegExp'
           */
          type: function(o2) {
            return Object.prototype.toString.call(o2).slice(8, -1);
          },
          /**
           * Returns a unique number for the given object. Later calls will still return the same number.
           *
           * @param {Object} obj
           * @returns {number}
           */
          objId: function(obj) {
            if (!obj["__id"]) {
              Object.defineProperty(obj, "__id", { value: ++uniqueId });
            }
            return obj["__id"];
          },
          /**
           * Creates a deep clone of the given object.
           *
           * The main intended use of this function is to clone language definitions.
           *
           * @param {T} o
           * @param {Record<number, any>} [visited]
           * @returns {T}
           * @template T
           */
          clone: function deepClone(o2, visited) {
            visited = visited || {};
            var clone2;
            var id2;
            switch (_2.util.type(o2)) {
              case "Object":
                id2 = _2.util.objId(o2);
                if (visited[id2]) {
                  return visited[id2];
                }
                clone2 = /** @type {Record<string, any>} */
                {};
                visited[id2] = clone2;
                for (var key in o2) {
                  if (o2.hasOwnProperty(key)) {
                    clone2[key] = deepClone(o2[key], visited);
                  }
                }
                return (
                  /** @type {any} */
                  clone2
                );
              case "Array":
                id2 = _2.util.objId(o2);
                if (visited[id2]) {
                  return visited[id2];
                }
                clone2 = [];
                visited[id2] = clone2;
                /** @type {Array} */
                /** @type {any} */
                o2.forEach(function(v2, i2) {
                  clone2[i2] = deepClone(v2, visited);
                });
                return (
                  /** @type {any} */
                  clone2
                );
              default:
                return o2;
            }
          },
          /**
           * Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class.
           *
           * If no language is set for the element or the element is `null` or `undefined`, `none` will be returned.
           *
           * @param {Element} element
           * @returns {string}
           */
          getLanguage: function(element) {
            while (element) {
              var m2 = lang.exec(element.className);
              if (m2) {
                return m2[1].toLowerCase();
              }
              element = element.parentElement;
            }
            return "none";
          },
          /**
           * Sets the Prism `language-xxxx` class of the given element.
           *
           * @param {Element} element
           * @param {string} language
           * @returns {void}
           */
          setLanguage: function(element, language) {
            element.className = element.className.replace(RegExp(lang, "gi"), "");
            element.classList.add("language-" + language);
          },
          /**
           * Returns the script element that is currently executing.
           *
           * This does __not__ work for line script element.
           *
           * @returns {HTMLScriptElement | null}
           */
          currentScript: function() {
            if (typeof document === "undefined") {
              return null;
            }
            if (document.currentScript && document.currentScript.tagName === "SCRIPT" && 1 < 2) {
              return (
                /** @type {any} */
                document.currentScript
              );
            }
            try {
              throw new Error();
            } catch (err) {
              var src = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(err.stack) || [])[1];
              if (src) {
                var scripts = document.getElementsByTagName("script");
                for (var i2 in scripts) {
                  if (scripts[i2].src == src) {
                    return scripts[i2];
                  }
                }
              }
              return null;
            }
          },
          /**
           * Returns whether a given class is active for `element`.
           *
           * The class can be activated if `element` or one of its ancestors has the given class and it can be deactivated
           * if `element` or one of its ancestors has the negated version of the given class. The _negated version_ of the
           * given class is just the given class with a `no-` prefix.
           *
           * Whether the class is active is determined by the closest ancestor of `element` (where `element` itself is
           * closest ancestor) that has the given class or the negated version of it. If neither `element` nor any of its
           * ancestors have the given class or the negated version of it, then the default activation will be returned.
           *
           * In the paradoxical situation where the closest ancestor contains __both__ the given class and the negated
           * version of it, the class is considered active.
           *
           * @param {Element} element
           * @param {string} className
           * @param {boolean} [defaultActivation=false]
           * @returns {boolean}
           */
          isActive: function(element, className, defaultActivation) {
            var no2 = "no-" + className;
            while (element) {
              var classList = element.classList;
              if (classList.contains(className)) {
                return true;
              }
              if (classList.contains(no2)) {
                return false;
              }
              element = element.parentElement;
            }
            return !!defaultActivation;
          }
        },
        /**
         * This namespace contains all currently loaded languages and the some helper functions to create and modify languages.
         *
         * @namespace
         * @memberof Prism
         * @public
         */
        languages: {
          /**
           * The grammar for plain, unformatted text.
           */
          plain: plainTextGrammar,
          plaintext: plainTextGrammar,
          text: plainTextGrammar,
          txt: plainTextGrammar,
          /**
           * Creates a deep copy of the language with the given id and appends the given tokens.
           *
           * If a token in `redef` also appears in the copied language, then the existing token in the copied language
           * will be overwritten at its original position.
           *
           * ## Best practices
           *
           * Since the position of overwriting tokens (token in `redef` that overwrite tokens in the copied language)
           * doesn't matter, they can technically be in any order. However, this can be confusing to others that trying to
           * understand the language definition because, normally, the order of tokens matters in Prism grammars.
           *
           * Therefore, it is encouraged to order overwriting tokens according to the positions of the overwritten tokens.
           * Furthermore, all non-overwriting tokens should be placed after the overwriting ones.
           *
           * @param {string} id The id of the language to extend. This has to be a key in `Prism.languages`.
           * @param {Grammar} redef The new tokens to append.
           * @returns {Grammar} The new language created.
           * @public
           * @example
           * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
           *     // Prism.languages.css already has a 'comment' token, so this token will overwrite CSS' 'comment' token
           *     // at its original position
           *     'comment': { ... },
           *     // CSS doesn't have a 'color' token, so this token will be appended
           *     'color': /\b(?:red|green|blue)\b/
           * });
           */
          extend: function(id2, redef) {
            var lang2 = _2.util.clone(_2.languages[id2]);
            for (var key in redef) {
              lang2[key] = redef[key];
            }
            return lang2;
          },
          /**
           * Inserts tokens _before_ another token in a language definition or any other grammar.
           *
           * ## Usage
           *
           * This helper method makes it easy to modify existing languages. For example, the CSS language definition
           * not only defines CSS highlighting for CSS documents, but also needs to define highlighting for CSS embedded
           * in HTML through `<style>` elements. To do this, it needs to modify `Prism.languages.markup` and add the
           * appropriate tokens. However, `Prism.languages.markup` is a regular JavaScript object literal, so if you do
           * this:
           *
           * ```js
           * Prism.languages.markup.style = {
           *     // token
           * };
           * ```
           *
           * then the `style` token will be added (and processed) at the end. `insertBefore` allows you to insert tokens
           * before existing tokens. For the CSS example above, you would use it like this:
           *
           * ```js
           * Prism.languages.insertBefore('markup', 'cdata', {
           *     'style': {
           *         // token
           *     }
           * });
           * ```
           *
           * ## Special cases
           *
           * If the grammars of `inside` and `insert` have tokens with the same name, the tokens in `inside`'s grammar
           * will be ignored.
           *
           * This behavior can be used to insert tokens after `before`:
           *
           * ```js
           * Prism.languages.insertBefore('markup', 'comment', {
           *     'comment': Prism.languages.markup.comment,
           *     // tokens after 'comment'
           * });
           * ```
           *
           * ## Limitations
           *
           * The main problem `insertBefore` has to solve is iteration order. Since ES2015, the iteration order for object
           * properties is guaranteed to be the insertion order (except for integer keys) but some browsers behave
           * differently when keys are deleted and re-inserted. So `insertBefore` can't be implemented by temporarily
           * deleting properties which is necessary to insert at arbitrary positions.
           *
           * To solve this problem, `insertBefore` doesn't actually insert the given tokens into the target object.
           * Instead, it will create a new object and replace all references to the target object with the new one. This
           * can be done without temporarily deleting properties, so the iteration order is well-defined.
           *
           * However, only references that can be reached from `Prism.languages` or `insert` will be replaced. I.e. if
           * you hold the target object in a variable, then the value of the variable will not change.
           *
           * ```js
           * var oldMarkup = Prism.languages.markup;
           * var newMarkup = Prism.languages.insertBefore('markup', 'comment', { ... });
           *
           * assert(oldMarkup !== Prism.languages.markup);
           * assert(newMarkup === Prism.languages.markup);
           * ```
           *
           * @param {string} inside The property of `root` (e.g. a language id in `Prism.languages`) that contains the
           * object to be modified.
           * @param {string} before The key to insert before.
           * @param {Grammar} insert An object containing the key-value pairs to be inserted.
           * @param {Object<string, any>} [root] The object containing `inside`, i.e. the object that contains the
           * object to be modified.
           *
           * Defaults to `Prism.languages`.
           * @returns {Grammar} The new grammar object.
           * @public
           */
          insertBefore: function(inside, before, insert, root) {
            root = root || /** @type {any} */
            _2.languages;
            var grammar = root[inside];
            var ret = {};
            for (var token in grammar) {
              if (grammar.hasOwnProperty(token)) {
                if (token == before) {
                  for (var newToken in insert) {
                    if (insert.hasOwnProperty(newToken)) {
                      ret[newToken] = insert[newToken];
                    }
                  }
                }
                if (!insert.hasOwnProperty(token)) {
                  ret[token] = grammar[token];
                }
              }
            }
            var old = root[inside];
            root[inside] = ret;
            _2.languages.DFS(_2.languages, function(key, value) {
              if (value === old && key != inside) {
                this[key] = ret;
              }
            });
            return ret;
          },
          // Traverse a language definition with Depth First Search
          DFS: function DFS(o2, callback, type2, visited) {
            visited = visited || {};
            var objId = _2.util.objId;
            for (var i2 in o2) {
              if (o2.hasOwnProperty(i2)) {
                callback.call(o2, i2, o2[i2], type2 || i2);
                var property = o2[i2];
                var propertyType = _2.util.type(property);
                if (propertyType === "Object" && !visited[objId(property)]) {
                  visited[objId(property)] = true;
                  DFS(property, callback, null, visited);
                } else if (propertyType === "Array" && !visited[objId(property)]) {
                  visited[objId(property)] = true;
                  DFS(property, callback, i2, visited);
                }
              }
            }
          }
        },
        plugins: {},
        /**
         * This is the most high-level function in Prism’s API.
         * It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
         * each one of them.
         *
         * This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
         *
         * @param {boolean} [async=false] Same as in {@link Prism.highlightAllUnder}.
         * @param {HighlightCallback} [callback] Same as in {@link Prism.highlightAllUnder}.
         * @memberof Prism
         * @public
         */
        highlightAll: function(async2, callback) {
          _2.highlightAllUnder(document, async2, callback);
        },
        /**
         * Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
         * {@link Prism.highlightElement} on each one of them.
         *
         * The following hooks will be run:
         * 1. `before-highlightall`
         * 2. `before-all-elements-highlight`
         * 3. All hooks of {@link Prism.highlightElement} for each element.
         *
         * @param {ParentNode} container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
         * @param {boolean} [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
         * @param {HighlightCallback} [callback] An optional callback to be invoked on each element after its highlighting is done.
         * @memberof Prism
         * @public
         */
        highlightAllUnder: function(container, async2, callback) {
          var env = {
            callback,
            container,
            selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
          };
          _2.hooks.run("before-highlightall", env);
          env.elements = Array.prototype.slice.apply(env.container.querySelectorAll(env.selector));
          _2.hooks.run("before-all-elements-highlight", env);
          for (var i2 = 0, element; element = env.elements[i2++]; ) {
            _2.highlightElement(element, async2 === true, env.callback);
          }
        },
        /**
         * Highlights the code inside a single element.
         *
         * The following hooks will be run:
         * 1. `before-sanity-check`
         * 2. `before-highlight`
         * 3. All hooks of {@link Prism.highlight}. These hooks will be run by an asynchronous worker if `async` is `true`.
         * 4. `before-insert`
         * 5. `after-highlight`
         * 6. `complete`
         *
         * Some the above hooks will be skipped if the element doesn't contain any text or there is no grammar loaded for
         * the element's language.
         *
         * @param {Element} element The element containing the code.
         * It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
         * @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers
         * to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
         * [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
         *
         * Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
         * asynchronous highlighting to work. You can build your own bundle on the
         * [Download page](https://prismjs.com/download.html).
         * @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done.
         * Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
         * @memberof Prism
         * @public
         */
        highlightElement: function(element, async2, callback) {
          var language = _2.util.getLanguage(element);
          var grammar = _2.languages[language];
          _2.util.setLanguage(element, language);
          var parent = element.parentElement;
          if (parent && parent.nodeName.toLowerCase() === "pre") {
            _2.util.setLanguage(parent, language);
          }
          var code2 = element.textContent;
          var env = {
            element,
            language,
            grammar,
            code: code2
          };
          function insertHighlightedCode(highlightedCode) {
            env.highlightedCode = highlightedCode;
            _2.hooks.run("before-insert", env);
            env.element.innerHTML = env.highlightedCode;
            _2.hooks.run("after-highlight", env);
            _2.hooks.run("complete", env);
            callback && callback.call(env.element);
          }
          _2.hooks.run("before-sanity-check", env);
          parent = env.element.parentElement;
          if (parent && parent.nodeName.toLowerCase() === "pre" && !parent.hasAttribute("tabindex")) {
            parent.setAttribute("tabindex", "0");
          }
          if (!env.code) {
            _2.hooks.run("complete", env);
            callback && callback.call(env.element);
            return;
          }
          _2.hooks.run("before-highlight", env);
          if (!env.grammar) {
            insertHighlightedCode(_2.util.encode(env.code));
            return;
          }
          if (async2 && _self2.Worker) {
            var worker = new Worker(_2.filename);
            worker.onmessage = function(evt) {
              insertHighlightedCode(evt.data);
            };
            worker.postMessage(JSON.stringify({
              language: env.language,
              code: env.code,
              immediateClose: true
            }));
          } else {
            insertHighlightedCode(_2.highlight(env.code, env.grammar, env.language));
          }
        },
        /**
         * Low-level function, only use if you know what you’re doing. It accepts a string of text as input
         * and the language definitions to use, and returns a string with the HTML produced.
         *
         * The following hooks will be run:
         * 1. `before-tokenize`
         * 2. `after-tokenize`
         * 3. `wrap`: On each {@link Token}.
         *
         * @param {string} text A string with the code to be highlighted.
         * @param {Grammar} grammar An object containing the tokens to use.
         *
         * Usually a language definition like `Prism.languages.markup`.
         * @param {string} language The name of the language definition passed to `grammar`.
         * @returns {string} The highlighted HTML.
         * @memberof Prism
         * @public
         * @example
         * Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
         */
        highlight: function(text, grammar, language) {
          var env = {
            code: text,
            grammar,
            language
          };
          _2.hooks.run("before-tokenize", env);
          if (!env.grammar) {
            throw new Error('The language "' + env.language + '" has no grammar.');
          }
          env.tokens = _2.tokenize(env.code, env.grammar);
          _2.hooks.run("after-tokenize", env);
          return Token.stringify(_2.util.encode(env.tokens), env.language);
        },
        /**
         * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
         * and the language definitions to use, and returns an array with the tokenized code.
         *
         * When the language definition includes nested tokens, the function is called recursively on each of these tokens.
         *
         * This method could be useful in other contexts as well, as a very crude parser.
         *
         * @param {string} text A string with the code to be highlighted.
         * @param {Grammar} grammar An object containing the tokens to use.
         *
         * Usually a language definition like `Prism.languages.markup`.
         * @returns {TokenStream} An array of strings and tokens, a token stream.
         * @memberof Prism
         * @public
         * @example
         * let code = `var foo = 0;`;
         * let tokens = Prism.tokenize(code, Prism.languages.javascript);
         * tokens.forEach(token => {
         *     if (token instanceof Prism.Token && token.type === 'number') {
         *         console.log(`Found numeric literal: ${token.content}`);
         *     }
         * });
         */
        tokenize: function(text, grammar) {
          var rest = grammar.rest;
          if (rest) {
            for (var token in rest) {
              grammar[token] = rest[token];
            }
            delete grammar.rest;
          }
          var tokenList = new LinkedList();
          addAfter(tokenList, tokenList.head, text);
          matchGrammar(text, tokenList, grammar, tokenList.head, 0);
          return toArray(tokenList);
        },
        /**
         * @namespace
         * @memberof Prism
         * @public
         */
        hooks: {
          all: {},
          /**
           * Adds the given callback to the list of callbacks for the given hook.
           *
           * The callback will be invoked when the hook it is registered for is run.
           * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
           *
           * One callback function can be registered to multiple hooks and the same hook multiple times.
           *
           * @param {string} name The name of the hook.
           * @param {HookCallback} callback The callback function which is given environment variables.
           * @public
           */
          add: function(name2, callback) {
            var hooks = _2.hooks.all;
            hooks[name2] = hooks[name2] || [];
            hooks[name2].push(callback);
          },
          /**
           * Runs a hook invoking all registered callbacks with the given environment variables.
           *
           * Callbacks will be invoked synchronously and in the order in which they were registered.
           *
           * @param {string} name The name of the hook.
           * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
           * @public
           */
          run: function(name2, env) {
            var callbacks = _2.hooks.all[name2];
            if (!callbacks || !callbacks.length) {
              return;
            }
            for (var i2 = 0, callback; callback = callbacks[i2++]; ) {
              callback(env);
            }
          }
        },
        Token
      };
      _self2.Prism = _2;
      function Token(type2, content, alias, matchedStr) {
        this.type = type2;
        this.content = content;
        this.alias = alias;
        this.length = (matchedStr || "").length | 0;
      }
      Token.stringify = function stringify(o2, language) {
        if (typeof o2 == "string") {
          return o2;
        }
        if (Array.isArray(o2)) {
          var s2 = "";
          o2.forEach(function(e2) {
            s2 += stringify(e2, language);
          });
          return s2;
        }
        var env = {
          type: o2.type,
          content: stringify(o2.content, language),
          tag: "span",
          classes: ["token", o2.type],
          attributes: {},
          language
        };
        var aliases = o2.alias;
        if (aliases) {
          if (Array.isArray(aliases)) {
            Array.prototype.push.apply(env.classes, aliases);
          } else {
            env.classes.push(aliases);
          }
        }
        _2.hooks.run("wrap", env);
        var attributes = "";
        for (var name2 in env.attributes) {
          attributes += " " + name2 + '="' + (env.attributes[name2] || "").replace(/"/g, "&quot;") + '"';
        }
        return "<" + env.tag + ' class="' + env.classes.join(" ") + '"' + attributes + ">" + env.content + "</" + env.tag + ">";
      };
      function matchPattern(pattern2, pos, text, lookbehind) {
        pattern2.lastIndex = pos;
        var match = pattern2.exec(text);
        if (match && lookbehind && match[1]) {
          var lookbehindLength = match[1].length;
          match.index += lookbehindLength;
          match[0] = match[0].slice(lookbehindLength);
        }
        return match;
      }
      function matchGrammar(text, tokenList, grammar, startNode, startPos, rematch) {
        for (var token in grammar) {
          if (!grammar.hasOwnProperty(token) || !grammar[token]) {
            continue;
          }
          var patterns = grammar[token];
          patterns = Array.isArray(patterns) ? patterns : [patterns];
          for (var j = 0; j < patterns.length; ++j) {
            if (rematch && rematch.cause == token + "," + j) {
              return;
            }
            var patternObj = patterns[j];
            var inside = patternObj.inside;
            var lookbehind = !!patternObj.lookbehind;
            var greedy = !!patternObj.greedy;
            var alias = patternObj.alias;
            if (greedy && !patternObj.pattern.global) {
              var flags = patternObj.pattern.toString().match(/[imsuy]*$/)[0];
              patternObj.pattern = RegExp(patternObj.pattern.source, flags + "g");
            }
            var pattern2 = patternObj.pattern || patternObj;
            for (var currentNode = startNode.next, pos = startPos; currentNode !== tokenList.tail; pos += currentNode.value.length, currentNode = currentNode.next) {
              if (rematch && pos >= rematch.reach) {
                break;
              }
              var str = currentNode.value;
              if (tokenList.length > text.length) {
                return;
              }
              if (str instanceof Token) {
                continue;
              }
              var removeCount = 1;
              var match;
              if (greedy) {
                match = matchPattern(pattern2, pos, text, lookbehind);
                if (!match || match.index >= text.length) {
                  break;
                }
                var from = match.index;
                var to2 = match.index + match[0].length;
                var p2 = pos;
                p2 += currentNode.value.length;
                while (from >= p2) {
                  currentNode = currentNode.next;
                  p2 += currentNode.value.length;
                }
                p2 -= currentNode.value.length;
                pos = p2;
                if (currentNode.value instanceof Token) {
                  continue;
                }
                for (var k2 = currentNode; k2 !== tokenList.tail && (p2 < to2 || typeof k2.value === "string"); k2 = k2.next) {
                  removeCount++;
                  p2 += k2.value.length;
                }
                removeCount--;
                str = text.slice(pos, p2);
                match.index -= pos;
              } else {
                match = matchPattern(pattern2, 0, str, lookbehind);
                if (!match) {
                  continue;
                }
              }
              var from = match.index;
              var matchStr = match[0];
              var before = str.slice(0, from);
              var after = str.slice(from + matchStr.length);
              var reach = pos + str.length;
              if (rematch && reach > rematch.reach) {
                rematch.reach = reach;
              }
              var removeFrom = currentNode.prev;
              if (before) {
                removeFrom = addAfter(tokenList, removeFrom, before);
                pos += before.length;
              }
              removeRange(tokenList, removeFrom, removeCount);
              var wrapped = new Token(token, inside ? _2.tokenize(matchStr, inside) : matchStr, alias, matchStr);
              currentNode = addAfter(tokenList, removeFrom, wrapped);
              if (after) {
                addAfter(tokenList, currentNode, after);
              }
              if (removeCount > 1) {
                var nestedRematch = {
                  cause: token + "," + j,
                  reach
                };
                matchGrammar(text, tokenList, grammar, currentNode.prev, pos, nestedRematch);
                if (rematch && nestedRematch.reach > rematch.reach) {
                  rematch.reach = nestedRematch.reach;
                }
              }
            }
          }
        }
      }
      function LinkedList() {
        var head = { value: null, prev: null, next: null };
        var tail = { value: null, prev: head, next: null };
        head.next = tail;
        this.head = head;
        this.tail = tail;
        this.length = 0;
      }
      function addAfter(list, node, value) {
        var next = node.next;
        var newNode = { value, prev: node, next };
        node.next = newNode;
        next.prev = newNode;
        list.length++;
        return newNode;
      }
      function removeRange(list, node, count2) {
        var next = node.next;
        for (var i2 = 0; i2 < count2 && next !== list.tail; i2++) {
          next = next.next;
        }
        node.next = next;
        next.prev = node;
        list.length -= i2;
      }
      function toArray(list) {
        var array2 = [];
        var node = list.head.next;
        while (node !== list.tail) {
          array2.push(node.value);
          node = node.next;
        }
        return array2;
      }
      if (!_self2.document) {
        if (!_self2.addEventListener) {
          return _2;
        }
        if (!_2.disableWorkerMessageHandler) {
          _self2.addEventListener("message", function(evt) {
            var message = JSON.parse(evt.data);
            var lang2 = message.language;
            var code2 = message.code;
            var immediateClose = message.immediateClose;
            _self2.postMessage(_2.highlight(code2, _2.languages[lang2], lang2));
            if (immediateClose) {
              _self2.close();
            }
          }, false);
        }
        return _2;
      }
      var script = _2.util.currentScript();
      if (script) {
        _2.filename = script.src;
        if (script.hasAttribute("data-manual")) {
          _2.manual = true;
        }
      }
      function highlightAutomaticallyCallback() {
        if (!_2.manual) {
          _2.highlightAll();
        }
      }
      if (!_2.manual) {
        var readyState = document.readyState;
        if (readyState === "loading" || readyState === "interactive" && script && script.defer) {
          document.addEventListener("DOMContentLoaded", highlightAutomaticallyCallback);
        } else {
          if (window.requestAnimationFrame) {
            window.requestAnimationFrame(highlightAutomaticallyCallback);
          } else {
            window.setTimeout(highlightAutomaticallyCallback, 16);
          }
        }
      }
      return _2;
    })(_self);
    if (module.exports) {
      module.exports = Prism2;
    }
    if (typeof commonjsGlobal !== "undefined") {
      commonjsGlobal.Prism = Prism2;
    }
    Prism2.languages.markup = {
      "comment": {
        pattern: /<!--(?:(?!<!--)[\s\S])*?-->/,
        greedy: true
      },
      "prolog": {
        pattern: /<\?[\s\S]+?\?>/,
        greedy: true
      },
      "doctype": {
        // https://www.w3.org/TR/xml/#NT-doctypedecl
        pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
        greedy: true,
        inside: {
          "internal-subset": {
            pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
            lookbehind: true,
            greedy: true,
            inside: null
            // see below
          },
          "string": {
            pattern: /"[^"]*"|'[^']*'/,
            greedy: true
          },
          "punctuation": /^<!|>$|[[\]]/,
          "doctype-tag": /^DOCTYPE/i,
          "name": /[^\s<>'"]+/
        }
      },
      "cdata": {
        pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
        greedy: true
      },
      "tag": {
        pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
        greedy: true,
        inside: {
          "tag": {
            pattern: /^<\/?[^\s>\/]+/,
            inside: {
              "punctuation": /^<\/?/,
              "namespace": /^[^\s>\/:]+:/
            }
          },
          "special-attr": [],
          "attr-value": {
            pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
            inside: {
              "punctuation": [
                {
                  pattern: /^=/,
                  alias: "attr-equals"
                },
                {
                  pattern: /^(\s*)["']|["']$/,
                  lookbehind: true
                }
              ]
            }
          },
          "punctuation": /\/?>/,
          "attr-name": {
            pattern: /[^\s>\/]+/,
            inside: {
              "namespace": /^[^\s>\/:]+:/
            }
          }
        }
      },
      "entity": [
        {
          pattern: /&[\da-z]{1,8};/i,
          alias: "named-entity"
        },
        /&#x?[\da-f]{1,8};/i
      ]
    };
    Prism2.languages.markup["tag"].inside["attr-value"].inside["entity"] = Prism2.languages.markup["entity"];
    Prism2.languages.markup["doctype"].inside["internal-subset"].inside = Prism2.languages.markup;
    Prism2.hooks.add("wrap", function(env) {
      if (env.type === "entity") {
        env.attributes["title"] = env.content.replace(/&amp;/, "&");
      }
    });
    Object.defineProperty(Prism2.languages.markup.tag, "addInlined", {
      /**
       * Adds an inlined language to markup.
       *
       * An example of an inlined language is CSS with `<style>` tags.
       *
       * @param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
       * case insensitive.
       * @param {string} lang The language key.
       * @example
       * addInlined('style', 'css');
       */
      value: function addInlined(tagName, lang) {
        var includedCdataInside = {};
        includedCdataInside["language-" + lang] = {
          pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
          lookbehind: true,
          inside: Prism2.languages[lang]
        };
        includedCdataInside["cdata"] = /^<!\[CDATA\[|\]\]>$/i;
        var inside = {
          "included-cdata": {
            pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
            inside: includedCdataInside
          }
        };
        inside["language-" + lang] = {
          pattern: /[\s\S]+/,
          inside: Prism2.languages[lang]
        };
        var def = {};
        def[tagName] = {
          pattern: RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g, function() {
            return tagName;
          }), "i"),
          lookbehind: true,
          greedy: true,
          inside
        };
        Prism2.languages.insertBefore("markup", "cdata", def);
      }
    });
    Object.defineProperty(Prism2.languages.markup.tag, "addAttribute", {
      /**
       * Adds an pattern to highlight languages embedded in HTML attributes.
       *
       * An example of an inlined language is CSS with `style` attributes.
       *
       * @param {string} attrName The name of the tag that contains the inlined language. This name will be treated as
       * case insensitive.
       * @param {string} lang The language key.
       * @example
       * addAttribute('style', 'css');
       */
      value: function(attrName, lang) {
        Prism2.languages.markup.tag.inside["special-attr"].push({
          pattern: RegExp(
            /(^|["'\s])/.source + "(?:" + attrName + ")" + /\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,
            "i"
          ),
          lookbehind: true,
          inside: {
            "attr-name": /^[^\s=]+/,
            "attr-value": {
              pattern: /=[\s\S]+/,
              inside: {
                "value": {
                  pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
                  lookbehind: true,
                  alias: [lang, "language-" + lang],
                  inside: Prism2.languages[lang]
                },
                "punctuation": [
                  {
                    pattern: /^=/,
                    alias: "attr-equals"
                  },
                  /"|'/
                ]
              }
            }
          }
        });
      }
    });
    Prism2.languages.html = Prism2.languages.markup;
    Prism2.languages.mathml = Prism2.languages.markup;
    Prism2.languages.svg = Prism2.languages.markup;
    Prism2.languages.xml = Prism2.languages.extend("markup", {});
    Prism2.languages.ssml = Prism2.languages.xml;
    Prism2.languages.atom = Prism2.languages.xml;
    Prism2.languages.rss = Prism2.languages.xml;
    (function(Prism3) {
      var string2 = /(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
      Prism3.languages.css = {
        "comment": /\/\*[\s\S]*?\*\//,
        "atrule": {
          pattern: RegExp("@[\\w-](?:" + /[^;{\s"']|\s+(?!\s)/.source + "|" + string2.source + ")*?" + /(?:;|(?=\s*\{))/.source),
          inside: {
            "rule": /^@[\w-]+/,
            "selector-function-argument": {
              pattern: /(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
              lookbehind: true,
              alias: "selector"
            },
            "keyword": {
              pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
              lookbehind: true
            }
            // See rest below
          }
        },
        "url": {
          // https://drafts.csswg.org/css-values-3/#urls
          pattern: RegExp("\\burl\\((?:" + string2.source + "|" + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ")\\)", "i"),
          greedy: true,
          inside: {
            "function": /^url/i,
            "punctuation": /^\(|\)$/,
            "string": {
              pattern: RegExp("^" + string2.source + "$"),
              alias: "url"
            }
          }
        },
        "selector": {
          pattern: RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|` + string2.source + ")*(?=\\s*\\{)"),
          lookbehind: true
        },
        "string": {
          pattern: string2,
          greedy: true
        },
        "property": {
          pattern: /(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
          lookbehind: true
        },
        "important": /!important\b/i,
        "function": {
          pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,
          lookbehind: true
        },
        "punctuation": /[(){};:,]/
      };
      Prism3.languages.css["atrule"].inside.rest = Prism3.languages.css;
      var markup = Prism3.languages.markup;
      if (markup) {
        markup.tag.addInlined("style", "css");
        markup.tag.addAttribute("style", "css");
      }
    })(Prism2);
    Prism2.languages.clike = {
      "comment": [
        {
          pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
          lookbehind: true,
          greedy: true
        },
        {
          pattern: /(^|[^\\:])\/\/.*/,
          lookbehind: true,
          greedy: true
        }
      ],
      "string": {
        pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
        greedy: true
      },
      "class-name": {
        pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
        lookbehind: true,
        inside: {
          "punctuation": /[.\\]/
        }
      },
      "keyword": /\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
      "boolean": /\b(?:false|true)\b/,
      "function": /\b\w+(?=\()/,
      "number": /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
      "operator": /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
      "punctuation": /[{}[\];(),.:]/
    };
    Prism2.languages.javascript = Prism2.languages.extend("clike", {
      "class-name": [
        Prism2.languages.clike["class-name"],
        {
          pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
          lookbehind: true
        }
      ],
      "keyword": [
        {
          pattern: /((?:^|\})\s*)catch\b/,
          lookbehind: true
        },
        {
          pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
          lookbehind: true
        }
      ],
      // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
      "function": /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
      "number": {
        pattern: RegExp(
          /(^|[^\w$])/.source + "(?:" + // constant
          (/NaN|Infinity/.source + "|" + // binary integer
          /0[bB][01]+(?:_[01]+)*n?/.source + "|" + // octal integer
          /0[oO][0-7]+(?:_[0-7]+)*n?/.source + "|" + // hexadecimal integer
          /0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source + "|" + // decimal bigint
          /\d+(?:_\d+)*n/.source + "|" + // decimal number (integer or float) but no bigint
          /(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source) + ")" + /(?![\w$])/.source
        ),
        lookbehind: true
      },
      "operator": /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
    });
    Prism2.languages.javascript["class-name"][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;
    Prism2.languages.insertBefore("javascript", "keyword", {
      "regex": {
        pattern: RegExp(
          // lookbehind
          // eslint-disable-next-line regexp/no-dupe-characters-character-class
          /((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source + // Regex pattern:
          // There are 2 regex patterns here. The RegExp set notation proposal added support for nested character
          // classes if the `v` flag is present. Unfortunately, nested CCs are both context-free and incompatible
          // with the only syntax, so we have to define 2 different regex patterns.
          /\//.source + "(?:" + /(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source + "|" + // `v` flag syntax. This supports 3 levels of nested character classes.
          /(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source + ")" + // lookahead
          /(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source
        ),
        lookbehind: true,
        greedy: true,
        inside: {
          "regex-source": {
            pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
            lookbehind: true,
            alias: "language-regex",
            inside: Prism2.languages.regex
          },
          "regex-delimiter": /^\/|\/$/,
          "regex-flags": /^[a-z]+$/
        }
      },
      // This must be declared before keyword because we use "function" inside the look-forward
      "function-variable": {
        pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,
        alias: "function"
      },
      "parameter": [
        {
          pattern: /(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
          lookbehind: true,
          inside: Prism2.languages.javascript
        },
        {
          pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
          lookbehind: true,
          inside: Prism2.languages.javascript
        },
        {
          pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
          lookbehind: true,
          inside: Prism2.languages.javascript
        },
        {
          pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,
          lookbehind: true,
          inside: Prism2.languages.javascript
        }
      ],
      "constant": /\b[A-Z](?:[A-Z_]|\dx?)*\b/
    });
    Prism2.languages.insertBefore("javascript", "string", {
      "hashbang": {
        pattern: /^#!.*/,
        greedy: true,
        alias: "comment"
      },
      "template-string": {
        pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
        greedy: true,
        inside: {
          "template-punctuation": {
            pattern: /^`|`$/,
            alias: "string"
          },
          "interpolation": {
            pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
            lookbehind: true,
            inside: {
              "interpolation-punctuation": {
                pattern: /^\$\{|\}$/,
                alias: "punctuation"
              },
              rest: Prism2.languages.javascript
            }
          },
          "string": /[\s\S]+/
        }
      },
      "string-property": {
        pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
        lookbehind: true,
        greedy: true,
        alias: "property"
      }
    });
    Prism2.languages.insertBefore("javascript", "operator", {
      "literal-property": {
        pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
        lookbehind: true,
        alias: "property"
      }
    });
    if (Prism2.languages.markup) {
      Prism2.languages.markup.tag.addInlined("script", "javascript");
      Prism2.languages.markup.tag.addAttribute(
        /on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,
        "javascript"
      );
    }
    Prism2.languages.js = Prism2.languages.javascript;
    (function() {
      if (typeof Prism2 === "undefined" || typeof document === "undefined") {
        return;
      }
      if (!Element.prototype.matches) {
        Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
      }
      var LOADING_MESSAGE = "Loading…";
      var FAILURE_MESSAGE = function(status, message) {
        return "✖ Error " + status + " while fetching file: " + message;
      };
      var FAILURE_EMPTY_MESSAGE = "✖ Error: File does not exist or is empty";
      var EXTENSIONS = {
        "js": "javascript",
        "py": "python",
        "rb": "ruby",
        "ps1": "powershell",
        "psm1": "powershell",
        "sh": "bash",
        "bat": "batch",
        "h": "c",
        "tex": "latex"
      };
      var STATUS_ATTR = "data-src-status";
      var STATUS_LOADING = "loading";
      var STATUS_LOADED = "loaded";
      var STATUS_FAILED = "failed";
      var SELECTOR = "pre[data-src]:not([" + STATUS_ATTR + '="' + STATUS_LOADED + '"]):not([' + STATUS_ATTR + '="' + STATUS_LOADING + '"])';
      function loadFile(src, success, error) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", src, true);
        xhr.onreadystatechange = function() {
          if (xhr.readyState == 4) {
            if (xhr.status < 400 && xhr.responseText) {
              success(xhr.responseText);
            } else {
              if (xhr.status >= 400) {
                error(FAILURE_MESSAGE(xhr.status, xhr.statusText));
              } else {
                error(FAILURE_EMPTY_MESSAGE);
              }
            }
          }
        };
        xhr.send(null);
      }
      function parseRange(range) {
        var m2 = /^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(range || "");
        if (m2) {
          var start = Number(m2[1]);
          var comma = m2[2];
          var end = m2[3];
          if (!comma) {
            return [start, start];
          }
          if (!end) {
            return [start, void 0];
          }
          return [start, Number(end)];
        }
        return void 0;
      }
      Prism2.hooks.add("before-highlightall", function(env) {
        env.selector += ", " + SELECTOR;
      });
      Prism2.hooks.add("before-sanity-check", function(env) {
        var pre = (
          /** @type {HTMLPreElement} */
          env.element
        );
        if (pre.matches(SELECTOR)) {
          env.code = "";
          pre.setAttribute(STATUS_ATTR, STATUS_LOADING);
          var code2 = pre.appendChild(document.createElement("CODE"));
          code2.textContent = LOADING_MESSAGE;
          var src = pre.getAttribute("data-src");
          var language = env.language;
          if (language === "none") {
            var extension = (/\.(\w+)$/.exec(src) || [, "none"])[1];
            language = EXTENSIONS[extension] || extension;
          }
          Prism2.util.setLanguage(code2, language);
          Prism2.util.setLanguage(pre, language);
          var autoloader = Prism2.plugins.autoloader;
          if (autoloader) {
            autoloader.loadLanguages(language);
          }
          loadFile(
            src,
            function(text) {
              pre.setAttribute(STATUS_ATTR, STATUS_LOADED);
              var range = parseRange(pre.getAttribute("data-range"));
              if (range) {
                var lines = text.split(/\r\n?|\n/g);
                var start = range[0];
                var end = range[1] == null ? lines.length : range[1];
                if (start < 0) {
                  start += lines.length;
                }
                start = Math.max(0, Math.min(start - 1, lines.length));
                if (end < 0) {
                  end += lines.length;
                }
                end = Math.max(0, Math.min(end, lines.length));
                text = lines.slice(start, end).join("\n");
                if (!pre.hasAttribute("data-start")) {
                  pre.setAttribute("data-start", String(start + 1));
                }
              }
              code2.textContent = text;
              Prism2.highlightElement(code2);
            },
            function(error) {
              pre.setAttribute(STATUS_ATTR, STATUS_FAILED);
              code2.textContent = error;
            }
          );
        }
      });
      Prism2.plugins.fileHighlight = {
        /**
         * Executes the File Highlight plugin for all matching `pre` elements under the given container.
         *
         * Note: Elements which are already loaded or currently loading will not be touched by this method.
         *
         * @param {ParentNode} [container=document]
         */
        highlight: function highlight(container) {
          var elements = (container || document).querySelectorAll(SELECTOR);
          for (var i2 = 0, element; element = elements[i2++]; ) {
            Prism2.highlightElement(element);
          }
        }
      };
      var logged = false;
      Prism2.fileHighlight = function() {
        if (!logged) {
          console.warn("Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead.");
          logged = true;
        }
        Prism2.plugins.fileHighlight.highlight.apply(this, arguments);
      };
    })();
  })(prism);
  return prism.exports;
}
var prismExports = requirePrism();
const Prism$1 = /* @__PURE__ */ getDefaultExportFromCjs(prismExports);
Prism.languages.json = {
  "property": {
    pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,
    lookbehind: true,
    greedy: true
  },
  "string": {
    pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,
    lookbehind: true,
    greedy: true
  },
  "comment": {
    pattern: /\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,
    greedy: true
  },
  "number": /-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,
  "punctuation": /[{}[\],]/,
  "operator": /:/,
  "boolean": /\b(?:false|true)\b/,
  "null": {
    pattern: /\bnull\b/,
    alias: "keyword"
  }
};
Prism.languages.webmanifest = Prism.languages.json;
const JsonEditor = ({
  value,
  onChange,
  error: externalError,
  placeholder
}) => {
  const [editorContent, setEditorContent] = reactExports.useState(value || "");
  const [internalError, setInternalError] = reactExports.useState(
    void 0
  );
  reactExports.useEffect(() => {
    setEditorContent(value || "");
  }, [value]);
  const handleEditorChange = (newContent) => {
    setEditorContent(newContent);
    setInternalError(void 0);
    onChange(newContent);
  };
  const displayError = internalError || externalError;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `border rounded-md ${displayError ? "border-red-500" : "border-gray-200 dark:border-gray-800"}`,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Editor,
          {
            value: editorContent,
            onValueChange: handleEditorChange,
            highlight: (code2) => Prism$1.highlight(code2, Prism$1.languages.json, "json"),
            padding: 10,
            placeholder,
            style: {
              fontFamily: '"Fira code", "Fira Mono", monospace',
              fontSize: 14,
              backgroundColor: "transparent",
              minHeight: "100px"
            },
            className: "w-full"
          }
        )
      }
    ),
    displayError && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-red-500 mt-1", children: displayError })
  ] });
};
const isTypeSupported = (type2, supportedTypes) => {
  if (Array.isArray(type2)) {
    return type2.every((t2) => supportedTypes.includes(t2));
  }
  return typeof type2 === "string" && supportedTypes.includes(type2);
};
const isSimpleObject = (schema) => {
  const supportedTypes = ["string", "number", "integer", "boolean", "null"];
  if (schema.type && isTypeSupported(schema.type, supportedTypes)) return true;
  if (schema.type === "object") {
    return Object.values(schema.properties ?? {}).every(
      (prop) => prop.type && isTypeSupported(prop.type, supportedTypes)
    );
  }
  if (schema.type === "array") {
    return !!schema.items && isSimpleObject(schema.items);
  }
  return false;
};
const getArrayItemDefault = (schema) => {
  if ("default" in schema && schema.default !== void 0) {
    return schema.default;
  }
  switch (schema.type) {
    case "string":
      return "";
    case "number":
    case "integer":
      return 0;
    case "boolean":
      return false;
    case "array":
      return [];
    case "object":
      return {};
    case "null":
      return null;
    default:
      return null;
  }
};
const DynamicJsonForm = reactExports.forwardRef(
  ({ schema, value, onChange, maxDepth = 3 }, ref2) => {
    const canRenderTopLevelForm = (s2) => {
      const primitiveTypes = ["string", "number", "integer", "boolean", "null"];
      const hasType = Array.isArray(s2.type) ? s2.type.length > 0 : !!s2.type;
      if (!hasType) return false;
      const includesType = (t2) => Array.isArray(s2.type) ? s2.type.includes(t2) : s2.type === t2;
      if (primitiveTypes.some(includesType)) return true;
      if (includesType("object")) {
        const keys = Object.keys(s2.properties ?? {});
        return keys.length > 0;
      }
      if (includesType("array")) {
        return !!s2.items;
      }
      return false;
    };
    const isOnlyJSON = !canRenderTopLevelForm(schema);
    const [isJsonMode, setIsJsonMode] = reactExports.useState(isOnlyJSON);
    const [jsonError, setJsonError] = reactExports.useState();
    const [copiedJson, setCopiedJson] = reactExports.useState(false);
    const { toast: toast2 } = useToast();
    const [rawJsonValue, setRawJsonValue] = reactExports.useState(
      JSON.stringify(value ?? generateDefaultValue(schema), null, 2)
    );
    const [numericInputDrafts, setNumericInputDrafts] = reactExports.useState({});
    const timeoutRef = reactExports.useRef();
    const hasJsonError = () => {
      return !!jsonError;
    };
    const getPathKey = (path) => path.length === 0 ? "$root" : path.join(".");
    const getNumericDisplayValue = (path, currentValue) => {
      const pathKey = getPathKey(path);
      if (Object.prototype.hasOwnProperty.call(numericInputDrafts, pathKey)) {
        return numericInputDrafts[pathKey];
      }
      return typeof currentValue === "number" ? currentValue.toString() : "";
    };
    const updateNumericDraft = (path, draftValue) => {
      const pathKey = getPathKey(path);
      setNumericInputDrafts((prev) => ({ ...prev, [pathKey]: draftValue }));
    };
    const clearNumericDraft = (path) => {
      const pathKey = getPathKey(path);
      setNumericInputDrafts((prev) => {
        if (!Object.prototype.hasOwnProperty.call(prev, pathKey)) {
          return prev;
        }
        const next = { ...prev };
        delete next[pathKey];
        return next;
      });
    };
    const debouncedUpdateParent = reactExports.useCallback(
      (jsonString) => {
        if (timeoutRef.current) {
          clearTimeout(timeoutRef.current);
        }
        timeoutRef.current = setTimeout(() => {
          try {
            const parsed = JSON.parse(jsonString);
            onChange(parsed);
            setJsonError(void 0);
          } catch (err) {
            const errorMessage = err instanceof Error ? err.message : "Invalid JSON";
            setJsonError(errorMessage);
            const trimmed = jsonString?.trim();
            if (trimmed && trimmed.length > 5 && !trimmed.match(/^[\s[{]/)) {
              onChange(generateDefaultValue(schema));
            }
          }
        }, 300);
      },
      [onChange, setJsonError, schema]
    );
    reactExports.useEffect(() => {
      if (!isJsonMode) {
        setRawJsonValue(
          JSON.stringify(value ?? generateDefaultValue(schema), null, 2)
        );
      }
    }, [value, schema, isJsonMode]);
    const handleSwitchToFormMode = () => {
      if (isJsonMode) {
        try {
          const parsed = JSON.parse(rawJsonValue);
          onChange(parsed);
          setIsJsonMode(false);
        } catch (err) {
          setJsonError(err instanceof Error ? err.message : "Invalid JSON");
        }
      } else {
        setRawJsonValue(
          JSON.stringify(value ?? generateDefaultValue(schema), null, 2)
        );
        setIsJsonMode(true);
      }
    };
    const formatJson = () => {
      try {
        const jsonStr = rawJsonValue?.trim();
        if (!jsonStr) {
          return;
        }
        const formatted = JSON.stringify(JSON.parse(jsonStr), null, 2);
        setRawJsonValue(formatted);
        debouncedUpdateParent(formatted);
        setJsonError(void 0);
      } catch (err) {
        setJsonError(err instanceof Error ? err.message : "Invalid JSON");
      }
    };
    const validateJson = () => {
      if (!isJsonMode) return { isValid: true, error: null };
      try {
        const jsonStr = rawJsonValue?.trim();
        if (!jsonStr) return { isValid: true, error: null };
        const parsed = JSON.parse(jsonStr);
        if (timeoutRef.current) {
          clearTimeout(timeoutRef.current);
        }
        onChange(parsed);
        setJsonError(void 0);
        return { isValid: true, error: null };
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : "Invalid JSON";
        setJsonError(errorMessage);
        return { isValid: false, error: errorMessage };
      }
    };
    const handleCopyJson = reactExports.useCallback(async () => {
      try {
        await navigator.clipboard.writeText(
          JSON.stringify(value, null, 2) ?? "[]"
        );
        setCopiedJson(true);
        toast2({
          title: "JSON copied",
          description: "The JSON data has been successfully copied to your clipboard."
        });
        setTimeout(() => {
          setCopiedJson(false);
        }, 2e3);
      } catch (error) {
        toast2({
          title: "Error",
          description: `Failed to copy JSON: ${error instanceof Error ? error.message : String(error)}`,
          variant: "destructive"
        });
      }
    }, [toast2, value]);
    reactExports.useImperativeHandle(ref2, () => ({
      validateJson,
      hasJsonError
    }));
    const renderFormFields = (propSchema, currentValue, path = [], depth = 0, parentSchema, propertyName) => {
      if (depth >= maxDepth && (propSchema.type === "object" || propSchema.type === "array")) {
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          JsonEditor,
          {
            value: JSON.stringify(
              currentValue ?? generateDefaultValue(propSchema, propertyName, parentSchema),
              null,
              2
            ),
            onChange: (newValue) => {
              try {
                const parsed = JSON.parse(newValue);
                handleFieldChange(path, parsed);
                setJsonError(void 0);
              } catch (err) {
                setJsonError(
                  err instanceof Error ? err.message : "Invalid JSON"
                );
              }
            },
            error: jsonError
          }
        );
      }
      const isRequired = parentSchema?.required?.includes(propertyName || "") ?? false;
      let fieldType = propSchema.type;
      if (Array.isArray(fieldType)) {
        fieldType = fieldType.find((t2) => t2 !== "null") ?? fieldType[0];
      }
      switch (fieldType) {
        case "string": {
          const titledOptions = (propSchema.oneOf ?? propSchema.anyOf)?.filter((opt) => "const" in opt);
          if (titledOptions && titledOptions.length > 0) {
            return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
              propSchema.description && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600", children: propSchema.description }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "select",
                {
                  value: currentValue ?? "",
                  onChange: (e2) => {
                    const val = e2.target.value;
                    if (!val && !isRequired) {
                      handleFieldChange(path, void 0);
                    } else {
                      handleFieldChange(path, val);
                    }
                  },
                  required: isRequired,
                  className: "w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-800",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "", children: "Select an option..." }),
                    titledOptions.map((option) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "option",
                      {
                        value: String(option.const),
                        children: option.title ?? String(option.const)
                      },
                      String(option.const)
                    ))
                  ]
                }
              )
            ] });
          }
          if (propSchema.enum) {
            const names2 = Array.isArray(propSchema.enumNames) ? propSchema.enumNames : void 0;
            return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
              propSchema.description && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600", children: propSchema.description }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "select",
                {
                  value: currentValue ?? "",
                  onChange: (e2) => {
                    const val = e2.target.value;
                    if (!val && !isRequired) {
                      handleFieldChange(path, void 0);
                    } else {
                      handleFieldChange(path, val);
                    }
                  },
                  required: isRequired,
                  className: "w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-800",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "", children: "Select an option..." }),
                    propSchema.enum.map((option, idx) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: option, children: names2?.[idx] ?? option }, option))
                  ]
                }
              )
            ] });
          }
          let inputType = "text";
          switch (propSchema.format) {
            case "email":
              inputType = "email";
              break;
            case "uri":
              inputType = "url";
              break;
            case "date":
              inputType = "date";
              break;
            case "date-time":
              inputType = "datetime-local";
              break;
            default:
              inputType = "text";
              break;
          }
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              type: inputType,
              value: currentValue ?? "",
              onChange: (e2) => {
                const val = e2.target.value;
                handleFieldChange(path, val);
              },
              placeholder: propSchema.description,
              required: isRequired,
              minLength: propSchema.minLength,
              maxLength: propSchema.maxLength,
              pattern: propSchema.pattern
            }
          );
        }
        case "number":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              type: "number",
              value: getNumericDisplayValue(path, currentValue),
              onChange: (e2) => {
                const val = e2.target.value;
                updateNumericDraft(path, val);
                if (!val && !isRequired) {
                  handleFieldChange(path, void 0);
                } else {
                  const num = Number(val);
                  if (!isNaN(num)) {
                    handleFieldChange(path, num);
                  }
                }
              },
              onBlur: (e2) => {
                const val = e2.target.value;
                if (!val) {
                  clearNumericDraft(path);
                  return;
                }
                const num = Number(val);
                if (!isNaN(num)) {
                  handleFieldChange(path, num);
                }
                clearNumericDraft(path);
              },
              placeholder: propSchema.description,
              required: isRequired,
              min: propSchema.minimum,
              max: propSchema.maximum
            }
          );
        case "integer":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              type: "number",
              step: "1",
              value: getNumericDisplayValue(path, currentValue),
              onChange: (e2) => {
                const val = e2.target.value;
                updateNumericDraft(path, val);
                if (!val && !isRequired) {
                  handleFieldChange(path, void 0);
                } else {
                  const num = Number(val);
                  if (!isNaN(num) && Number.isInteger(num)) {
                    handleFieldChange(path, num);
                  }
                }
              },
              onBlur: (e2) => {
                const val = e2.target.value;
                if (!val) {
                  clearNumericDraft(path);
                  return;
                }
                const num = Number(val);
                if (!isNaN(num) && Number.isInteger(num)) {
                  handleFieldChange(path, num);
                }
                clearNumericDraft(path);
              },
              placeholder: propSchema.description,
              required: isRequired,
              min: propSchema.minimum,
              max: propSchema.maximum
            }
          );
        case "boolean":
          return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            propSchema.description && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600", children: propSchema.description }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                type: "checkbox",
                checked: currentValue ?? false,
                onChange: (e2) => handleFieldChange(path, e2.target.checked),
                className: "w-4 h-4",
                required: isRequired
              }
            )
          ] });
        case "null":
          return null;
        case "object":
          if (!propSchema.properties) {
            return /* @__PURE__ */ jsxRuntimeExports.jsx(
              JsonEditor,
              {
                value: JSON.stringify(currentValue ?? {}, null, 2),
                onChange: (newValue) => {
                  try {
                    const parsed = JSON.parse(newValue);
                    handleFieldChange(path, parsed);
                    setJsonError(void 0);
                  } catch (err) {
                    setJsonError(
                      err instanceof Error ? err.message : "Invalid JSON"
                    );
                  }
                },
                error: jsonError
              }
            );
          }
          return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2 border rounded p-3", children: Object.entries(propSchema.properties).map(([key, subSchema]) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium mb-1", children: [
              subSchema.title ?? key,
              propSchema.required?.includes(key) && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500 ml-1", children: "*" })
            ] }),
            renderFormFields(
              subSchema,
              currentValue?.[key],
              [...path, key],
              depth + 1,
              propSchema,
              key
            )
          ] }, key)) });
        case "array": {
          const arrayValue = Array.isArray(currentValue) ? currentValue : [];
          if (!propSchema.items) return null;
          const itemSchema = propSchema.items;
          let multiOptions = null;
          const titledMulti = (itemSchema.anyOf ?? itemSchema.oneOf)?.filter((opt) => "const" in opt);
          if (titledMulti && titledMulti.length > 0) {
            multiOptions = titledMulti.map((o2) => ({
              value: String(o2.const),
              label: o2.title ?? String(o2.const)
            }));
          } else if (itemSchema.enum) {
            const names2 = Array.isArray(itemSchema.enumNames) ? itemSchema.enumNames : void 0;
            multiOptions = itemSchema.enum.map((v2, i2) => ({
              value: v2,
              label: names2?.[i2] ?? v2
            }));
          }
          if (multiOptions) {
            const selectSize = Math.min(Math.max(multiOptions.length, 3), 8);
            return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
              propSchema.description && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600", children: propSchema.description }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "select",
                {
                  multiple: true,
                  size: selectSize,
                  value: arrayValue,
                  onChange: (e2) => {
                    const selected = Array.from(
                      e2.target.selectedOptions
                    ).map((o2) => o2.value);
                    handleFieldChange(path, selected);
                  },
                  className: "w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-800",
                  children: multiOptions.map((opt) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: opt.value, children: opt.label }, opt.value))
                }
              ),
              (propSchema.minItems || propSchema.maxItems) && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-gray-500", children: [
                propSchema.minItems ? `Select at least ${propSchema.minItems}. ` : "",
                propSchema.maxItems ? `Select at most ${propSchema.maxItems}.` : ""
              ] })
            ] });
          }
          if (isSimpleObject(propSchema.items)) {
            return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
              propSchema.description && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600", children: propSchema.description }),
              propSchema.items?.description && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm text-gray-500", children: [
                "Items: ",
                propSchema.items.description
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                arrayValue.map((item, index2) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                  renderFormFields(
                    propSchema.items,
                    item,
                    [...path, index2.toString()],
                    depth + 1
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Button,
                    {
                      variant: "outline",
                      size: "sm",
                      onClick: () => {
                        const newArray = [...arrayValue];
                        newArray.splice(index2, 1);
                        handleFieldChange(path, newArray);
                      },
                      children: "Remove"
                    }
                  )
                ] }, index2)),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    variant: "outline",
                    size: "sm",
                    onClick: () => {
                      const defaultValue = getArrayItemDefault(
                        propSchema.items
                      );
                      handleFieldChange(path, [...arrayValue, defaultValue]);
                    },
                    title: propSchema.items?.description ? `Add new ${propSchema.items.description}` : "Add new item",
                    children: "Add Item"
                  }
                )
              ] })
            ] });
          }
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            JsonEditor,
            {
              value: JSON.stringify(currentValue ?? [], null, 2),
              onChange: (newValue) => {
                try {
                  const parsed = JSON.parse(newValue);
                  handleFieldChange(path, parsed);
                  setJsonError(void 0);
                } catch (err) {
                  setJsonError(
                    err instanceof Error ? err.message : "Invalid JSON"
                  );
                }
              },
              error: jsonError
            }
          );
        }
        default:
          return null;
      }
    };
    const handleFieldChange = (path, fieldValue) => {
      if (path.length === 0) {
        onChange(fieldValue);
        return;
      }
      try {
        const newValue = updateValueAtPath(value, path, fieldValue);
        onChange(newValue);
      } catch (error) {
        console.error("Failed to update form value:", error);
        onChange(value);
      }
    };
    const shouldUseJsonMode = schema.type === "object" && (!schema.properties || Object.keys(schema.properties).length === 0);
    reactExports.useEffect(() => {
      if (shouldUseJsonMode && !isJsonMode) {
        setIsJsonMode(true);
      }
    }, [shouldUseJsonMode, isJsonMode]);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-end space-x-2", children: [
        isJsonMode && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              onClick: handleCopyJson,
              children: [
                copiedJson ? /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCheck, { className: "h-4 w-4 mr-2" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "h-4 w-4 mr-2" }),
                "Copy JSON"
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              onClick: formatJson,
              children: "Format JSON"
            }
          )
        ] }),
        !isOnlyJSON && /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "outline",
            size: "sm",
            onClick: handleSwitchToFormMode,
            children: isJsonMode ? "Switch to Form" : "Switch to JSON"
          }
        )
      ] }),
      isJsonMode ? /* @__PURE__ */ jsxRuntimeExports.jsx(
        JsonEditor,
        {
          value: rawJsonValue,
          onChange: (newValue) => {
            setRawJsonValue(newValue);
            debouncedUpdateParent(newValue);
          },
          error: jsonError,
          placeholder: schema.description
        }
      ) : (
        // If schema type is object but value is not an object or is empty, and we have actual JSON data,
        // render a simple representation of the JSON data
        schema.type === "object" && (typeof value !== "object" || value === null || Object.keys(value).length === 0) && rawJsonValue && rawJsonValue !== "{}" ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4 border rounded-md p-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: "Form view not available for this JSON structure. Using simplified view:" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "bg-gray-50 dark:bg-gray-800 dark:text-gray-100 p-4 rounded text-sm overflow-auto", children: rawJsonValue }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: "Use JSON mode for full editing capabilities." })
        ] }) : renderFormFields(schema, value)
      )
    ] });
  }
);
const SamplingRequest = ({
  onApprove,
  request,
  onReject
}) => {
  const { toast: toast2 } = useToast();
  const [messageResult, setMessageResult] = reactExports.useState({
    model: "stub-model",
    stopReason: "endTurn",
    role: "assistant",
    content: {
      type: "text",
      text: ""
    }
  });
  const contentType = messageResult?.content?.type;
  const schema = reactExports.useMemo(() => {
    const s2 = {
      type: "object",
      description: "Message result",
      properties: {
        model: {
          type: "string",
          default: "stub-model",
          description: "model name"
        },
        stopReason: {
          type: "string",
          default: "endTurn",
          description: "Stop reason"
        },
        role: {
          type: "string",
          default: "assistant",
          description: "Role of the model"
        },
        content: {
          type: "object",
          properties: {
            type: {
              type: "string",
              default: "text",
              description: "Type of content"
            }
          }
        }
      }
    };
    if (contentType === "text" && s2.properties) {
      s2.properties.content.properties = {
        ...s2.properties.content.properties,
        text: {
          type: "string",
          default: "",
          description: "text content"
        }
      };
      setMessageResult((prev) => ({
        ...prev,
        content: {
          type: contentType,
          text: ""
        }
      }));
    } else if (contentType === "image" && s2.properties) {
      s2.properties.content.properties = {
        ...s2.properties.content.properties,
        data: {
          type: "string",
          default: "",
          description: "Base64 encoded image data"
        },
        mimeType: {
          type: "string",
          default: "",
          description: "Mime type of the image"
        }
      };
      setMessageResult((prev) => ({
        ...prev,
        content: {
          type: contentType,
          data: "",
          mimeType: ""
        }
      }));
    }
    return s2;
  }, [contentType]);
  const handleApprove = (id2) => {
    const validationResult = CreateMessageResultSchema.safeParse(messageResult);
    if (!validationResult.success) {
      toast2({
        title: "Error",
        description: `There was an error validating the message result: ${validationResult.error.message}`,
        variant: "destructive"
      });
      return;
    }
    onApprove(id2, validationResult.data);
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      "data-testid": "sampling-request",
      className: "flex gap-4 p-4 border rounded-lg space-y-4",
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-1 bg-gray-50 dark:bg-gray-800 dark:text-gray-100 p-2 rounded", children: /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: JSON.stringify(request.request) }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { className: "flex-1 space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            DynamicJsonForm,
            {
              schema,
              value: messageResult,
              onChange: (newValue) => {
                setMessageResult(newValue);
              }
            }
          ) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex space-x-2 mt-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { type: "button", onClick: () => handleApprove(request.id), children: "Approve" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                type: "button",
                variant: "outline",
                onClick: () => onReject(request.id),
                children: "Reject"
              }
            )
          ] })
        ] })
      ]
    }
  );
};
const SamplingTab = ({ pendingRequests, onApprove, onReject }) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(TabsContent, { value: "sampling", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "h-96", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Alert, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { children: "When the server requests LLM sampling, requests will appear here for approval." }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-4 space-y-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold", children: "Recent Requests" }),
      pendingRequests.map((request) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        SamplingRequest,
        {
          request,
          onApprove,
          onReject
        },
        request.id
      )),
      pendingRequests.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-500", children: "No pending requests" })
    ] })
  ] }) });
};
function clamp(value, [min2, max2]) {
  return Math.min(max2, Math.max(min2, value));
}
// @__NO_SIDE_EFFECTS__
function createSlot(ownerName) {
  const SlotClone = /* @__PURE__ */ createSlotClone(ownerName);
  const Slot2 = reactExports.forwardRef((props, forwardedRef) => {
    const { children, ...slotProps } = props;
    const childrenArray = reactExports.Children.toArray(children);
    const slottable = childrenArray.find(isSlottable);
    if (slottable) {
      const newElement = slottable.props.children;
      const newChildren = childrenArray.map((child) => {
        if (child === slottable) {
          if (reactExports.Children.count(newElement) > 1) return reactExports.Children.only(null);
          return reactExports.isValidElement(newElement) ? newElement.props.children : null;
        } else {
          return child;
        }
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children: reactExports.isValidElement(newElement) ? reactExports.cloneElement(newElement, void 0, newChildren) : null });
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children });
  });
  Slot2.displayName = `${ownerName}.Slot`;
  return Slot2;
}
// @__NO_SIDE_EFFECTS__
function createSlotClone(ownerName) {
  const SlotClone = reactExports.forwardRef((props, forwardedRef) => {
    const { children, ...slotProps } = props;
    if (reactExports.isValidElement(children)) {
      const childrenRef = getElementRef(children);
      const props2 = mergeProps(slotProps, children.props);
      if (children.type !== reactExports.Fragment) {
        props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;
      }
      return reactExports.cloneElement(children, props2);
    }
    return reactExports.Children.count(children) > 1 ? reactExports.Children.only(null) : null;
  });
  SlotClone.displayName = `${ownerName}.SlotClone`;
  return SlotClone;
}
var SLOTTABLE_IDENTIFIER$1 = /* @__PURE__ */ Symbol("radix.slottable");
function isSlottable(child) {
  return reactExports.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER$1;
}
function mergeProps(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          const result = childPropValue(...args);
          slotPropValue(...args);
          return result;
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}
function usePrevious(value) {
  const ref2 = reactExports.useRef({ value, previous: value });
  return reactExports.useMemo(() => {
    if (ref2.current.value !== value) {
      ref2.current.previous = ref2.current.value;
      ref2.current.value = value;
    }
    return ref2.current.previous;
  }, [value]);
}
var OPEN_KEYS = [" ", "Enter", "ArrowUp", "ArrowDown"];
var SELECTION_KEYS = [" ", "Enter"];
var SELECT_NAME = "Select";
var [Collection, useCollection, createCollectionScope] = createCollection(SELECT_NAME);
var [createSelectContext] = createContextScope(SELECT_NAME, [
  createCollectionScope,
  createPopperScope
]);
var usePopperScope$1 = createPopperScope();
var [SelectProvider, useSelectContext] = createSelectContext(SELECT_NAME);
var [SelectNativeOptionsProvider, useSelectNativeOptionsContext] = createSelectContext(SELECT_NAME);
var Select$1 = (props) => {
  const {
    __scopeSelect,
    children,
    open: openProp,
    defaultOpen,
    onOpenChange,
    value: valueProp,
    defaultValue,
    onValueChange,
    dir,
    name: name2,
    autoComplete,
    disabled,
    required: required2,
    form
  } = props;
  const popperScope = usePopperScope$1(__scopeSelect);
  const [trigger, setTrigger] = reactExports.useState(null);
  const [valueNode, setValueNode] = reactExports.useState(null);
  const [valueNodeHasChildren, setValueNodeHasChildren] = reactExports.useState(false);
  const direction = useDirection(dir);
  const [open, setOpen] = useControllableState({
    prop: openProp,
    defaultProp: defaultOpen ?? false,
    onChange: onOpenChange,
    caller: SELECT_NAME
  });
  const [value, setValue] = useControllableState({
    prop: valueProp,
    defaultProp: defaultValue,
    onChange: onValueChange,
    caller: SELECT_NAME
  });
  const triggerPointerDownPosRef = reactExports.useRef(null);
  const isFormControl = trigger ? form || !!trigger.closest("form") : true;
  const [nativeOptionsSet, setNativeOptionsSet] = reactExports.useState(/* @__PURE__ */ new Set());
  const nativeSelectKey = Array.from(nativeOptionsSet).map((option) => option.props.value).join(";");
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Root2$2, { ...popperScope, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
    SelectProvider,
    {
      required: required2,
      scope: __scopeSelect,
      trigger,
      onTriggerChange: setTrigger,
      valueNode,
      onValueNodeChange: setValueNode,
      valueNodeHasChildren,
      onValueNodeHasChildrenChange: setValueNodeHasChildren,
      contentId: useId(),
      value,
      onValueChange: setValue,
      open,
      onOpenChange: setOpen,
      dir: direction,
      triggerPointerDownPosRef,
      disabled,
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Collection.Provider, { scope: __scopeSelect, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          SelectNativeOptionsProvider,
          {
            scope: props.__scopeSelect,
            onNativeOptionAdd: reactExports.useCallback((option) => {
              setNativeOptionsSet((prev) => new Set(prev).add(option));
            }, []),
            onNativeOptionRemove: reactExports.useCallback((option) => {
              setNativeOptionsSet((prev) => {
                const optionsSet = new Set(prev);
                optionsSet.delete(option);
                return optionsSet;
              });
            }, []),
            children
          }
        ) }),
        isFormControl ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
          SelectBubbleInput,
          {
            "aria-hidden": true,
            required: required2,
            tabIndex: -1,
            name: name2,
            autoComplete,
            value,
            onChange: (event) => setValue(event.target.value),
            disabled,
            form,
            children: [
              value === void 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "" }) : null,
              Array.from(nativeOptionsSet)
            ]
          },
          nativeSelectKey
        ) : null
      ]
    }
  ) });
};
Select$1.displayName = SELECT_NAME;
var TRIGGER_NAME$2 = "SelectTrigger";
var SelectTrigger$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, disabled = false, ...triggerProps } = props;
    const popperScope = usePopperScope$1(__scopeSelect);
    const context = useSelectContext(TRIGGER_NAME$2, __scopeSelect);
    const isDisabled = context.disabled || disabled;
    const composedRefs = useComposedRefs(forwardedRef, context.onTriggerChange);
    const getItems = useCollection(__scopeSelect);
    const pointerTypeRef = reactExports.useRef("touch");
    const [searchRef, handleTypeaheadSearch, resetTypeahead] = useTypeaheadSearch((search) => {
      const enabledItems = getItems().filter((item) => !item.disabled);
      const currentItem = enabledItems.find((item) => item.value === context.value);
      const nextItem = findNextItem(enabledItems, search, currentItem);
      if (nextItem !== void 0) {
        context.onValueChange(nextItem.value);
      }
    });
    const handleOpen = (pointerEvent) => {
      if (!isDisabled) {
        context.onOpenChange(true);
        resetTypeahead();
      }
      if (pointerEvent) {
        context.triggerPointerDownPosRef.current = {
          x: Math.round(pointerEvent.pageX),
          y: Math.round(pointerEvent.pageY)
        };
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Anchor, { asChild: true, ...popperScope, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.button,
      {
        type: "button",
        role: "combobox",
        "aria-controls": context.contentId,
        "aria-expanded": context.open,
        "aria-required": context.required,
        "aria-autocomplete": "none",
        dir: context.dir,
        "data-state": context.open ? "open" : "closed",
        disabled: isDisabled,
        "data-disabled": isDisabled ? "" : void 0,
        "data-placeholder": shouldShowPlaceholder(context.value) ? "" : void 0,
        ...triggerProps,
        ref: composedRefs,
        onClick: composeEventHandlers(triggerProps.onClick, (event) => {
          event.currentTarget.focus();
          if (pointerTypeRef.current !== "mouse") {
            handleOpen(event);
          }
        }),
        onPointerDown: composeEventHandlers(triggerProps.onPointerDown, (event) => {
          pointerTypeRef.current = event.pointerType;
          const target = event.target;
          if (target.hasPointerCapture(event.pointerId)) {
            target.releasePointerCapture(event.pointerId);
          }
          if (event.button === 0 && event.ctrlKey === false && event.pointerType === "mouse") {
            handleOpen(event);
            event.preventDefault();
          }
        }),
        onKeyDown: composeEventHandlers(triggerProps.onKeyDown, (event) => {
          const isTypingAhead = searchRef.current !== "";
          const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;
          if (!isModifierKey && event.key.length === 1) handleTypeaheadSearch(event.key);
          if (isTypingAhead && event.key === " ") return;
          if (OPEN_KEYS.includes(event.key)) {
            handleOpen();
            event.preventDefault();
          }
        })
      }
    ) });
  }
);
SelectTrigger$1.displayName = TRIGGER_NAME$2;
var VALUE_NAME = "SelectValue";
var SelectValue$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, className, style, children, placeholder = "", ...valueProps } = props;
    const context = useSelectContext(VALUE_NAME, __scopeSelect);
    const { onValueNodeHasChildrenChange } = context;
    const hasChildren = children !== void 0;
    const composedRefs = useComposedRefs(forwardedRef, context.onValueNodeChange);
    useLayoutEffect2(() => {
      onValueNodeHasChildrenChange(hasChildren);
    }, [onValueNodeHasChildrenChange, hasChildren]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.span,
      {
        ...valueProps,
        ref: composedRefs,
        style: { pointerEvents: "none" },
        children: shouldShowPlaceholder(context.value) ? /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: placeholder }) : children
      }
    );
  }
);
SelectValue$1.displayName = VALUE_NAME;
var ICON_NAME = "SelectIcon";
var SelectIcon = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, children, ...iconProps } = props;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.span, { "aria-hidden": true, ...iconProps, ref: forwardedRef, children: children || "▼" });
  }
);
SelectIcon.displayName = ICON_NAME;
var PORTAL_NAME$1 = "SelectPortal";
var SelectPortal = (props) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Portal$3, { asChild: true, ...props });
};
SelectPortal.displayName = PORTAL_NAME$1;
var CONTENT_NAME$1 = "SelectContent";
var SelectContent$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const context = useSelectContext(CONTENT_NAME$1, props.__scopeSelect);
    const [fragment, setFragment] = reactExports.useState();
    useLayoutEffect2(() => {
      setFragment(new DocumentFragment());
    }, []);
    if (!context.open) {
      const frag = fragment;
      return frag ? reactDomExports.createPortal(
        /* @__PURE__ */ jsxRuntimeExports.jsx(SelectContentProvider, { scope: props.__scopeSelect, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Collection.Slot, { scope: props.__scopeSelect, children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: props.children }) }) }),
        frag
      ) : null;
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(SelectContentImpl, { ...props, ref: forwardedRef });
  }
);
SelectContent$1.displayName = CONTENT_NAME$1;
var CONTENT_MARGIN = 10;
var [SelectContentProvider, useSelectContentContext] = createSelectContext(CONTENT_NAME$1);
var CONTENT_IMPL_NAME = "SelectContentImpl";
var Slot = /* @__PURE__ */ createSlot("SelectContent.RemoveScroll");
var SelectContentImpl = reactExports.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeSelect,
      position = "item-aligned",
      onCloseAutoFocus,
      onEscapeKeyDown,
      onPointerDownOutside,
      //
      // PopperContent props
      side,
      sideOffset,
      align,
      alignOffset,
      arrowPadding,
      collisionBoundary,
      collisionPadding,
      sticky,
      hideWhenDetached,
      avoidCollisions,
      //
      ...contentProps
    } = props;
    const context = useSelectContext(CONTENT_NAME$1, __scopeSelect);
    const [content, setContent] = reactExports.useState(null);
    const [viewport, setViewport] = reactExports.useState(null);
    const composedRefs = useComposedRefs(forwardedRef, (node) => setContent(node));
    const [selectedItem, setSelectedItem] = reactExports.useState(null);
    const [selectedItemText, setSelectedItemText] = reactExports.useState(
      null
    );
    const getItems = useCollection(__scopeSelect);
    const [isPositioned, setIsPositioned] = reactExports.useState(false);
    const firstValidItemFoundRef = reactExports.useRef(false);
    reactExports.useEffect(() => {
      if (content) return hideOthers(content);
    }, [content]);
    useFocusGuards();
    const focusFirst2 = reactExports.useCallback(
      (candidates) => {
        const [firstItem, ...restItems] = getItems().map((item) => item.ref.current);
        const [lastItem] = restItems.slice(-1);
        const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;
        for (const candidate of candidates) {
          if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return;
          candidate?.scrollIntoView({ block: "nearest" });
          if (candidate === firstItem && viewport) viewport.scrollTop = 0;
          if (candidate === lastItem && viewport) viewport.scrollTop = viewport.scrollHeight;
          candidate?.focus();
          if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return;
        }
      },
      [getItems, viewport]
    );
    const focusSelectedItem = reactExports.useCallback(
      () => focusFirst2([selectedItem, content]),
      [focusFirst2, selectedItem, content]
    );
    reactExports.useEffect(() => {
      if (isPositioned) {
        focusSelectedItem();
      }
    }, [isPositioned, focusSelectedItem]);
    const { onOpenChange, triggerPointerDownPosRef } = context;
    reactExports.useEffect(() => {
      if (content) {
        let pointerMoveDelta = { x: 0, y: 0 };
        const handlePointerMove = (event) => {
          pointerMoveDelta = {
            x: Math.abs(Math.round(event.pageX) - (triggerPointerDownPosRef.current?.x ?? 0)),
            y: Math.abs(Math.round(event.pageY) - (triggerPointerDownPosRef.current?.y ?? 0))
          };
        };
        const handlePointerUp = (event) => {
          if (pointerMoveDelta.x <= 10 && pointerMoveDelta.y <= 10) {
            event.preventDefault();
          } else {
            if (!content.contains(event.target)) {
              onOpenChange(false);
            }
          }
          document.removeEventListener("pointermove", handlePointerMove);
          triggerPointerDownPosRef.current = null;
        };
        if (triggerPointerDownPosRef.current !== null) {
          document.addEventListener("pointermove", handlePointerMove);
          document.addEventListener("pointerup", handlePointerUp, { capture: true, once: true });
        }
        return () => {
          document.removeEventListener("pointermove", handlePointerMove);
          document.removeEventListener("pointerup", handlePointerUp, { capture: true });
        };
      }
    }, [content, onOpenChange, triggerPointerDownPosRef]);
    reactExports.useEffect(() => {
      const close = () => onOpenChange(false);
      window.addEventListener("blur", close);
      window.addEventListener("resize", close);
      return () => {
        window.removeEventListener("blur", close);
        window.removeEventListener("resize", close);
      };
    }, [onOpenChange]);
    const [searchRef, handleTypeaheadSearch] = useTypeaheadSearch((search) => {
      const enabledItems = getItems().filter((item) => !item.disabled);
      const currentItem = enabledItems.find((item) => item.ref.current === document.activeElement);
      const nextItem = findNextItem(enabledItems, search, currentItem);
      if (nextItem) {
        setTimeout(() => nextItem.ref.current.focus());
      }
    });
    const itemRefCallback = reactExports.useCallback(
      (node, value, disabled) => {
        const isFirstValidItem = !firstValidItemFoundRef.current && !disabled;
        const isSelectedItem = context.value !== void 0 && context.value === value;
        if (isSelectedItem || isFirstValidItem) {
          setSelectedItem(node);
          if (isFirstValidItem) firstValidItemFoundRef.current = true;
        }
      },
      [context.value]
    );
    const handleItemLeave = reactExports.useCallback(() => content?.focus(), [content]);
    const itemTextRefCallback = reactExports.useCallback(
      (node, value, disabled) => {
        const isFirstValidItem = !firstValidItemFoundRef.current && !disabled;
        const isSelectedItem = context.value !== void 0 && context.value === value;
        if (isSelectedItem || isFirstValidItem) {
          setSelectedItemText(node);
        }
      },
      [context.value]
    );
    const SelectPosition = position === "popper" ? SelectPopperPosition : SelectItemAlignedPosition;
    const popperContentProps = SelectPosition === SelectPopperPosition ? {
      side,
      sideOffset,
      align,
      alignOffset,
      arrowPadding,
      collisionBoundary,
      collisionPadding,
      sticky,
      hideWhenDetached,
      avoidCollisions
    } : {};
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      SelectContentProvider,
      {
        scope: __scopeSelect,
        content,
        viewport,
        onViewportChange: setViewport,
        itemRefCallback,
        selectedItem,
        onItemLeave: handleItemLeave,
        itemTextRefCallback,
        focusSelectedItem,
        selectedItemText,
        position,
        isPositioned,
        searchRef,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(ReactRemoveScroll, { as: Slot, allowPinchZoom: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          FocusScope,
          {
            asChild: true,
            trapped: context.open,
            onMountAutoFocus: (event) => {
              event.preventDefault();
            },
            onUnmountAutoFocus: composeEventHandlers(onCloseAutoFocus, (event) => {
              context.trigger?.focus({ preventScroll: true });
              event.preventDefault();
            }),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              DismissableLayer,
              {
                asChild: true,
                disableOutsidePointerEvents: true,
                onEscapeKeyDown,
                onPointerDownOutside,
                onFocusOutside: (event) => event.preventDefault(),
                onDismiss: () => context.onOpenChange(false),
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  SelectPosition,
                  {
                    role: "listbox",
                    id: context.contentId,
                    "data-state": context.open ? "open" : "closed",
                    dir: context.dir,
                    onContextMenu: (event) => event.preventDefault(),
                    ...contentProps,
                    ...popperContentProps,
                    onPlaced: () => setIsPositioned(true),
                    ref: composedRefs,
                    style: {
                      // flex layout so we can place the scroll buttons properly
                      display: "flex",
                      flexDirection: "column",
                      // reset the outline by default as the content MAY get focused
                      outline: "none",
                      ...contentProps.style
                    },
                    onKeyDown: composeEventHandlers(contentProps.onKeyDown, (event) => {
                      const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;
                      if (event.key === "Tab") event.preventDefault();
                      if (!isModifierKey && event.key.length === 1) handleTypeaheadSearch(event.key);
                      if (["ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) {
                        const items2 = getItems().filter((item) => !item.disabled);
                        let candidateNodes = items2.map((item) => item.ref.current);
                        if (["ArrowUp", "End"].includes(event.key)) {
                          candidateNodes = candidateNodes.slice().reverse();
                        }
                        if (["ArrowUp", "ArrowDown"].includes(event.key)) {
                          const currentElement = event.target;
                          const currentIndex = candidateNodes.indexOf(currentElement);
                          candidateNodes = candidateNodes.slice(currentIndex + 1);
                        }
                        setTimeout(() => focusFirst2(candidateNodes));
                        event.preventDefault();
                      }
                    })
                  }
                )
              }
            )
          }
        ) })
      }
    );
  }
);
SelectContentImpl.displayName = CONTENT_IMPL_NAME;
var ITEM_ALIGNED_POSITION_NAME = "SelectItemAlignedPosition";
var SelectItemAlignedPosition = reactExports.forwardRef((props, forwardedRef) => {
  const { __scopeSelect, onPlaced, ...popperProps } = props;
  const context = useSelectContext(CONTENT_NAME$1, __scopeSelect);
  const contentContext = useSelectContentContext(CONTENT_NAME$1, __scopeSelect);
  const [contentWrapper, setContentWrapper] = reactExports.useState(null);
  const [content, setContent] = reactExports.useState(null);
  const composedRefs = useComposedRefs(forwardedRef, (node) => setContent(node));
  const getItems = useCollection(__scopeSelect);
  const shouldExpandOnScrollRef = reactExports.useRef(false);
  const shouldRepositionRef = reactExports.useRef(true);
  const { viewport, selectedItem, selectedItemText, focusSelectedItem } = contentContext;
  const position = reactExports.useCallback(() => {
    if (context.trigger && context.valueNode && contentWrapper && content && viewport && selectedItem && selectedItemText) {
      const triggerRect = context.trigger.getBoundingClientRect();
      const contentRect = content.getBoundingClientRect();
      const valueNodeRect = context.valueNode.getBoundingClientRect();
      const itemTextRect = selectedItemText.getBoundingClientRect();
      if (context.dir !== "rtl") {
        const itemTextOffset = itemTextRect.left - contentRect.left;
        const left = valueNodeRect.left - itemTextOffset;
        const leftDelta = triggerRect.left - left;
        const minContentWidth = triggerRect.width + leftDelta;
        const contentWidth = Math.max(minContentWidth, contentRect.width);
        const rightEdge = window.innerWidth - CONTENT_MARGIN;
        const clampedLeft = clamp(left, [
          CONTENT_MARGIN,
          // Prevents the content from going off the starting edge of the
          // viewport. It may still go off the ending edge, but this can be
          // controlled by the user since they may want to manage overflow in a
          // specific way.
          // https://github.com/radix-ui/primitives/issues/2049
          Math.max(CONTENT_MARGIN, rightEdge - contentWidth)
        ]);
        contentWrapper.style.minWidth = minContentWidth + "px";
        contentWrapper.style.left = clampedLeft + "px";
      } else {
        const itemTextOffset = contentRect.right - itemTextRect.right;
        const right = window.innerWidth - valueNodeRect.right - itemTextOffset;
        const rightDelta = window.innerWidth - triggerRect.right - right;
        const minContentWidth = triggerRect.width + rightDelta;
        const contentWidth = Math.max(minContentWidth, contentRect.width);
        const leftEdge = window.innerWidth - CONTENT_MARGIN;
        const clampedRight = clamp(right, [
          CONTENT_MARGIN,
          Math.max(CONTENT_MARGIN, leftEdge - contentWidth)
        ]);
        contentWrapper.style.minWidth = minContentWidth + "px";
        contentWrapper.style.right = clampedRight + "px";
      }
      const items2 = getItems();
      const availableHeight = window.innerHeight - CONTENT_MARGIN * 2;
      const itemsHeight = viewport.scrollHeight;
      const contentStyles = window.getComputedStyle(content);
      const contentBorderTopWidth = parseInt(contentStyles.borderTopWidth, 10);
      const contentPaddingTop = parseInt(contentStyles.paddingTop, 10);
      const contentBorderBottomWidth = parseInt(contentStyles.borderBottomWidth, 10);
      const contentPaddingBottom = parseInt(contentStyles.paddingBottom, 10);
      const fullContentHeight = contentBorderTopWidth + contentPaddingTop + itemsHeight + contentPaddingBottom + contentBorderBottomWidth;
      const minContentHeight = Math.min(selectedItem.offsetHeight * 5, fullContentHeight);
      const viewportStyles = window.getComputedStyle(viewport);
      const viewportPaddingTop = parseInt(viewportStyles.paddingTop, 10);
      const viewportPaddingBottom = parseInt(viewportStyles.paddingBottom, 10);
      const topEdgeToTriggerMiddle = triggerRect.top + triggerRect.height / 2 - CONTENT_MARGIN;
      const triggerMiddleToBottomEdge = availableHeight - topEdgeToTriggerMiddle;
      const selectedItemHalfHeight = selectedItem.offsetHeight / 2;
      const itemOffsetMiddle = selectedItem.offsetTop + selectedItemHalfHeight;
      const contentTopToItemMiddle = contentBorderTopWidth + contentPaddingTop + itemOffsetMiddle;
      const itemMiddleToContentBottom = fullContentHeight - contentTopToItemMiddle;
      const willAlignWithoutTopOverflow = contentTopToItemMiddle <= topEdgeToTriggerMiddle;
      if (willAlignWithoutTopOverflow) {
        const isLastItem = items2.length > 0 && selectedItem === items2[items2.length - 1].ref.current;
        contentWrapper.style.bottom = "0px";
        const viewportOffsetBottom = content.clientHeight - viewport.offsetTop - viewport.offsetHeight;
        const clampedTriggerMiddleToBottomEdge = Math.max(
          triggerMiddleToBottomEdge,
          selectedItemHalfHeight + // viewport might have padding bottom, include it to avoid a scrollable viewport
          (isLastItem ? viewportPaddingBottom : 0) + viewportOffsetBottom + contentBorderBottomWidth
        );
        const height = contentTopToItemMiddle + clampedTriggerMiddleToBottomEdge;
        contentWrapper.style.height = height + "px";
      } else {
        const isFirstItem = items2.length > 0 && selectedItem === items2[0].ref.current;
        contentWrapper.style.top = "0px";
        const clampedTopEdgeToTriggerMiddle = Math.max(
          topEdgeToTriggerMiddle,
          contentBorderTopWidth + viewport.offsetTop + // viewport might have padding top, include it to avoid a scrollable viewport
          (isFirstItem ? viewportPaddingTop : 0) + selectedItemHalfHeight
        );
        const height = clampedTopEdgeToTriggerMiddle + itemMiddleToContentBottom;
        contentWrapper.style.height = height + "px";
        viewport.scrollTop = contentTopToItemMiddle - topEdgeToTriggerMiddle + viewport.offsetTop;
      }
      contentWrapper.style.margin = `${CONTENT_MARGIN}px 0`;
      contentWrapper.style.minHeight = minContentHeight + "px";
      contentWrapper.style.maxHeight = availableHeight + "px";
      onPlaced?.();
      requestAnimationFrame(() => shouldExpandOnScrollRef.current = true);
    }
  }, [
    getItems,
    context.trigger,
    context.valueNode,
    contentWrapper,
    content,
    viewport,
    selectedItem,
    selectedItemText,
    context.dir,
    onPlaced
  ]);
  useLayoutEffect2(() => position(), [position]);
  const [contentZIndex, setContentZIndex] = reactExports.useState();
  useLayoutEffect2(() => {
    if (content) setContentZIndex(window.getComputedStyle(content).zIndex);
  }, [content]);
  const handleScrollButtonChange = reactExports.useCallback(
    (node) => {
      if (node && shouldRepositionRef.current === true) {
        position();
        focusSelectedItem?.();
        shouldRepositionRef.current = false;
      }
    },
    [position, focusSelectedItem]
  );
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    SelectViewportProvider,
    {
      scope: __scopeSelect,
      contentWrapper,
      shouldExpandOnScrollRef,
      onScrollButtonChange: handleScrollButtonChange,
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          ref: setContentWrapper,
          style: {
            display: "flex",
            flexDirection: "column",
            position: "fixed",
            zIndex: contentZIndex
          },
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            Primitive$1.div,
            {
              ...popperProps,
              ref: composedRefs,
              style: {
                // When we get the height of the content, it includes borders. If we were to set
                // the height without having `boxSizing: 'border-box'` it would be too big.
                boxSizing: "border-box",
                // We need to ensure the content doesn't get taller than the wrapper
                maxHeight: "100%",
                ...popperProps.style
              }
            }
          )
        }
      )
    }
  );
});
SelectItemAlignedPosition.displayName = ITEM_ALIGNED_POSITION_NAME;
var POPPER_POSITION_NAME = "SelectPopperPosition";
var SelectPopperPosition = reactExports.forwardRef((props, forwardedRef) => {
  const {
    __scopeSelect,
    align = "start",
    collisionPadding = CONTENT_MARGIN,
    ...popperProps
  } = props;
  const popperScope = usePopperScope$1(__scopeSelect);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    Content,
    {
      ...popperScope,
      ...popperProps,
      ref: forwardedRef,
      align,
      collisionPadding,
      style: {
        // Ensure border-box for floating-ui calculations
        boxSizing: "border-box",
        ...popperProps.style,
        // re-namespace exposed content custom properties
        ...{
          "--radix-select-content-transform-origin": "var(--radix-popper-transform-origin)",
          "--radix-select-content-available-width": "var(--radix-popper-available-width)",
          "--radix-select-content-available-height": "var(--radix-popper-available-height)",
          "--radix-select-trigger-width": "var(--radix-popper-anchor-width)",
          "--radix-select-trigger-height": "var(--radix-popper-anchor-height)"
        }
      }
    }
  );
});
SelectPopperPosition.displayName = POPPER_POSITION_NAME;
var [SelectViewportProvider, useSelectViewportContext] = createSelectContext(CONTENT_NAME$1, {});
var VIEWPORT_NAME = "SelectViewport";
var SelectViewport = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, nonce, ...viewportProps } = props;
    const contentContext = useSelectContentContext(VIEWPORT_NAME, __scopeSelect);
    const viewportContext = useSelectViewportContext(VIEWPORT_NAME, __scopeSelect);
    const composedRefs = useComposedRefs(forwardedRef, contentContext.onViewportChange);
    const prevScrollTopRef = reactExports.useRef(0);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "style",
        {
          dangerouslySetInnerHTML: {
            __html: `[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}`
          },
          nonce
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Collection.Slot, { scope: __scopeSelect, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Primitive$1.div,
        {
          "data-radix-select-viewport": "",
          role: "presentation",
          ...viewportProps,
          ref: composedRefs,
          style: {
            // we use position: 'relative' here on the `viewport` so that when we call
            // `selectedItem.offsetTop` in calculations, the offset is relative to the viewport
            // (independent of the scrollUpButton).
            position: "relative",
            flex: 1,
            // Viewport should only be scrollable in the vertical direction.
            // This won't work in vertical writing modes, so we'll need to
            // revisit this if/when that is supported
            // https://developer.chrome.com/blog/vertical-form-controls
            overflow: "hidden auto",
            ...viewportProps.style
          },
          onScroll: composeEventHandlers(viewportProps.onScroll, (event) => {
            const viewport = event.currentTarget;
            const { contentWrapper, shouldExpandOnScrollRef } = viewportContext;
            if (shouldExpandOnScrollRef?.current && contentWrapper) {
              const scrolledBy = Math.abs(prevScrollTopRef.current - viewport.scrollTop);
              if (scrolledBy > 0) {
                const availableHeight = window.innerHeight - CONTENT_MARGIN * 2;
                const cssMinHeight = parseFloat(contentWrapper.style.minHeight);
                const cssHeight = parseFloat(contentWrapper.style.height);
                const prevHeight = Math.max(cssMinHeight, cssHeight);
                if (prevHeight < availableHeight) {
                  const nextHeight = prevHeight + scrolledBy;
                  const clampedNextHeight = Math.min(availableHeight, nextHeight);
                  const heightDiff = nextHeight - clampedNextHeight;
                  contentWrapper.style.height = clampedNextHeight + "px";
                  if (contentWrapper.style.bottom === "0px") {
                    viewport.scrollTop = heightDiff > 0 ? heightDiff : 0;
                    contentWrapper.style.justifyContent = "flex-end";
                  }
                }
              }
            }
            prevScrollTopRef.current = viewport.scrollTop;
          })
        }
      ) })
    ] });
  }
);
SelectViewport.displayName = VIEWPORT_NAME;
var GROUP_NAME = "SelectGroup";
var [SelectGroupContextProvider, useSelectGroupContext] = createSelectContext(GROUP_NAME);
var SelectGroup = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, ...groupProps } = props;
    const groupId = useId();
    return /* @__PURE__ */ jsxRuntimeExports.jsx(SelectGroupContextProvider, { scope: __scopeSelect, id: groupId, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.div, { role: "group", "aria-labelledby": groupId, ...groupProps, ref: forwardedRef }) });
  }
);
SelectGroup.displayName = GROUP_NAME;
var LABEL_NAME = "SelectLabel";
var SelectLabel$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, ...labelProps } = props;
    const groupContext = useSelectGroupContext(LABEL_NAME, __scopeSelect);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.div, { id: groupContext.id, ...labelProps, ref: forwardedRef });
  }
);
SelectLabel$1.displayName = LABEL_NAME;
var ITEM_NAME = "SelectItem";
var [SelectItemContextProvider, useSelectItemContext] = createSelectContext(ITEM_NAME);
var SelectItem$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeSelect,
      value,
      disabled = false,
      textValue: textValueProp,
      ...itemProps
    } = props;
    const context = useSelectContext(ITEM_NAME, __scopeSelect);
    const contentContext = useSelectContentContext(ITEM_NAME, __scopeSelect);
    const isSelected = context.value === value;
    const [textValue, setTextValue] = reactExports.useState(textValueProp ?? "");
    const [isFocused, setIsFocused] = reactExports.useState(false);
    const composedRefs = useComposedRefs(
      forwardedRef,
      (node) => contentContext.itemRefCallback?.(node, value, disabled)
    );
    const textId = useId();
    const pointerTypeRef = reactExports.useRef("touch");
    const handleSelect = () => {
      if (!disabled) {
        context.onValueChange(value);
        context.onOpenChange(false);
      }
    };
    if (value === "") {
      throw new Error(
        "A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder."
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      SelectItemContextProvider,
      {
        scope: __scopeSelect,
        value,
        disabled,
        textId,
        isSelected,
        onItemTextChange: reactExports.useCallback((node) => {
          setTextValue((prevTextValue) => prevTextValue || (node?.textContent ?? "").trim());
        }, []),
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Collection.ItemSlot,
          {
            scope: __scopeSelect,
            value,
            disabled,
            textValue,
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              Primitive$1.div,
              {
                role: "option",
                "aria-labelledby": textId,
                "data-highlighted": isFocused ? "" : void 0,
                "aria-selected": isSelected && isFocused,
                "data-state": isSelected ? "checked" : "unchecked",
                "aria-disabled": disabled || void 0,
                "data-disabled": disabled ? "" : void 0,
                tabIndex: disabled ? void 0 : -1,
                ...itemProps,
                ref: composedRefs,
                onFocus: composeEventHandlers(itemProps.onFocus, () => setIsFocused(true)),
                onBlur: composeEventHandlers(itemProps.onBlur, () => setIsFocused(false)),
                onClick: composeEventHandlers(itemProps.onClick, () => {
                  if (pointerTypeRef.current !== "mouse") handleSelect();
                }),
                onPointerUp: composeEventHandlers(itemProps.onPointerUp, () => {
                  if (pointerTypeRef.current === "mouse") handleSelect();
                }),
                onPointerDown: composeEventHandlers(itemProps.onPointerDown, (event) => {
                  pointerTypeRef.current = event.pointerType;
                }),
                onPointerMove: composeEventHandlers(itemProps.onPointerMove, (event) => {
                  pointerTypeRef.current = event.pointerType;
                  if (disabled) {
                    contentContext.onItemLeave?.();
                  } else if (pointerTypeRef.current === "mouse") {
                    event.currentTarget.focus({ preventScroll: true });
                  }
                }),
                onPointerLeave: composeEventHandlers(itemProps.onPointerLeave, (event) => {
                  if (event.currentTarget === document.activeElement) {
                    contentContext.onItemLeave?.();
                  }
                }),
                onKeyDown: composeEventHandlers(itemProps.onKeyDown, (event) => {
                  const isTypingAhead = contentContext.searchRef?.current !== "";
                  if (isTypingAhead && event.key === " ") return;
                  if (SELECTION_KEYS.includes(event.key)) handleSelect();
                  if (event.key === " ") event.preventDefault();
                })
              }
            )
          }
        )
      }
    );
  }
);
SelectItem$1.displayName = ITEM_NAME;
var ITEM_TEXT_NAME = "SelectItemText";
var SelectItemText = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, className, style, ...itemTextProps } = props;
    const context = useSelectContext(ITEM_TEXT_NAME, __scopeSelect);
    const contentContext = useSelectContentContext(ITEM_TEXT_NAME, __scopeSelect);
    const itemContext = useSelectItemContext(ITEM_TEXT_NAME, __scopeSelect);
    const nativeOptionsContext = useSelectNativeOptionsContext(ITEM_TEXT_NAME, __scopeSelect);
    const [itemTextNode, setItemTextNode] = reactExports.useState(null);
    const composedRefs = useComposedRefs(
      forwardedRef,
      (node) => setItemTextNode(node),
      itemContext.onItemTextChange,
      (node) => contentContext.itemTextRefCallback?.(node, itemContext.value, itemContext.disabled)
    );
    const textContent = itemTextNode?.textContent;
    const nativeOption = reactExports.useMemo(
      () => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: itemContext.value, disabled: itemContext.disabled, children: textContent }, itemContext.value),
      [itemContext.disabled, itemContext.value, textContent]
    );
    const { onNativeOptionAdd, onNativeOptionRemove } = nativeOptionsContext;
    useLayoutEffect2(() => {
      onNativeOptionAdd(nativeOption);
      return () => onNativeOptionRemove(nativeOption);
    }, [onNativeOptionAdd, onNativeOptionRemove, nativeOption]);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.span, { id: itemContext.textId, ...itemTextProps, ref: composedRefs }),
      itemContext.isSelected && context.valueNode && !context.valueNodeHasChildren ? reactDomExports.createPortal(itemTextProps.children, context.valueNode) : null
    ] });
  }
);
SelectItemText.displayName = ITEM_TEXT_NAME;
var ITEM_INDICATOR_NAME = "SelectItemIndicator";
var SelectItemIndicator = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, ...itemIndicatorProps } = props;
    const itemContext = useSelectItemContext(ITEM_INDICATOR_NAME, __scopeSelect);
    return itemContext.isSelected ? /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.span, { "aria-hidden": true, ...itemIndicatorProps, ref: forwardedRef }) : null;
  }
);
SelectItemIndicator.displayName = ITEM_INDICATOR_NAME;
var SCROLL_UP_BUTTON_NAME = "SelectScrollUpButton";
var SelectScrollUpButton$1 = reactExports.forwardRef((props, forwardedRef) => {
  const contentContext = useSelectContentContext(SCROLL_UP_BUTTON_NAME, props.__scopeSelect);
  const viewportContext = useSelectViewportContext(SCROLL_UP_BUTTON_NAME, props.__scopeSelect);
  const [canScrollUp, setCanScrollUp] = reactExports.useState(false);
  const composedRefs = useComposedRefs(forwardedRef, viewportContext.onScrollButtonChange);
  useLayoutEffect2(() => {
    if (contentContext.viewport && contentContext.isPositioned) {
      let handleScroll2 = function() {
        const canScrollUp2 = viewport.scrollTop > 0;
        setCanScrollUp(canScrollUp2);
      };
      const viewport = contentContext.viewport;
      handleScroll2();
      viewport.addEventListener("scroll", handleScroll2);
      return () => viewport.removeEventListener("scroll", handleScroll2);
    }
  }, [contentContext.viewport, contentContext.isPositioned]);
  return canScrollUp ? /* @__PURE__ */ jsxRuntimeExports.jsx(
    SelectScrollButtonImpl,
    {
      ...props,
      ref: composedRefs,
      onAutoScroll: () => {
        const { viewport, selectedItem } = contentContext;
        if (viewport && selectedItem) {
          viewport.scrollTop = viewport.scrollTop - selectedItem.offsetHeight;
        }
      }
    }
  ) : null;
});
SelectScrollUpButton$1.displayName = SCROLL_UP_BUTTON_NAME;
var SCROLL_DOWN_BUTTON_NAME = "SelectScrollDownButton";
var SelectScrollDownButton$1 = reactExports.forwardRef((props, forwardedRef) => {
  const contentContext = useSelectContentContext(SCROLL_DOWN_BUTTON_NAME, props.__scopeSelect);
  const viewportContext = useSelectViewportContext(SCROLL_DOWN_BUTTON_NAME, props.__scopeSelect);
  const [canScrollDown, setCanScrollDown] = reactExports.useState(false);
  const composedRefs = useComposedRefs(forwardedRef, viewportContext.onScrollButtonChange);
  useLayoutEffect2(() => {
    if (contentContext.viewport && contentContext.isPositioned) {
      let handleScroll2 = function() {
        const maxScroll = viewport.scrollHeight - viewport.clientHeight;
        const canScrollDown2 = Math.ceil(viewport.scrollTop) < maxScroll;
        setCanScrollDown(canScrollDown2);
      };
      const viewport = contentContext.viewport;
      handleScroll2();
      viewport.addEventListener("scroll", handleScroll2);
      return () => viewport.removeEventListener("scroll", handleScroll2);
    }
  }, [contentContext.viewport, contentContext.isPositioned]);
  return canScrollDown ? /* @__PURE__ */ jsxRuntimeExports.jsx(
    SelectScrollButtonImpl,
    {
      ...props,
      ref: composedRefs,
      onAutoScroll: () => {
        const { viewport, selectedItem } = contentContext;
        if (viewport && selectedItem) {
          viewport.scrollTop = viewport.scrollTop + selectedItem.offsetHeight;
        }
      }
    }
  ) : null;
});
SelectScrollDownButton$1.displayName = SCROLL_DOWN_BUTTON_NAME;
var SelectScrollButtonImpl = reactExports.forwardRef((props, forwardedRef) => {
  const { __scopeSelect, onAutoScroll, ...scrollIndicatorProps } = props;
  const contentContext = useSelectContentContext("SelectScrollButton", __scopeSelect);
  const autoScrollTimerRef = reactExports.useRef(null);
  const getItems = useCollection(__scopeSelect);
  const clearAutoScrollTimer = reactExports.useCallback(() => {
    if (autoScrollTimerRef.current !== null) {
      window.clearInterval(autoScrollTimerRef.current);
      autoScrollTimerRef.current = null;
    }
  }, []);
  reactExports.useEffect(() => {
    return () => clearAutoScrollTimer();
  }, [clearAutoScrollTimer]);
  useLayoutEffect2(() => {
    const activeItem = getItems().find((item) => item.ref.current === document.activeElement);
    activeItem?.ref.current?.scrollIntoView({ block: "nearest" });
  }, [getItems]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    Primitive$1.div,
    {
      "aria-hidden": true,
      ...scrollIndicatorProps,
      ref: forwardedRef,
      style: { flexShrink: 0, ...scrollIndicatorProps.style },
      onPointerDown: composeEventHandlers(scrollIndicatorProps.onPointerDown, () => {
        if (autoScrollTimerRef.current === null) {
          autoScrollTimerRef.current = window.setInterval(onAutoScroll, 50);
        }
      }),
      onPointerMove: composeEventHandlers(scrollIndicatorProps.onPointerMove, () => {
        contentContext.onItemLeave?.();
        if (autoScrollTimerRef.current === null) {
          autoScrollTimerRef.current = window.setInterval(onAutoScroll, 50);
        }
      }),
      onPointerLeave: composeEventHandlers(scrollIndicatorProps.onPointerLeave, () => {
        clearAutoScrollTimer();
      })
    }
  );
});
var SEPARATOR_NAME = "SelectSeparator";
var SelectSeparator$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, ...separatorProps } = props;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Primitive$1.div, { "aria-hidden": true, ...separatorProps, ref: forwardedRef });
  }
);
SelectSeparator$1.displayName = SEPARATOR_NAME;
var ARROW_NAME$1 = "SelectArrow";
var SelectArrow = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, ...arrowProps } = props;
    const popperScope = usePopperScope$1(__scopeSelect);
    const context = useSelectContext(ARROW_NAME$1, __scopeSelect);
    const contentContext = useSelectContentContext(ARROW_NAME$1, __scopeSelect);
    return context.open && contentContext.position === "popper" ? /* @__PURE__ */ jsxRuntimeExports.jsx(Arrow, { ...popperScope, ...arrowProps, ref: forwardedRef }) : null;
  }
);
SelectArrow.displayName = ARROW_NAME$1;
var BUBBLE_INPUT_NAME$2 = "SelectBubbleInput";
var SelectBubbleInput = reactExports.forwardRef(
  ({ __scopeSelect, value, ...props }, forwardedRef) => {
    const ref2 = reactExports.useRef(null);
    const composedRefs = useComposedRefs(forwardedRef, ref2);
    const prevValue = usePrevious(value);
    reactExports.useEffect(() => {
      const select = ref2.current;
      if (!select) return;
      const selectProto = window.HTMLSelectElement.prototype;
      const descriptor = Object.getOwnPropertyDescriptor(
        selectProto,
        "value"
      );
      const setValue = descriptor.set;
      if (prevValue !== value && setValue) {
        const event = new Event("change", { bubbles: true });
        setValue.call(select, value);
        select.dispatchEvent(event);
      }
    }, [prevValue, value]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.select,
      {
        ...props,
        style: { ...VISUALLY_HIDDEN_STYLES, ...props.style },
        ref: composedRefs,
        defaultValue: value
      }
    );
  }
);
SelectBubbleInput.displayName = BUBBLE_INPUT_NAME$2;
function shouldShowPlaceholder(value) {
  return value === "" || value === void 0;
}
function useTypeaheadSearch(onSearchChange) {
  const handleSearchChange = useCallbackRef$1(onSearchChange);
  const searchRef = reactExports.useRef("");
  const timerRef = reactExports.useRef(0);
  const handleTypeaheadSearch = reactExports.useCallback(
    (key) => {
      const search = searchRef.current + key;
      handleSearchChange(search);
      (function updateSearch(value) {
        searchRef.current = value;
        window.clearTimeout(timerRef.current);
        if (value !== "") timerRef.current = window.setTimeout(() => updateSearch(""), 1e3);
      })(search);
    },
    [handleSearchChange]
  );
  const resetTypeahead = reactExports.useCallback(() => {
    searchRef.current = "";
    window.clearTimeout(timerRef.current);
  }, []);
  reactExports.useEffect(() => {
    return () => window.clearTimeout(timerRef.current);
  }, []);
  return [searchRef, handleTypeaheadSearch, resetTypeahead];
}
function findNextItem(items2, search, currentItem) {
  const isRepeated = search.length > 1 && Array.from(search).every((char) => char === search[0]);
  const normalizedSearch = isRepeated ? search[0] : search;
  const currentItemIndex = currentItem ? items2.indexOf(currentItem) : -1;
  let wrappedItems = wrapArray(items2, Math.max(currentItemIndex, 0));
  const excludeCurrentItem = normalizedSearch.length === 1;
  if (excludeCurrentItem) wrappedItems = wrappedItems.filter((v2) => v2 !== currentItem);
  const nextItem = wrappedItems.find(
    (item) => item.textValue.toLowerCase().startsWith(normalizedSearch.toLowerCase())
  );
  return nextItem !== currentItem ? nextItem : void 0;
}
function wrapArray(array2, startIndex) {
  return array2.map((_2, index2) => array2[(startIndex + index2) % array2.length]);
}
var Root2 = Select$1;
var Trigger$1 = SelectTrigger$1;
var Value = SelectValue$1;
var Icon = SelectIcon;
var Portal = SelectPortal;
var Content2$1 = SelectContent$1;
var Viewport = SelectViewport;
var Label = SelectLabel$1;
var Item = SelectItem$1;
var ItemText = SelectItemText;
var ItemIndicator = SelectItemIndicator;
var ScrollUpButton = SelectScrollUpButton$1;
var ScrollDownButton = SelectScrollDownButton$1;
var Separator = SelectSeparator$1;
const Select = Root2;
const SelectValue = Value;
const SelectTrigger = reactExports.forwardRef(({ className, children, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
  Trigger$1,
  {
    ref: ref2,
    className: cn$1(
      "flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 hover:border-[#646cff] hover:border-1",
      className
    ),
    ...props,
    children: [
      children,
      /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(CaretSortIcon, { className: "h-4 w-4 opacity-50" }) })
    ]
  }
));
SelectTrigger.displayName = Trigger$1.displayName;
const SelectScrollUpButton = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  ScrollUpButton,
  {
    ref: ref2,
    className: cn$1(
      "flex cursor-default items-center justify-center py-1",
      className
    ),
    ...props,
    children: /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronUpIcon, {})
  }
));
SelectScrollUpButton.displayName = ScrollUpButton.displayName;
const SelectScrollDownButton = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  ScrollDownButton,
  {
    ref: ref2,
    className: cn$1(
      "flex cursor-default items-center justify-center py-1",
      className
    ),
    ...props,
    children: /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDownIcon, {})
  }
));
SelectScrollDownButton.displayName = ScrollDownButton.displayName;
const SelectContent = reactExports.forwardRef(({ className, children, position = "popper", ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(Portal, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
  Content2$1,
  {
    ref: ref2,
    className: cn$1(
      "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
      position === "popper" && "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
      className
    ),
    position,
    ...props,
    children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(SelectScrollUpButton, {}),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Viewport,
        {
          className: cn$1(
            "p-1",
            position === "popper" && "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
          ),
          children
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(SelectScrollDownButton, {})
    ]
  }
) }));
SelectContent.displayName = Content2$1.displayName;
const SelectLabel = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Label,
  {
    ref: ref2,
    className: cn$1("px-2 py-1.5 text-sm font-semibold", className),
    ...props
  }
));
SelectLabel.displayName = Label.displayName;
const SelectItem = reactExports.forwardRef(({ className, children, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
  Item,
  {
    ref: ref2,
    className: cn$1(
      "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      className
    ),
    ...props,
    children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "absolute right-2 flex h-3.5 w-3.5 items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ItemIndicator, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CheckIcon, { className: "h-4 w-4" }) }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ItemText, { children })
    ]
  }
));
SelectItem.displayName = Item.displayName;
const SelectSeparator = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Separator,
  {
    ref: ref2,
    className: cn$1("-mx-1 my-1 h-px bg-muted", className),
    ...props
  }
));
SelectSeparator.displayName = Separator.displayName;
const useTheme = () => {
  const [theme, setTheme] = reactExports.useState(() => {
    const savedTheme = localStorage.getItem("theme");
    return savedTheme || "system";
  });
  reactExports.useEffect(() => {
    const darkModeMediaQuery = window.matchMedia(
      "(prefers-color-scheme: dark)"
    );
    const handleDarkModeChange = (e2) => {
      if (theme === "system") {
        updateDocumentTheme(e2.matches ? "dark" : "light");
      }
    };
    const updateDocumentTheme = (newTheme) => {
      document.documentElement.classList.toggle("dark", newTheme === "dark");
    };
    if (theme === "system") {
      updateDocumentTheme(darkModeMediaQuery.matches ? "dark" : "light");
    } else {
      updateDocumentTheme(theme);
    }
    darkModeMediaQuery.addEventListener("change", handleDarkModeChange);
    return () => {
      darkModeMediaQuery.removeEventListener("change", handleDarkModeChange);
    };
  }, [theme]);
  const setThemeWithSideEffect = reactExports.useCallback((newTheme) => {
    setTheme(newTheme);
    localStorage.setItem("theme", newTheme);
    if (newTheme !== "system") {
      document.documentElement.classList.toggle("dark", newTheme === "dark");
    }
  }, []);
  return reactExports.useMemo(
    () => [theme, setThemeWithSideEffect],
    [theme, setThemeWithSideEffect]
  );
};
const version = "0.22.0";
var SLOTTABLE_IDENTIFIER = /* @__PURE__ */ Symbol("radix.slottable");
// @__NO_SIDE_EFFECTS__
function createSlottable(ownerName) {
  const Slottable2 = ({ children }) => {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children });
  };
  Slottable2.displayName = `${ownerName}.Slottable`;
  Slottable2.__radixId = SLOTTABLE_IDENTIFIER;
  return Slottable2;
}
var [createTooltipContext] = createContextScope("Tooltip", [
  createPopperScope
]);
var usePopperScope = createPopperScope();
var PROVIDER_NAME = "TooltipProvider";
var DEFAULT_DELAY_DURATION = 700;
var TOOLTIP_OPEN = "tooltip.open";
var [TooltipProviderContextProvider, useTooltipProviderContext] = createTooltipContext(PROVIDER_NAME);
var TooltipProvider$1 = (props) => {
  const {
    __scopeTooltip,
    delayDuration = DEFAULT_DELAY_DURATION,
    skipDelayDuration = 300,
    disableHoverableContent = false,
    children
  } = props;
  const isOpenDelayedRef = reactExports.useRef(true);
  const isPointerInTransitRef = reactExports.useRef(false);
  const skipDelayTimerRef = reactExports.useRef(0);
  reactExports.useEffect(() => {
    const skipDelayTimer = skipDelayTimerRef.current;
    return () => window.clearTimeout(skipDelayTimer);
  }, []);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    TooltipProviderContextProvider,
    {
      scope: __scopeTooltip,
      isOpenDelayedRef,
      delayDuration,
      onOpen: reactExports.useCallback(() => {
        window.clearTimeout(skipDelayTimerRef.current);
        isOpenDelayedRef.current = false;
      }, []),
      onClose: reactExports.useCallback(() => {
        window.clearTimeout(skipDelayTimerRef.current);
        skipDelayTimerRef.current = window.setTimeout(
          () => isOpenDelayedRef.current = true,
          skipDelayDuration
        );
      }, [skipDelayDuration]),
      isPointerInTransitRef,
      onPointerInTransitChange: reactExports.useCallback((inTransit) => {
        isPointerInTransitRef.current = inTransit;
      }, []),
      disableHoverableContent,
      children
    }
  );
};
TooltipProvider$1.displayName = PROVIDER_NAME;
var TOOLTIP_NAME = "Tooltip";
var [TooltipContextProvider, useTooltipContext] = createTooltipContext(TOOLTIP_NAME);
var Tooltip$1 = (props) => {
  const {
    __scopeTooltip,
    children,
    open: openProp,
    defaultOpen,
    onOpenChange,
    disableHoverableContent: disableHoverableContentProp,
    delayDuration: delayDurationProp
  } = props;
  const providerContext = useTooltipProviderContext(TOOLTIP_NAME, props.__scopeTooltip);
  const popperScope = usePopperScope(__scopeTooltip);
  const [trigger, setTrigger] = reactExports.useState(null);
  const contentId = useId();
  const openTimerRef = reactExports.useRef(0);
  const disableHoverableContent = disableHoverableContentProp ?? providerContext.disableHoverableContent;
  const delayDuration = delayDurationProp ?? providerContext.delayDuration;
  const wasOpenDelayedRef = reactExports.useRef(false);
  const [open, setOpen] = useControllableState({
    prop: openProp,
    defaultProp: defaultOpen ?? false,
    onChange: (open2) => {
      if (open2) {
        providerContext.onOpen();
        document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN));
      } else {
        providerContext.onClose();
      }
      onOpenChange?.(open2);
    },
    caller: TOOLTIP_NAME
  });
  const stateAttribute = reactExports.useMemo(() => {
    return open ? wasOpenDelayedRef.current ? "delayed-open" : "instant-open" : "closed";
  }, [open]);
  const handleOpen = reactExports.useCallback(() => {
    window.clearTimeout(openTimerRef.current);
    openTimerRef.current = 0;
    wasOpenDelayedRef.current = false;
    setOpen(true);
  }, [setOpen]);
  const handleClose = reactExports.useCallback(() => {
    window.clearTimeout(openTimerRef.current);
    openTimerRef.current = 0;
    setOpen(false);
  }, [setOpen]);
  const handleDelayedOpen = reactExports.useCallback(() => {
    window.clearTimeout(openTimerRef.current);
    openTimerRef.current = window.setTimeout(() => {
      wasOpenDelayedRef.current = true;
      setOpen(true);
      openTimerRef.current = 0;
    }, delayDuration);
  }, [delayDuration, setOpen]);
  reactExports.useEffect(() => {
    return () => {
      if (openTimerRef.current) {
        window.clearTimeout(openTimerRef.current);
        openTimerRef.current = 0;
      }
    };
  }, []);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Root2$2, { ...popperScope, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
    TooltipContextProvider,
    {
      scope: __scopeTooltip,
      contentId,
      open,
      stateAttribute,
      trigger,
      onTriggerChange: setTrigger,
      onTriggerEnter: reactExports.useCallback(() => {
        if (providerContext.isOpenDelayedRef.current) handleDelayedOpen();
        else handleOpen();
      }, [providerContext.isOpenDelayedRef, handleDelayedOpen, handleOpen]),
      onTriggerLeave: reactExports.useCallback(() => {
        if (disableHoverableContent) {
          handleClose();
        } else {
          window.clearTimeout(openTimerRef.current);
          openTimerRef.current = 0;
        }
      }, [handleClose, disableHoverableContent]),
      onOpen: handleOpen,
      onClose: handleClose,
      disableHoverableContent,
      children
    }
  ) });
};
Tooltip$1.displayName = TOOLTIP_NAME;
var TRIGGER_NAME$1 = "TooltipTrigger";
var TooltipTrigger$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeTooltip, ...triggerProps } = props;
    const context = useTooltipContext(TRIGGER_NAME$1, __scopeTooltip);
    const providerContext = useTooltipProviderContext(TRIGGER_NAME$1, __scopeTooltip);
    const popperScope = usePopperScope(__scopeTooltip);
    const ref2 = reactExports.useRef(null);
    const composedRefs = useComposedRefs(forwardedRef, ref2, context.onTriggerChange);
    const isPointerDownRef = reactExports.useRef(false);
    const hasPointerMoveOpenedRef = reactExports.useRef(false);
    const handlePointerUp = reactExports.useCallback(() => isPointerDownRef.current = false, []);
    reactExports.useEffect(() => {
      return () => document.removeEventListener("pointerup", handlePointerUp);
    }, [handlePointerUp]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Anchor, { asChild: true, ...popperScope, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.button,
      {
        "aria-describedby": context.open ? context.contentId : void 0,
        "data-state": context.stateAttribute,
        ...triggerProps,
        ref: composedRefs,
        onPointerMove: composeEventHandlers(props.onPointerMove, (event) => {
          if (event.pointerType === "touch") return;
          if (!hasPointerMoveOpenedRef.current && !providerContext.isPointerInTransitRef.current) {
            context.onTriggerEnter();
            hasPointerMoveOpenedRef.current = true;
          }
        }),
        onPointerLeave: composeEventHandlers(props.onPointerLeave, () => {
          context.onTriggerLeave();
          hasPointerMoveOpenedRef.current = false;
        }),
        onPointerDown: composeEventHandlers(props.onPointerDown, () => {
          if (context.open) {
            context.onClose();
          }
          isPointerDownRef.current = true;
          document.addEventListener("pointerup", handlePointerUp, { once: true });
        }),
        onFocus: composeEventHandlers(props.onFocus, () => {
          if (!isPointerDownRef.current) context.onOpen();
        }),
        onBlur: composeEventHandlers(props.onBlur, context.onClose),
        onClick: composeEventHandlers(props.onClick, context.onClose)
      }
    ) });
  }
);
TooltipTrigger$1.displayName = TRIGGER_NAME$1;
var PORTAL_NAME = "TooltipPortal";
var [PortalProvider, usePortalContext] = createTooltipContext(PORTAL_NAME, {
  forceMount: void 0
});
var CONTENT_NAME = "TooltipContent";
var TooltipContent$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const portalContext = usePortalContext(CONTENT_NAME, props.__scopeTooltip);
    const { forceMount = portalContext.forceMount, side = "top", ...contentProps } = props;
    const context = useTooltipContext(CONTENT_NAME, props.__scopeTooltip);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Presence, { present: forceMount || context.open, children: context.disableHoverableContent ? /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipContentImpl, { side, ...contentProps, ref: forwardedRef }) : /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipContentHoverable, { side, ...contentProps, ref: forwardedRef }) });
  }
);
var TooltipContentHoverable = reactExports.forwardRef((props, forwardedRef) => {
  const context = useTooltipContext(CONTENT_NAME, props.__scopeTooltip);
  const providerContext = useTooltipProviderContext(CONTENT_NAME, props.__scopeTooltip);
  const ref2 = reactExports.useRef(null);
  const composedRefs = useComposedRefs(forwardedRef, ref2);
  const [pointerGraceArea, setPointerGraceArea] = reactExports.useState(null);
  const { trigger, onClose } = context;
  const content = ref2.current;
  const { onPointerInTransitChange } = providerContext;
  const handleRemoveGraceArea = reactExports.useCallback(() => {
    setPointerGraceArea(null);
    onPointerInTransitChange(false);
  }, [onPointerInTransitChange]);
  const handleCreateGraceArea = reactExports.useCallback(
    (event, hoverTarget) => {
      const currentTarget = event.currentTarget;
      const exitPoint = { x: event.clientX, y: event.clientY };
      const exitSide = getExitSideFromRect(exitPoint, currentTarget.getBoundingClientRect());
      const paddedExitPoints = getPaddedExitPoints(exitPoint, exitSide);
      const hoverTargetPoints = getPointsFromRect(hoverTarget.getBoundingClientRect());
      const graceArea = getHull([...paddedExitPoints, ...hoverTargetPoints]);
      setPointerGraceArea(graceArea);
      onPointerInTransitChange(true);
    },
    [onPointerInTransitChange]
  );
  reactExports.useEffect(() => {
    return () => handleRemoveGraceArea();
  }, [handleRemoveGraceArea]);
  reactExports.useEffect(() => {
    if (trigger && content) {
      const handleTriggerLeave = (event) => handleCreateGraceArea(event, content);
      const handleContentLeave = (event) => handleCreateGraceArea(event, trigger);
      trigger.addEventListener("pointerleave", handleTriggerLeave);
      content.addEventListener("pointerleave", handleContentLeave);
      return () => {
        trigger.removeEventListener("pointerleave", handleTriggerLeave);
        content.removeEventListener("pointerleave", handleContentLeave);
      };
    }
  }, [trigger, content, handleCreateGraceArea, handleRemoveGraceArea]);
  reactExports.useEffect(() => {
    if (pointerGraceArea) {
      const handleTrackPointerGrace = (event) => {
        const target = event.target;
        const pointerPosition = { x: event.clientX, y: event.clientY };
        const hasEnteredTarget = trigger?.contains(target) || content?.contains(target);
        const isPointerOutsideGraceArea = !isPointInPolygon(pointerPosition, pointerGraceArea);
        if (hasEnteredTarget) {
          handleRemoveGraceArea();
        } else if (isPointerOutsideGraceArea) {
          handleRemoveGraceArea();
          onClose();
        }
      };
      document.addEventListener("pointermove", handleTrackPointerGrace);
      return () => document.removeEventListener("pointermove", handleTrackPointerGrace);
    }
  }, [trigger, content, pointerGraceArea, onClose, handleRemoveGraceArea]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipContentImpl, { ...props, ref: composedRefs });
});
var [VisuallyHiddenContentContextProvider, useVisuallyHiddenContentContext] = createTooltipContext(TOOLTIP_NAME, { isInside: false });
var Slottable = /* @__PURE__ */ createSlottable("TooltipContent");
var TooltipContentImpl = reactExports.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeTooltip,
      children,
      "aria-label": ariaLabel,
      onEscapeKeyDown,
      onPointerDownOutside,
      ...contentProps
    } = props;
    const context = useTooltipContext(CONTENT_NAME, __scopeTooltip);
    const popperScope = usePopperScope(__scopeTooltip);
    const { onClose } = context;
    reactExports.useEffect(() => {
      document.addEventListener(TOOLTIP_OPEN, onClose);
      return () => document.removeEventListener(TOOLTIP_OPEN, onClose);
    }, [onClose]);
    reactExports.useEffect(() => {
      if (context.trigger) {
        const handleScroll2 = (event) => {
          const target = event.target;
          if (target?.contains(context.trigger)) onClose();
        };
        window.addEventListener("scroll", handleScroll2, { capture: true });
        return () => window.removeEventListener("scroll", handleScroll2, { capture: true });
      }
    }, [context.trigger, onClose]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      DismissableLayer,
      {
        asChild: true,
        disableOutsidePointerEvents: false,
        onEscapeKeyDown,
        onPointerDownOutside,
        onFocusOutside: (event) => event.preventDefault(),
        onDismiss: onClose,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Content,
          {
            "data-state": context.stateAttribute,
            ...popperScope,
            ...contentProps,
            ref: forwardedRef,
            style: {
              ...contentProps.style,
              // re-namespace exposed content custom properties
              ...{
                "--radix-tooltip-content-transform-origin": "var(--radix-popper-transform-origin)",
                "--radix-tooltip-content-available-width": "var(--radix-popper-available-width)",
                "--radix-tooltip-content-available-height": "var(--radix-popper-available-height)",
                "--radix-tooltip-trigger-width": "var(--radix-popper-anchor-width)",
                "--radix-tooltip-trigger-height": "var(--radix-popper-anchor-height)"
              }
            },
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Slottable, { children }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(VisuallyHiddenContentContextProvider, { scope: __scopeTooltip, isInside: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Root$5, { id: context.contentId, role: "tooltip", children: ariaLabel || children }) })
            ]
          }
        )
      }
    );
  }
);
TooltipContent$1.displayName = CONTENT_NAME;
var ARROW_NAME = "TooltipArrow";
var TooltipArrow = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeTooltip, ...arrowProps } = props;
    const popperScope = usePopperScope(__scopeTooltip);
    const visuallyHiddenContentContext = useVisuallyHiddenContentContext(
      ARROW_NAME,
      __scopeTooltip
    );
    return visuallyHiddenContentContext.isInside ? null : /* @__PURE__ */ jsxRuntimeExports.jsx(Arrow, { ...popperScope, ...arrowProps, ref: forwardedRef });
  }
);
TooltipArrow.displayName = ARROW_NAME;
function getExitSideFromRect(point, rect) {
  const top = Math.abs(rect.top - point.y);
  const bottom = Math.abs(rect.bottom - point.y);
  const right = Math.abs(rect.right - point.x);
  const left = Math.abs(rect.left - point.x);
  switch (Math.min(top, bottom, right, left)) {
    case left:
      return "left";
    case right:
      return "right";
    case top:
      return "top";
    case bottom:
      return "bottom";
    default:
      throw new Error("unreachable");
  }
}
function getPaddedExitPoints(exitPoint, exitSide, padding = 5) {
  const paddedExitPoints = [];
  switch (exitSide) {
    case "top":
      paddedExitPoints.push(
        { x: exitPoint.x - padding, y: exitPoint.y + padding },
        { x: exitPoint.x + padding, y: exitPoint.y + padding }
      );
      break;
    case "bottom":
      paddedExitPoints.push(
        { x: exitPoint.x - padding, y: exitPoint.y - padding },
        { x: exitPoint.x + padding, y: exitPoint.y - padding }
      );
      break;
    case "left":
      paddedExitPoints.push(
        { x: exitPoint.x + padding, y: exitPoint.y - padding },
        { x: exitPoint.x + padding, y: exitPoint.y + padding }
      );
      break;
    case "right":
      paddedExitPoints.push(
        { x: exitPoint.x - padding, y: exitPoint.y - padding },
        { x: exitPoint.x - padding, y: exitPoint.y + padding }
      );
      break;
  }
  return paddedExitPoints;
}
function getPointsFromRect(rect) {
  const { top, right, bottom, left } = rect;
  return [
    { x: left, y: top },
    { x: right, y: top },
    { x: right, y: bottom },
    { x: left, y: bottom }
  ];
}
function isPointInPolygon(point, polygon) {
  const { x: x2, y } = point;
  let inside = false;
  for (let i2 = 0, j = polygon.length - 1; i2 < polygon.length; j = i2++) {
    const ii2 = polygon[i2];
    const jj = polygon[j];
    const xi2 = ii2.x;
    const yi2 = ii2.y;
    const xj = jj.x;
    const yj = jj.y;
    const intersect = yi2 > y !== yj > y && x2 < (xj - xi2) * (y - yi2) / (yj - yi2) + xi2;
    if (intersect) inside = !inside;
  }
  return inside;
}
function getHull(points) {
  const newPoints = points.slice();
  newPoints.sort((a2, b2) => {
    if (a2.x < b2.x) return -1;
    else if (a2.x > b2.x) return 1;
    else if (a2.y < b2.y) return -1;
    else if (a2.y > b2.y) return 1;
    else return 0;
  });
  return getHullPresorted(newPoints);
}
function getHullPresorted(points) {
  if (points.length <= 1) return points.slice();
  const upperHull = [];
  for (let i2 = 0; i2 < points.length; i2++) {
    const p2 = points[i2];
    while (upperHull.length >= 2) {
      const q2 = upperHull[upperHull.length - 1];
      const r2 = upperHull[upperHull.length - 2];
      if ((q2.x - r2.x) * (p2.y - r2.y) >= (q2.y - r2.y) * (p2.x - r2.x)) upperHull.pop();
      else break;
    }
    upperHull.push(p2);
  }
  upperHull.pop();
  const lowerHull = [];
  for (let i2 = points.length - 1; i2 >= 0; i2--) {
    const p2 = points[i2];
    while (lowerHull.length >= 2) {
      const q2 = lowerHull[lowerHull.length - 1];
      const r2 = lowerHull[lowerHull.length - 2];
      if ((q2.x - r2.x) * (p2.y - r2.y) >= (q2.y - r2.y) * (p2.x - r2.x)) lowerHull.pop();
      else break;
    }
    lowerHull.push(p2);
  }
  lowerHull.pop();
  if (upperHull.length === 1 && lowerHull.length === 1 && upperHull[0].x === lowerHull[0].x && upperHull[0].y === lowerHull[0].y) {
    return upperHull;
  } else {
    return upperHull.concat(lowerHull);
  }
}
var Provider = TooltipProvider$1;
var Root3 = Tooltip$1;
var Trigger = TooltipTrigger$1;
var Content2 = TooltipContent$1;
const TooltipProvider = Provider;
const Tooltip = Root3;
const TooltipTrigger = Trigger;
const TooltipContent = reactExports.forwardRef(({ className, sideOffset = 4, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Content2,
  {
    ref: ref2,
    sideOffset,
    className: cn$1(
      "z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",
      className
    ),
    ...props
  }
));
TooltipContent.displayName = Content2.displayName;
const Textarea = reactExports.forwardRef(
  ({ className, ...props }, ref2) => {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "textarea",
      {
        className: cn$1(
          "flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
          className
        ),
        ref: ref2,
        ...props
      }
    );
  }
);
Textarea.displayName = "Textarea";
var SWITCH_NAME = "Switch";
var [createSwitchContext] = createContextScope(SWITCH_NAME);
var [SwitchProvider, useSwitchContext] = createSwitchContext(SWITCH_NAME);
var Switch$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeSwitch,
      name: name2,
      checked: checkedProp,
      defaultChecked,
      required: required2,
      disabled,
      value = "on",
      onCheckedChange,
      form,
      ...switchProps
    } = props;
    const [button, setButton] = reactExports.useState(null);
    const composedRefs = useComposedRefs(forwardedRef, (node) => setButton(node));
    const hasConsumerStoppedPropagationRef = reactExports.useRef(false);
    const isFormControl = button ? form || !!button.closest("form") : true;
    const [checked, setChecked] = useControllableState({
      prop: checkedProp,
      defaultProp: defaultChecked ?? false,
      onChange: onCheckedChange,
      caller: SWITCH_NAME
    });
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(SwitchProvider, { scope: __scopeSwitch, checked, disabled, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Primitive$1.button,
        {
          type: "button",
          role: "switch",
          "aria-checked": checked,
          "aria-required": required2,
          "data-state": getState$1(checked),
          "data-disabled": disabled ? "" : void 0,
          disabled,
          value,
          ...switchProps,
          ref: composedRefs,
          onClick: composeEventHandlers(props.onClick, (event) => {
            setChecked((prevChecked) => !prevChecked);
            if (isFormControl) {
              hasConsumerStoppedPropagationRef.current = event.isPropagationStopped();
              if (!hasConsumerStoppedPropagationRef.current) event.stopPropagation();
            }
          })
        }
      ),
      isFormControl && /* @__PURE__ */ jsxRuntimeExports.jsx(
        SwitchBubbleInput,
        {
          control: button,
          bubbles: !hasConsumerStoppedPropagationRef.current,
          name: name2,
          value,
          checked,
          required: required2,
          disabled,
          form,
          style: { transform: "translateX(-100%)" }
        }
      )
    ] });
  }
);
Switch$1.displayName = SWITCH_NAME;
var THUMB_NAME = "SwitchThumb";
var SwitchThumb = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSwitch, ...thumbProps } = props;
    const context = useSwitchContext(THUMB_NAME, __scopeSwitch);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.span,
      {
        "data-state": getState$1(context.checked),
        "data-disabled": context.disabled ? "" : void 0,
        ...thumbProps,
        ref: forwardedRef
      }
    );
  }
);
SwitchThumb.displayName = THUMB_NAME;
var BUBBLE_INPUT_NAME$1 = "SwitchBubbleInput";
var SwitchBubbleInput = reactExports.forwardRef(
  ({
    __scopeSwitch,
    control,
    checked,
    bubbles = true,
    ...props
  }, forwardedRef) => {
    const ref2 = reactExports.useRef(null);
    const composedRefs = useComposedRefs(ref2, forwardedRef);
    const prevChecked = usePrevious(checked);
    const controlSize = useSize(control);
    reactExports.useEffect(() => {
      const input = ref2.current;
      if (!input) return;
      const inputProto = window.HTMLInputElement.prototype;
      const descriptor = Object.getOwnPropertyDescriptor(
        inputProto,
        "checked"
      );
      const setChecked = descriptor.set;
      if (prevChecked !== checked && setChecked) {
        const event = new Event("click", { bubbles });
        setChecked.call(input, checked);
        input.dispatchEvent(event);
      }
    }, [prevChecked, checked, bubbles]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        type: "checkbox",
        "aria-hidden": true,
        defaultChecked: checked,
        ...props,
        tabIndex: -1,
        ref: composedRefs,
        style: {
          ...props.style,
          ...controlSize,
          position: "absolute",
          pointerEvents: "none",
          opacity: 0,
          margin: 0
        }
      }
    );
  }
);
SwitchBubbleInput.displayName = BUBBLE_INPUT_NAME$1;
function getState$1(checked) {
  return checked ? "checked" : "unchecked";
}
var Root = Switch$1;
var Thumb = SwitchThumb;
const Switch = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Root,
  {
    className: cn$1(
      "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
      className
    ),
    ...props,
    ref: ref2,
    children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Thumb,
      {
        className: cn$1(
          "pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"
        )
      }
    )
  }
));
Switch.displayName = Root.displayName;
const createEmptyHeader = () => ({
  name: "",
  value: "",
  enabled: true
});
const createHeaderFromBearerToken = (bearerToken, headerName) => ({
  name: headerName || "Authorization",
  value: headerName?.toLowerCase() === "authorization" || !headerName ? `Bearer ${bearerToken}` : bearerToken,
  enabled: true
});
const migrateFromLegacyAuth = (bearerToken, headerName) => {
  return bearerToken ? [createHeaderFromBearerToken(bearerToken, headerName)] : [];
};
const CustomHeaders = ({
  headers,
  onChange,
  className
}) => {
  const [isJsonMode, setIsJsonMode] = reactExports.useState(false);
  const [jsonValue, setJsonValue] = reactExports.useState("");
  const [jsonError, setJsonError] = reactExports.useState(null);
  const [visibleValues, setVisibleValues] = reactExports.useState(/* @__PURE__ */ new Set());
  const updateHeader = (index2, field, value) => {
    const newHeaders = [...headers];
    newHeaders[index2] = { ...newHeaders[index2], [field]: value };
    onChange(newHeaders);
  };
  const addHeader = () => {
    onChange([...headers, createEmptyHeader()]);
  };
  const removeHeader = (index2) => {
    const newHeaders = headers.filter((_2, i2) => i2 !== index2);
    onChange(newHeaders);
  };
  const toggleValueVisibility = (index2) => {
    const newVisible = new Set(visibleValues);
    if (newVisible.has(index2)) {
      newVisible.delete(index2);
    } else {
      newVisible.add(index2);
    }
    setVisibleValues(newVisible);
  };
  const switchToJsonMode = () => {
    const jsonObject = {};
    headers.forEach((header) => {
      if (header.enabled && header.name.trim() && header.value.trim()) {
        jsonObject[header.name.trim()] = header.value.trim();
      }
    });
    setJsonValue(JSON.stringify(jsonObject, null, 2));
    setJsonError(null);
    setIsJsonMode(true);
  };
  const switchToFormMode = () => {
    try {
      const parsed = JSON.parse(jsonValue);
      if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
        setJsonError("JSON must be an object with string key-value pairs");
        return;
      }
      const newHeaders = Object.entries(parsed).map(
        ([name2, value]) => ({
          name: name2,
          value: String(value),
          enabled: true
        })
      );
      onChange(newHeaders);
      setJsonError(null);
      setIsJsonMode(false);
    } catch {
      setJsonError("Invalid JSON format");
    }
  };
  const handleJsonChange = (value) => {
    setJsonValue(value);
    setJsonError(null);
  };
  if (isJsonMode) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `space-y-3 ${className}`, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-sm font-semibold flex-shrink-0", children: "Custom Headers (JSON)" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            onClick: switchToFormMode,
            className: "flex-shrink-0",
            children: "Switch to Form"
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Textarea,
          {
            value: jsonValue,
            onChange: (e2) => handleJsonChange(e2.target.value),
            placeholder: '{\\n  "Authorization": "Bearer token123",\\n  "X-Tenant-ID": "acme-inc",\\n  "X-Environment": "staging"\\n}',
            className: "font-mono text-sm min-h-[100px] resize-none"
          }
        ),
        jsonError && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-red-600", children: jsonError }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-muted-foreground", children: "Enter headers as a JSON object with string key-value pairs." })
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `space-y-3 ${className}`, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-center gap-2", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-sm font-semibold flex-shrink-0", children: "Custom Headers" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-1 flex-shrink-0", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            onClick: switchToJsonMode,
            className: "text-xs px-2",
            children: "JSON"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            onClick: addHeader,
            className: "text-xs px-2",
            "data-testid": "add-header-button",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-3 h-3 mr-1" }),
              "Add"
            ]
          }
        )
      ] })
    ] }),
    headers.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-4 text-muted-foreground", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm", children: "No custom headers configured" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs mt-1", children: 'Click "Add" to get started' })
    ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2 max-h-[300px] overflow-y-auto", children: headers.map((header, index2) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: "flex items-start gap-2 p-2 border rounded-md",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Switch,
            {
              checked: header.enabled,
              onCheckedChange: (enabled) => updateHeader(index2, "enabled", enabled),
              className: "shrink-0 mt-2"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0 space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                placeholder: "Header Name",
                value: header.name,
                onChange: (e2) => updateHeader(index2, "name", e2.target.value),
                className: "font-mono text-xs",
                "data-testid": `header-name-input-${index2}`
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  placeholder: "Header Value",
                  value: header.value,
                  onChange: (e2) => updateHeader(index2, "value", e2.target.value),
                  type: visibleValues.has(index2) ? "text" : "password",
                  className: "font-mono text-xs pr-8",
                  "data-testid": `header-value-input-${index2}`
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  size: "sm",
                  onClick: () => toggleValueVisibility(index2),
                  className: "absolute right-1 top-1/2 -translate-y-1/2 h-6 w-6 p-0",
                  children: visibleValues.has(index2) ? /* @__PURE__ */ jsxRuntimeExports.jsx(EyeOff, { className: "w-3 h-3" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-3 h-3" })
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              onClick: () => removeHeader(index2),
              className: "shrink-0 text-red-600 hover:text-red-700 hover:bg-red-50 h-6 w-6 p-0 mt-2",
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-3 h-3" })
            }
          )
        ]
      },
      index2
    )) }),
    headers.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-muted-foreground", children: "Use the toggle to enable/disable headers. Only enabled headers with both name and value will be sent." })
  ] });
};
const Sidebar = ({
  connectionStatus,
  transportType,
  setTransportType,
  command,
  setCommand,
  args,
  setArgs,
  sseUrl,
  setSseUrl,
  env,
  setEnv,
  customHeaders,
  setCustomHeaders,
  oauthClientId,
  setOauthClientId,
  oauthClientSecret,
  setOauthClientSecret,
  oauthScope,
  setOauthScope,
  onConnect,
  onDisconnect,
  logLevel,
  sendLogLevelRequest,
  loggingSupported,
  config: config2,
  setConfig,
  connectionType,
  setConnectionType,
  serverImplementation
}) => {
  const [theme, setTheme] = useTheme();
  const [showEnvVars, setShowEnvVars] = reactExports.useState(false);
  const [showAuthConfig, setShowAuthConfig] = reactExports.useState(false);
  const [showConfig, setShowConfig] = reactExports.useState(false);
  const [shownEnvVars, setShownEnvVars] = reactExports.useState(/* @__PURE__ */ new Set());
  const [showClientSecret, setShowClientSecret] = reactExports.useState(false);
  const [copiedServerEntry, setCopiedServerEntry] = reactExports.useState(false);
  const [copiedServerFile, setCopiedServerFile] = reactExports.useState(false);
  const { toast: toast2 } = useToast();
  const connectionTypeTip = "Connect to server directly (requires CORS config on server) or via MCP Inspector Proxy";
  const reportError2 = reactExports.useCallback(
    (error) => {
      toast2({
        title: "Error",
        description: `Failed to copy config: ${error instanceof Error ? error.message : String(error)}`,
        variant: "destructive"
      });
    },
    [toast2]
  );
  const generateServerConfig = reactExports.useCallback(() => {
    if (transportType === "stdio") {
      return {
        command,
        args: args.trim() ? args.split(/\s+/) : [],
        env: { ...env }
      };
    }
    if (transportType === "sse") {
      return {
        type: "sse",
        url: sseUrl,
        note: "For SSE connections, add this URL directly in your MCP Client"
      };
    }
    if (transportType === "streamable-http") {
      return {
        type: "streamable-http",
        url: sseUrl,
        note: "For Streamable HTTP connections, add this URL directly in your MCP Client"
      };
    }
    return {};
  }, [transportType, command, args, env, sseUrl]);
  const generateMCPServerEntry = reactExports.useCallback(() => {
    return JSON.stringify(generateServerConfig(), null, 4);
  }, [generateServerConfig]);
  const generateMCPServerFile = reactExports.useCallback(() => {
    return JSON.stringify(
      {
        mcpServers: {
          "default-server": generateServerConfig()
        }
      },
      null,
      4
    );
  }, [generateServerConfig]);
  const handleCopyServerEntry = reactExports.useCallback(() => {
    try {
      const configJson = generateMCPServerEntry();
      navigator.clipboard.writeText(configJson).then(() => {
        setCopiedServerEntry(true);
        toast2({
          title: "Config entry copied",
          description: transportType === "stdio" ? "Server configuration has been copied to clipboard. Add this to your mcp.json inside the 'mcpServers' object with your preferred server name." : transportType === "streamable-http" ? "Streamable HTTP URL has been copied. Use this URL directly in your MCP Client." : "SSE URL has been copied. Use this URL directly in your MCP Client."
        });
        setTimeout(() => {
          setCopiedServerEntry(false);
        }, 2e3);
      }).catch((error) => {
        reportError2(error);
      });
    } catch (error) {
      reportError2(error);
    }
  }, [generateMCPServerEntry, transportType, toast2, reportError2]);
  const handleCopyServerFile = reactExports.useCallback(() => {
    try {
      const configJson = generateMCPServerFile();
      navigator.clipboard.writeText(configJson).then(() => {
        setCopiedServerFile(true);
        toast2({
          title: "Servers file copied",
          description: "Servers configuration has been copied to clipboard. Add this to your mcp.json file. Current testing server will be added as 'default-server'"
        });
        setTimeout(() => {
          setCopiedServerFile(false);
        }, 2e3);
      }).catch((error) => {
        reportError2(error);
      });
    } catch (error) {
      reportError2(error);
    }
  }, [generateMCPServerFile, toast2, reportError2]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-card border-r border-border flex flex-col h-full", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-between p-4 border-b border-gray-200 dark:border-border", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("h1", { className: "ml-2 text-lg font-semibold", children: [
      "MCP Inspector v",
      version
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4 flex-1 overflow-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "label",
          {
            className: "text-sm font-medium",
            htmlFor: "transport-type-select",
            children: "Transport Type"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Select,
          {
            value: transportType,
            onValueChange: (value) => setTransportType(value),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(SelectTrigger, { id: "transport-type-select", children: /* @__PURE__ */ jsxRuntimeExports.jsx(SelectValue, { placeholder: "Select transport type" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(SelectContent, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "stdio", children: "STDIO" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "sse", children: "SSE" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "streamable-http", children: "Streamable HTTP" })
              ] })
            ]
          }
        )
      ] }),
      transportType === "stdio" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-sm font-medium", htmlFor: "command-input", children: "Command" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              id: "command-input",
              placeholder: "Command",
              value: command,
              onChange: (e2) => setCommand(e2.target.value),
              onBlur: (e2) => setCommand(e2.target.value.trim()),
              className: "font-mono"
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "label",
            {
              className: "text-sm font-medium",
              htmlFor: "arguments-input",
              children: "Arguments"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              id: "arguments-input",
              placeholder: "Arguments (space-separated)",
              value: args,
              onChange: (e2) => setArgs(e2.target.value),
              className: "font-mono"
            }
          )
        ] })
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-sm font-medium", htmlFor: "sse-url-input", children: "URL" }),
          sseUrl ? /* @__PURE__ */ jsxRuntimeExports.jsxs(Tooltip, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                id: "sse-url-input",
                placeholder: "URL",
                value: sseUrl,
                onChange: (e2) => setSseUrl(e2.target.value),
                className: "font-mono"
              }
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipContent, { children: sseUrl })
          ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              id: "sse-url-input",
              placeholder: "URL",
              value: sseUrl,
              onChange: (e2) => setSseUrl(e2.target.value),
              className: "font-mono"
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Tooltip, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                className: "text-sm font-medium",
                htmlFor: "connection-type-select",
                children: "Connection Type"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                value: connectionType,
                onValueChange: (value) => setConnectionType(value),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(SelectTrigger, { id: "connection-type-select", children: /* @__PURE__ */ jsxRuntimeExports.jsx(SelectValue, { placeholder: "Select connection type" }) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs(SelectContent, { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "proxy", children: "Via Proxy" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "direct", children: "Direct" })
                  ] })
                ]
              }
            )
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipContent, { children: connectionTypeTip })
        ] })
      ] }),
      transportType === "stdio" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: () => setShowEnvVars(!showEnvVars),
            className: "flex items-center w-full",
            "data-testid": "env-vars-button",
            "aria-expanded": showEnvVars,
            children: [
              showEnvVars ? /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDown, { className: "w-4 h-4 mr-2" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "w-4 h-4 mr-2" }),
              "Environment Variables"
            ]
          }
        ),
        showEnvVars && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          Object.entries(env).map(([key, value], idx) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2 pb-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  "aria-label": `Environment variable key ${idx + 1}`,
                  placeholder: "Key",
                  value: key,
                  onChange: (e2) => {
                    const newKey = e2.target.value;
                    const newEnv = Object.entries(env).reduce(
                      (acc, [k2, v2]) => {
                        if (k2 === key) {
                          acc[newKey] = value;
                        } else {
                          acc[k2] = v2;
                        }
                        return acc;
                      },
                      {}
                    );
                    setEnv(newEnv);
                    setShownEnvVars((prev) => {
                      const next = new Set(prev);
                      if (next.has(key)) {
                        next.delete(key);
                        next.add(newKey);
                      }
                      return next;
                    });
                  },
                  className: "font-mono"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  variant: "destructive",
                  size: "icon",
                  className: "h-9 w-9 p-0 shrink-0",
                  onClick: () => {
                    const { [key]: _removed, ...rest } = env;
                    setEnv(rest);
                  },
                  children: "×"
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  "aria-label": `Environment variable value ${idx + 1}`,
                  type: shownEnvVars.has(key) ? "text" : "password",
                  placeholder: "Value",
                  value,
                  onChange: (e2) => {
                    const newEnv = { ...env };
                    newEnv[key] = e2.target.value;
                    setEnv(newEnv);
                  },
                  className: "font-mono"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  variant: "outline",
                  size: "icon",
                  className: "h-9 w-9 p-0 shrink-0",
                  onClick: () => {
                    setShownEnvVars((prev) => {
                      const next = new Set(prev);
                      if (next.has(key)) {
                        next.delete(key);
                      } else {
                        next.add(key);
                      }
                      return next;
                    });
                  },
                  "aria-label": shownEnvVars.has(key) ? "Hide value" : "Show value",
                  "aria-pressed": shownEnvVars.has(key),
                  title: shownEnvVars.has(key) ? "Hide value" : "Show value",
                  children: shownEnvVars.has(key) ? /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "h-4 w-4", "aria-hidden": "true" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(EyeOff, { className: "h-4 w-4", "aria-hidden": "true" })
                }
              )
            ] })
          ] }, idx)),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "outline",
              className: "w-full mt-2",
              onClick: () => {
                const key = "";
                const newEnv = { ...env };
                newEnv[key] = "";
                setEnv(newEnv);
              },
              children: "Add Environment Variable"
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-2 mt-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Tooltip, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: handleCopyServerEntry,
              className: "w-full",
              children: [
                copiedServerEntry ? /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCheck, { className: "h-4 w-4 mr-2" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "h-4 w-4 mr-2" }),
                "Server Entry"
              ]
            }
          ) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipContent, { children: "Copy Server Entry" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Tooltip, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: handleCopyServerFile,
              className: "w-full",
              children: [
                copiedServerFile ? /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCheck, { className: "h-4 w-4 mr-2" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "h-4 w-4 mr-2" }),
                "Servers File"
              ]
            }
          ) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipContent, { children: "Copy Servers File" })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: () => setShowAuthConfig(!showAuthConfig),
            className: "flex items-center w-full",
            "data-testid": "auth-button",
            "aria-expanded": showAuthConfig,
            children: [
              showAuthConfig ? /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDown, { className: "w-4 h-4 mr-2" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "w-4 h-4 mr-2" }),
              "Authentication"
            ]
          }
        ),
        showAuthConfig && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 rounded border overflow-hidden", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            CustomHeaders,
            {
              headers: customHeaders,
              onChange: setCustomHeaders
            }
          ) }),
          transportType !== "stdio" && // OAuth Configuration
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2 p-3  rounded border", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-sm font-semibold flex items-center", children: "OAuth 2.0 Flow" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-sm font-medium", children: "Client ID" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  placeholder: "Client ID",
                  onChange: (e2) => setOauthClientId(e2.target.value),
                  value: oauthClientId,
                  "data-testid": "oauth-client-id-input",
                  className: "font-mono"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-sm font-medium", children: "Client Secret" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    type: showClientSecret ? "text" : "password",
                    placeholder: "Client Secret (optional)",
                    onChange: (e2) => setOauthClientSecret(e2.target.value),
                    value: oauthClientSecret,
                    "data-testid": "oauth-client-secret-input",
                    className: "font-mono"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    variant: "outline",
                    size: "icon",
                    className: "h-9 w-9 p-0 shrink-0",
                    onClick: () => setShowClientSecret(!showClientSecret),
                    "aria-label": showClientSecret ? "Hide secret" : "Show secret",
                    "aria-pressed": showClientSecret,
                    title: showClientSecret ? "Hide secret" : "Show secret",
                    children: showClientSecret ? /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "h-4 w-4", "aria-hidden": "true" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(EyeOff, { className: "h-4 w-4", "aria-hidden": "true" })
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-sm font-medium", children: "Redirect URL" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  readOnly: true,
                  placeholder: "Redirect URL",
                  value: window.location.origin + "/oauth/callback",
                  className: "font-mono"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-sm font-medium", children: "Scope" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  placeholder: "Scope (space-separated)",
                  onChange: (e2) => setOauthScope(e2.target.value),
                  value: oauthScope,
                  "data-testid": "oauth-scope-input",
                  className: "font-mono"
                }
              )
            ] })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: () => setShowConfig(!showConfig),
            className: "flex items-center w-full",
            "data-testid": "config-button",
            "aria-expanded": showConfig,
            children: [
              showConfig ? /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDown, { className: "w-4 h-4 mr-2" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "w-4 h-4 mr-2" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Settings, { className: "w-4 h-4 mr-2" }),
              "Configuration"
            ]
          }
        ),
        showConfig && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: Object.entries(config2).map(([key, configItem]) => {
          const configKey = key;
          return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  className: "text-sm font-medium text-green-600 break-all",
                  htmlFor: `${configKey}-input`,
                  children: configItem.label
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(Tooltip, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(CircleQuestionMark, { className: "h-4 w-4 text-muted-foreground" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipContent, { children: configItem.description })
              ] })
            ] }),
            typeof configItem.value === "number" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                id: `${configKey}-input`,
                type: "number",
                "data-testid": `${configKey}-input`,
                value: configItem.value,
                onChange: (e2) => {
                  const newConfig = { ...config2 };
                  newConfig[configKey] = {
                    ...configItem,
                    value: Number(e2.target.value)
                  };
                  setConfig(newConfig);
                },
                className: "font-mono"
              }
            ) : typeof configItem.value === "boolean" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                "data-testid": `${configKey}-select`,
                value: configItem.value.toString(),
                onValueChange: (val) => {
                  const newConfig = { ...config2 };
                  newConfig[configKey] = {
                    ...configItem,
                    value: val === "true"
                  };
                  setConfig(newConfig);
                },
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(SelectTrigger, { id: `${configKey}-input`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(SelectValue, {}) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs(SelectContent, { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "true", children: "True" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "false", children: "False" })
                  ] })
                ]
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                id: `${configKey}-input`,
                "data-testid": `${configKey}-input`,
                value: configItem.value,
                onChange: (e2) => {
                  const newConfig = { ...config2 };
                  newConfig[configKey] = {
                    ...configItem,
                    value: e2.target.value
                  };
                  setConfig(newConfig);
                },
                className: "font-mono"
              }
            )
          ] }, key);
        }) })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
        connectionStatus === "connected" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              "data-testid": "connect-button",
              onClick: () => {
                onDisconnect();
                onConnect();
              },
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(RotateCcw, { className: "w-4 h-4 mr-2" }),
                transportType === "stdio" ? "Restart" : "Reconnect"
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: onDisconnect, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCwOff, { className: "w-4 h-4 mr-2" }),
            "Disconnect"
          ] })
        ] }),
        connectionStatus !== "connected" && /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { className: "w-full", onClick: onConnect, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Play, { className: "w-4 h-4 mr-2" }),
          "Connect"
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-center space-x-2 mb-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: `w-2 h-2 rounded-full ${(() => {
                switch (connectionStatus) {
                  case "connected":
                    return "bg-green-500";
                  case "error":
                    return "bg-red-500";
                  case "error-connecting-to-proxy":
                    return "bg-red-500";
                  default:
                    return "bg-gray-500";
                }
              })()}`
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: (() => {
            switch (connectionStatus) {
              case "connected":
                return "Connected";
              case "error": {
                const hasProxyToken = config2.MCP_PROXY_AUTH_TOKEN?.value;
                if (!hasProxyToken) {
                  return "Connection Error - Did you add the proxy session token in Configuration?";
                }
                return "Connection Error - Check if your MCP server is running and proxy token is correct";
              }
              case "error-connecting-to-proxy":
                return "Error Connecting to MCP Inspector Proxy - Check Console logs";
              default:
                return "Disconnected";
            }
          })() })
        ] }),
        connectionStatus === "connected" && serverImplementation && (() => {
          const websiteUrl = serverImplementation.websiteUrl;
          let isValidWebsiteUrl = false;
          if (websiteUrl) {
            try {
              validateRedirectUrl(websiteUrl);
              isValidWebsiteUrl = true;
            } catch {
              isValidWebsiteUrl = false;
            }
          }
          const serverName = serverImplementation.name || "MCP Server";
          return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900 p-3 rounded-lg mb-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 mb-1", children: [
              serverImplementation.icons && serverImplementation.icons.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                IconDisplay,
                {
                  icons: serverImplementation.icons,
                  size: "sm"
                }
              ) : /* @__PURE__ */ jsxRuntimeExports.jsx(Server, { className: "w-4 h-4 text-gray-500" }),
              websiteUrl && isValidWebsiteUrl ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                "a",
                {
                  href: websiteUrl,
                  target: "_blank",
                  rel: "noopener noreferrer",
                  className: "text-sm font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline transition-colors",
                  children: serverName
                }
              ) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-gray-800 dark:text-gray-200", children: serverName })
            ] }),
            websiteUrl && !isValidWebsiteUrl && /* @__PURE__ */ jsxRuntimeExports.jsxs(Tooltip, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-yellow-600 dark:text-yellow-500 mb-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(TriangleAlert, { className: "w-3.5 h-3.5 flex-shrink-0" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-normal", children: "Potentially malicious websiteURL field" })
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "max-w-xs break-all", children: websiteUrl }) })
            ] }),
            serverImplementation.version && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
              "Version: ",
              serverImplementation.version
            ] })
          ] });
        })(),
        loggingSupported && connectionStatus === "connected" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "label",
            {
              className: "text-sm font-medium",
              htmlFor: "logging-level-select",
              children: "Logging Level"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Select,
            {
              value: logLevel,
              onValueChange: (value) => sendLogLevelRequest(value),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(SelectTrigger, { id: "logging-level-select", children: /* @__PURE__ */ jsxRuntimeExports.jsx(SelectValue, { placeholder: "Select logging level" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(SelectContent, { children: Object.values(LoggingLevelSchema.enum).map((level) => /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: level, children: level }, level)) })
              ]
            }
          )
        ] })
      ] })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4 border-t", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: theme,
          onValueChange: (value) => setTheme(value),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(SelectTrigger, { className: "w-[100px]", id: "theme-select", children: /* @__PURE__ */ jsxRuntimeExports.jsx(SelectValue, {}) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(SelectContent, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "system", children: "System" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "light", children: "Light" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "dark", children: "Dark" })
            ] })
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center space-x-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "ghost", title: "Inspector Documentation", asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "a",
          {
            href: "https://modelcontextprotocol.io/docs/tools/inspector",
            target: "_blank",
            rel: "noopener noreferrer",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(CircleQuestionMark, { className: "w-4 h-4 text-foreground" })
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "ghost", title: "Debugging Guide", asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "a",
          {
            href: "https://modelcontextprotocol.io/docs/tools/debugging",
            target: "_blank",
            rel: "noopener noreferrer",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(Bug, { className: "w-4 h-4 text-foreground" })
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "ghost",
            title: "Report bugs or contribute on GitHub",
            asChild: true,
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: "https://github.com/modelcontextprotocol/inspector",
                target: "_blank",
                rel: "noopener noreferrer",
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(Github, { className: "w-4 h-4 text-foreground" })
              }
            )
          }
        )
      ] })
    ] }) })
  ] });
};
var CHECKBOX_NAME = "Checkbox";
var [createCheckboxContext] = createContextScope(CHECKBOX_NAME);
var [CheckboxProviderImpl, useCheckboxContext] = createCheckboxContext(CHECKBOX_NAME);
function CheckboxProvider(props) {
  const {
    __scopeCheckbox,
    checked: checkedProp,
    children,
    defaultChecked,
    disabled,
    form,
    name: name2,
    onCheckedChange,
    required: required2,
    value = "on",
    // @ts-expect-error
    internal_do_not_use_render
  } = props;
  const [checked, setChecked] = useControllableState({
    prop: checkedProp,
    defaultProp: defaultChecked ?? false,
    onChange: onCheckedChange,
    caller: CHECKBOX_NAME
  });
  const [control, setControl] = reactExports.useState(null);
  const [bubbleInput, setBubbleInput] = reactExports.useState(null);
  const hasConsumerStoppedPropagationRef = reactExports.useRef(false);
  const isFormControl = control ? !!form || !!control.closest("form") : (
    // We set this to true by default so that events bubble to forms without JS (SSR)
    true
  );
  const context = {
    checked,
    disabled,
    setChecked,
    control,
    setControl,
    name: name2,
    form,
    value,
    hasConsumerStoppedPropagationRef,
    required: required2,
    defaultChecked: isIndeterminate(defaultChecked) ? false : defaultChecked,
    isFormControl,
    bubbleInput,
    setBubbleInput
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    CheckboxProviderImpl,
    {
      scope: __scopeCheckbox,
      ...context,
      children: isFunction(internal_do_not_use_render) ? internal_do_not_use_render(context) : children
    }
  );
}
var TRIGGER_NAME = "CheckboxTrigger";
var CheckboxTrigger = reactExports.forwardRef(
  ({ __scopeCheckbox, onKeyDown, onClick, ...checkboxProps }, forwardedRef) => {
    const {
      control,
      value,
      disabled,
      checked,
      required: required2,
      setControl,
      setChecked,
      hasConsumerStoppedPropagationRef,
      isFormControl,
      bubbleInput
    } = useCheckboxContext(TRIGGER_NAME, __scopeCheckbox);
    const composedRefs = useComposedRefs(forwardedRef, setControl);
    const initialCheckedStateRef = reactExports.useRef(checked);
    reactExports.useEffect(() => {
      const form = control?.form;
      if (form) {
        const reset = () => setChecked(initialCheckedStateRef.current);
        form.addEventListener("reset", reset);
        return () => form.removeEventListener("reset", reset);
      }
    }, [control, setChecked]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.button,
      {
        type: "button",
        role: "checkbox",
        "aria-checked": isIndeterminate(checked) ? "mixed" : checked,
        "aria-required": required2,
        "data-state": getState(checked),
        "data-disabled": disabled ? "" : void 0,
        disabled,
        value,
        ...checkboxProps,
        ref: composedRefs,
        onKeyDown: composeEventHandlers(onKeyDown, (event) => {
          if (event.key === "Enter") event.preventDefault();
        }),
        onClick: composeEventHandlers(onClick, (event) => {
          setChecked((prevChecked) => isIndeterminate(prevChecked) ? true : !prevChecked);
          if (bubbleInput && isFormControl) {
            hasConsumerStoppedPropagationRef.current = event.isPropagationStopped();
            if (!hasConsumerStoppedPropagationRef.current) event.stopPropagation();
          }
        })
      }
    );
  }
);
CheckboxTrigger.displayName = TRIGGER_NAME;
var Checkbox$1 = reactExports.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeCheckbox,
      name: name2,
      checked,
      defaultChecked,
      required: required2,
      disabled,
      value,
      onCheckedChange,
      form,
      ...checkboxProps
    } = props;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      CheckboxProvider,
      {
        __scopeCheckbox,
        checked,
        defaultChecked,
        disabled,
        required: required2,
        onCheckedChange,
        name: name2,
        form,
        value,
        internal_do_not_use_render: ({ isFormControl }) => /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            CheckboxTrigger,
            {
              ...checkboxProps,
              ref: forwardedRef,
              __scopeCheckbox
            }
          ),
          isFormControl && /* @__PURE__ */ jsxRuntimeExports.jsx(
            CheckboxBubbleInput,
            {
              __scopeCheckbox
            }
          )
        ] })
      }
    );
  }
);
Checkbox$1.displayName = CHECKBOX_NAME;
var INDICATOR_NAME = "CheckboxIndicator";
var CheckboxIndicator = reactExports.forwardRef(
  (props, forwardedRef) => {
    const { __scopeCheckbox, forceMount, ...indicatorProps } = props;
    const context = useCheckboxContext(INDICATOR_NAME, __scopeCheckbox);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Presence,
      {
        present: forceMount || isIndeterminate(context.checked) || context.checked === true,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Primitive$1.span,
          {
            "data-state": getState(context.checked),
            "data-disabled": context.disabled ? "" : void 0,
            ...indicatorProps,
            ref: forwardedRef,
            style: { pointerEvents: "none", ...props.style }
          }
        )
      }
    );
  }
);
CheckboxIndicator.displayName = INDICATOR_NAME;
var BUBBLE_INPUT_NAME = "CheckboxBubbleInput";
var CheckboxBubbleInput = reactExports.forwardRef(
  ({ __scopeCheckbox, ...props }, forwardedRef) => {
    const {
      control,
      hasConsumerStoppedPropagationRef,
      checked,
      defaultChecked,
      required: required2,
      disabled,
      name: name2,
      value,
      form,
      bubbleInput,
      setBubbleInput
    } = useCheckboxContext(BUBBLE_INPUT_NAME, __scopeCheckbox);
    const composedRefs = useComposedRefs(forwardedRef, setBubbleInput);
    const prevChecked = usePrevious(checked);
    const controlSize = useSize(control);
    reactExports.useEffect(() => {
      const input = bubbleInput;
      if (!input) return;
      const inputProto = window.HTMLInputElement.prototype;
      const descriptor = Object.getOwnPropertyDescriptor(
        inputProto,
        "checked"
      );
      const setChecked = descriptor.set;
      const bubbles = !hasConsumerStoppedPropagationRef.current;
      if (prevChecked !== checked && setChecked) {
        const event = new Event("click", { bubbles });
        input.indeterminate = isIndeterminate(checked);
        setChecked.call(input, isIndeterminate(checked) ? false : checked);
        input.dispatchEvent(event);
      }
    }, [bubbleInput, prevChecked, checked, hasConsumerStoppedPropagationRef]);
    const defaultCheckedRef = reactExports.useRef(isIndeterminate(checked) ? false : checked);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Primitive$1.input,
      {
        type: "checkbox",
        "aria-hidden": true,
        defaultChecked: defaultChecked ?? defaultCheckedRef.current,
        required: required2,
        disabled,
        name: name2,
        value,
        form,
        ...props,
        tabIndex: -1,
        ref: composedRefs,
        style: {
          ...props.style,
          ...controlSize,
          position: "absolute",
          pointerEvents: "none",
          opacity: 0,
          margin: 0,
          // We transform because the input is absolutely positioned but we have
          // rendered it **after** the button. This pulls it back to sit on top
          // of the button.
          transform: "translateX(-100%)"
        }
      }
    );
  }
);
CheckboxBubbleInput.displayName = BUBBLE_INPUT_NAME;
function isFunction(value) {
  return typeof value === "function";
}
function isIndeterminate(checked) {
  return checked === "indeterminate";
}
function getState(checked) {
  return isIndeterminate(checked) ? "indeterminate" : checked ? "checked" : "unchecked";
}
const Checkbox = reactExports.forwardRef(({ className, ...props }, ref2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Checkbox$1,
  {
    ref: ref2,
    className: cn$1(
      "peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
      className
    ),
    ...props,
    children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      CheckboxIndicator,
      {
        className: cn$1("flex items-center justify-center text-current"),
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "h-4 w-4" })
      }
    )
  }
));
Checkbox.displayName = Checkbox$1.displayName;
const ResourceLinkView = reactExports.memo(
  ({
    uri: uri2,
    name: name2,
    description: description2,
    mimeType,
    resourceContent,
    onReadResource
  }) => {
    const [{ expanded, loading }, setState] = reactExports.useState({
      expanded: false,
      loading: false
    });
    const expandedContent = reactExports.useMemo(
      () => expanded && resourceContent ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-between items-center mb-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold text-green-600", children: "Resource:" }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: resourceContent, className: "bg-background" })
      ] }) : null,
      [expanded, resourceContent]
    );
    const handleClick = reactExports.useCallback(() => {
      if (!onReadResource) return;
      if (!expanded) {
        setState((prev) => ({ ...prev, expanded: true, loading: true }));
        onReadResource(uri2);
        setState((prev) => ({ ...prev, loading: false }));
      } else {
        setState((prev) => ({ ...prev, expanded: false }));
      }
    }, [expanded, onReadResource, uri2]);
    const handleKeyDown = reactExports.useCallback(
      (e2) => {
        if ((e2.key === "Enter" || e2.key === " ") && onReadResource) {
          e2.preventDefault();
          handleClick();
        }
      },
      [handleClick, onReadResource]
    );
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-foreground bg-secondary py-2 px-3 rounded", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: "flex justify-between items-center cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-1 rounded",
          onClick: onReadResource ? handleClick : void 0,
          onKeyDown: onReadResource ? handleKeyDown : void 0,
          tabIndex: onReadResource ? 0 : -1,
          role: "button",
          "aria-expanded": expanded,
          "aria-label": `${expanded ? "Collapse" : "Expand"} resource ${uri2}`,
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between gap-2 mb-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 hover:underline px-1 py-0.5 break-all font-mono flex-1 min-w-0", children: uri2 }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 flex-shrink-0", children: [
                mimeType && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200", children: mimeType }),
                onReadResource && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-2 flex-shrink-0", "aria-hidden": "true", children: loading ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: expanded ? "▼" : "▶" }) })
              ] })
            ] }),
            name2 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-semibold text-sm text-gray-900 dark:text-gray-100 mb-1", children: name2 }),
            description2 && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-300 leading-relaxed", children: description2 })
          ] })
        }
      ),
      expandedContent
    ] });
  }
);
const checkContentCompatibility = (structuredContent, unstructuredContent) => {
  const textBlocks = unstructuredContent.filter(
    (block) => block.type === "text"
  );
  if (textBlocks.length === 0) {
    return null;
  }
  for (const textBlock of textBlocks) {
    const textContent = textBlock.text;
    if (!textContent) {
      continue;
    }
    try {
      const parsedContent = JSON.parse(textContent);
      const isEqual = JSON.stringify(parsedContent) === JSON.stringify(structuredContent);
      if (isEqual) {
        return {
          hasMatch: true,
          message: `Structured content matches text block${textBlocks.length > 1 ? " (multiple blocks)" : ""}${unstructuredContent.length > textBlocks.length ? " + other content" : ""}`
        };
      }
    } catch {
      continue;
    }
  }
  return null;
};
const ToolResults = ({
  toolResult,
  selectedTool,
  resourceContent,
  onReadResource,
  isPollingTask
}) => {
  if (!toolResult) return null;
  if ("content" in toolResult) {
    const parsedResult = CallToolResultSchema.safeParse(toolResult);
    if (!parsedResult.success) {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-semibold mb-2", children: "Invalid Tool Result:" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: toolResult }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-semibold mb-2", children: "Errors:" }),
        parsedResult.error.issues.map((issue2, idx) => /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: issue2 }, idx))
      ] });
    }
    const structuredResult = parsedResult.data;
    const isError = structuredResult.isError ?? false;
    const relatedTask = structuredResult._meta?.["io.modelcontextprotocol/related-task"];
    const isTaskRunning = isPollingTask || !!relatedTask && structuredResult.content.some(
      (c) => c.type === "text" && (c.text?.includes("Polling") || c.text?.includes("Task status"))
    );
    let validationResult = null;
    const toolHasOutputSchema = selectedTool && hasOutputSchema(selectedTool.name);
    if (toolHasOutputSchema) {
      if (!structuredResult.structuredContent && !isError) {
        validationResult = {
          isValid: false,
          error: "Tool has an output schema but did not return structured content"
        };
      } else if (structuredResult.structuredContent) {
        validationResult = validateToolOutput(
          selectedTool.name,
          structuredResult.structuredContent
        );
      }
    }
    let compatibilityResult = null;
    if (structuredResult.structuredContent && structuredResult.content.length > 0 && selectedTool && hasOutputSchema(selectedTool.name)) {
      compatibilityResult = checkContentCompatibility(
        structuredResult.structuredContent,
        structuredResult.content
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("h4", { className: "font-semibold mb-2", children: [
        "Tool Result:",
        " ",
        isError ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-600 font-semibold", children: "Error" }) : isTaskRunning ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-yellow-600 font-semibold", children: "Task Running" }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-green-600 font-semibold", children: "Success" })
      ] }),
      structuredResult.structuredContent && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h5", { className: "font-semibold mb-2 text-sm", children: "Structured Content:" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900 p-3 rounded-lg", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: structuredResult.structuredContent }),
          validationResult && /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: `mt-2 p-2 rounded text-sm ${validationResult.isValid ? "bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200" : "bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200"}`,
              children: validationResult.isValid ? "✓ Valid according to output schema" : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                "✗ Validation Error: ",
                validationResult.error
              ] })
            }
          )
        ] })
      ] }),
      structuredResult._meta && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h5", { className: "font-semibold mb-2 text-sm", children: "Meta:" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-gray-50 dark:bg-gray-900 p-3 rounded-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: structuredResult._meta }) })
      ] }),
      !structuredResult.structuredContent && validationResult && !validationResult.isValid && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mb-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 p-2 rounded text-sm", children: [
        "✗ Validation Error: ",
        validationResult.error
      ] }) }),
      structuredResult.content.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-4", children: [
        structuredResult.structuredContent && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h5", { className: "font-semibold mb-2 text-sm", children: "Unstructured Content:" }),
          compatibilityResult?.hasMatch && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-2 p-2 rounded text-sm bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200", children: [
            "✓ ",
            compatibilityResult.message
          ] })
        ] }),
        structuredResult.content.map((item, index2) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-2", children: [
          item.type === "text" && /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: item.text, isError }),
          item.type === "image" && /* @__PURE__ */ jsxRuntimeExports.jsx(
            "img",
            {
              src: `data:${item.mimeType};base64,${item.data}`,
              alt: "Tool result image",
              className: "max-w-full h-auto"
            }
          ),
          item.type === "resource" && (item.resource?.mimeType?.startsWith("audio/") && "blob" in item.resource ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            "audio",
            {
              controls: true,
              src: `data:${item.resource.mimeType};base64,${item.resource.blob}`,
              className: "w-full",
              children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Your browser does not support audio playback" })
            }
          ) : /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: item.resource })),
          item.type === "resource_link" && /* @__PURE__ */ jsxRuntimeExports.jsx(
            ResourceLinkView,
            {
              uri: item.uri,
              name: item.name,
              description: item.description,
              mimeType: item.mimeType,
              resourceContent: resourceContent[item.uri] || "",
              onReadResource
            }
          )
        ] }, index2))
      ] })
    ] });
  } else if ("toolResult" in toolResult) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-semibold mb-2", children: "Tool Result (Legacy):" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: toolResult.toolResult })
    ] });
  }
  return null;
};
const hasMeta = (tool) => typeof tool._meta !== "undefined";
const getTaskSupport = (tool) => {
  if (!tool) return "forbidden";
  const extendedTool = tool;
  const taskSupport = extendedTool.execution?.taskSupport;
  if (taskSupport === "forbidden" || taskSupport === "required" || taskSupport === "optional") {
    return taskSupport;
  }
  return "forbidden";
};
const hasAnnotations = (tool) => typeof tool.annotations !== "undefined" && tool.annotations !== null;
const AnnotationBadges = ({
  annotations
}) => {
  const getValueAndImplied = (value, defaultValue) => ({
    value: value ?? defaultValue,
    implied: value === void 0
  });
  const readOnly = getValueAndImplied(annotations?.readOnlyHint, false);
  const destructive = getValueAndImplied(annotations?.destructiveHint, true);
  const idempotent = getValueAndImplied(annotations?.idempotentHint, false);
  const openWorld = getValueAndImplied(annotations?.openWorldHint, true);
  const badges = [
    {
      label: "Read-only",
      value: readOnly.value,
      implied: readOnly.implied,
      description: "Tool does not modify its environment"
    },
    {
      label: "Destructive",
      value: destructive.value,
      implied: destructive.implied,
      description: "Tool may perform destructive updates (delete/overwrite data)"
    },
    {
      label: "Idempotent",
      value: idempotent.value,
      implied: idempotent.implied,
      description: "Calling repeatedly with same args has no additional effect"
    },
    {
      label: "Open-world",
      value: openWorld.value,
      implied: openWorld.implied,
      description: "Tool may interact with external entities beyond its local environment"
    }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-wrap gap-1 mt-2", children: badges.map(({ label, value, implied, description: description2 }) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "span",
    {
      title: `${description2}

Value: ${value ? "Yes" : "No"} (${implied ? "implied default" : "explicitly set"})`,
      className: cn$1(
        "inline-flex items-center px-2 py-0.5 rounded text-xs font-medium border",
        "bg-slate-100 text-slate-700 border-slate-300 dark:bg-slate-800 dark:text-slate-300 dark:border-slate-600",
        implied && "border-dashed opacity-60",
        !implied && "border-solid"
      ),
      children: [
        value ? "✓" : "✗",
        " ",
        label
      ]
    },
    label
  )) });
};
const ToolsTab = ({
  tools,
  listTools,
  clearTools,
  callTool,
  selectedTool,
  setSelectedTool,
  toolResult,
  isPollingTask,
  nextCursor,
  error,
  resourceContent,
  onReadResource,
  serverSupportsTaskRequests
}) => {
  const [params, setParams] = reactExports.useState({});
  const [runAsTask, setRunAsTask] = reactExports.useState(false);
  const [isToolRunning, setIsToolRunning] = reactExports.useState(false);
  const [isOutputSchemaExpanded, setIsOutputSchemaExpanded] = reactExports.useState(false);
  const [isMetadataExpanded, setIsMetadataExpanded] = reactExports.useState(false);
  const [metadataEntries, setMetadataEntries] = reactExports.useState([]);
  const [hasValidationErrors, setHasValidationErrors] = reactExports.useState(false);
  const formRefs = reactExports.useRef({});
  const { toast: toast2 } = useToast();
  const { copied, setCopied } = useCopy();
  const checkValidationErrors = (validateChildren = false) => {
    const errors2 = Object.values(formRefs.current).some(
      (ref2) => ref2 && (validateChildren ? !ref2.validateJson().isValid : ref2.hasJsonError())
    );
    setHasValidationErrors(errors2);
    return errors2;
  };
  reactExports.useEffect(() => {
    const params2 = Object.entries(
      selectedTool?.inputSchema.properties ?? []
    ).map(([key, value]) => {
      const resolvedValue = resolveRef(
        value,
        selectedTool?.inputSchema
      );
      return [
        key,
        generateDefaultValue(
          resolvedValue,
          key,
          selectedTool?.inputSchema
        )
      ];
    });
    setParams(Object.fromEntries(params2));
    const toolTaskSupport = serverSupportsTaskRequests ? getTaskSupport(selectedTool) : "forbidden";
    setRunAsTask(toolTaskSupport === "required");
    setHasValidationErrors(false);
    formRefs.current = {};
  }, [selectedTool, serverSupportsTaskRequests]);
  const hasReservedMetadataEntry = metadataEntries.some(({ key }) => {
    const trimmedKey = key.trim();
    return trimmedKey !== "" && isReservedMetaKey(trimmedKey);
  });
  const hasInvalidMetaPrefixEntry = metadataEntries.some(({ key }) => {
    const trimmedKey = key.trim();
    return trimmedKey !== "" && !hasValidMetaPrefix(trimmedKey);
  });
  const hasInvalidMetaNameEntry = metadataEntries.some(({ key }) => {
    const trimmedKey = key.trim();
    return trimmedKey !== "" && !hasValidMetaName(trimmedKey);
  });
  const taskSupport = serverSupportsTaskRequests ? getTaskSupport(selectedTool) : "forbidden";
  return /* @__PURE__ */ jsxRuntimeExports.jsx(TabsContent, { value: "tools", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ListPane,
      {
        items: tools,
        listItems: listTools,
        clearItems: () => {
          clearTools();
          setSelectedTool(null);
          setRunAsTask(false);
        },
        setSelectedItem: setSelectedTool,
        renderItem: (tool) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start w-full gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-shrink-0 mt-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx(IconDisplay, { icons: tool.icons, size: "sm" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col flex-1 min-w-0", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "truncate", children: tool.title || tool.name }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-500 text-left line-clamp-2", children: tool.description })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "w-4 h-4 flex-shrink-0 text-gray-400 mt-1" })
        ] }),
        title: "Tools",
        buttonText: nextCursor ? "List More Tools" : "List Tools",
        isButtonDisabled: !nextCursor && tools.length > 0
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-card border border-border rounded-lg shadow", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4 border-b border-gray-200 dark:border-border", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        selectedTool && /* @__PURE__ */ jsxRuntimeExports.jsx(
          IconDisplay,
          {
            icons: selectedTool.icons,
            size: "md"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "font-semibold", children: selectedTool ? selectedTool.title || selectedTool.name : "Select a tool" })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4", children: selectedTool ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
        error && /* @__PURE__ */ jsxRuntimeExports.jsxs(Alert, { variant: "destructive", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CircleAlert, { className: "h-4 w-4" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTitle, { children: "Error" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { className: "break-all", children: error })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 whitespace-pre-wrap max-h-48 overflow-y-auto", children: selectedTool.description }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          AnnotationBadges,
          {
            annotations: hasAnnotations(selectedTool) ? selectedTool.annotations : void 0
          }
        ),
        Object.entries(selectedTool.inputSchema.properties ?? []).map(
          ([key, value]) => {
            const resolvedValue = resolveRef(
              value,
              selectedTool.inputSchema
            );
            const prop = normalizeUnionType(resolvedValue);
            const inputSchema = selectedTool.inputSchema;
            const required2 = isPropertyRequired(key, inputSchema);
            return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Label$1,
                  {
                    htmlFor: key,
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300",
                    children: [
                      key,
                      required2 && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500 ml-1", children: "*" })
                    ]
                  }
                ),
                prop.nullable ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center space-x-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Checkbox,
                    {
                      id: key,
                      name: key,
                      checked: params[key] === null,
                      onCheckedChange: (checked) => setParams({
                        ...params,
                        [key]: checked ? null : prop.type === "array" ? void 0 : prop.default !== null ? prop.default : prop.type === "boolean" ? false : prop.type === "string" ? "" : prop.type === "number" || prop.type === "integer" ? void 0 : void 0
                      })
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "label",
                    {
                      htmlFor: key,
                      className: "text-sm font-medium text-gray-700 dark:text-gray-300",
                      children: "null"
                    }
                  )
                ] }) : null
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  role: "toolinputwrapper",
                  className: `${prop.nullable && params[key] === null ? "pointer-events-none opacity-50" : ""}`,
                  children: prop.type === "boolean" ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center space-x-2 mt-2", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      Checkbox,
                      {
                        id: key,
                        name: key,
                        checked: !!params[key],
                        onCheckedChange: (checked) => setParams({
                          ...params,
                          [key]: checked
                        })
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "label",
                      {
                        htmlFor: key,
                        className: "text-sm font-medium text-gray-700 dark:text-gray-300",
                        children: prop.description || "Toggle this option"
                      }
                    )
                  ] }) : prop.type === "string" && prop.enum ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    Select,
                    {
                      value: params[key] === void 0 ? "" : String(params[key]),
                      onValueChange: (value2) => {
                        if (value2 === "") {
                          setParams({
                            ...params,
                            [key]: void 0
                          });
                        } else {
                          setParams({
                            ...params,
                            [key]: value2
                          });
                        }
                      },
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(SelectTrigger, { id: key, className: "mt-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                          SelectValue,
                          {
                            placeholder: prop.description || "Select an option"
                          }
                        ) }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx(SelectContent, { children: prop.enum.map((option) => /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: option, children: option }, option)) })
                      ]
                    }
                  ) : prop.type === "string" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Textarea,
                    {
                      id: key,
                      name: key,
                      placeholder: prop.description,
                      value: params[key] === void 0 ? "" : String(params[key]),
                      onChange: (e2) => {
                        const value2 = e2.target.value;
                        if (value2 === "") {
                          setParams({
                            ...params,
                            [key]: void 0
                          });
                        } else {
                          setParams({
                            ...params,
                            [key]: value2
                          });
                        }
                      },
                      className: "mt-1"
                    }
                  ) : prop.type === "object" || prop.type === "array" ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    DynamicJsonForm,
                    {
                      ref: (ref2) => formRefs.current[key] = ref2,
                      schema: {
                        type: prop.type,
                        properties: prop.properties,
                        description: prop.description,
                        items: prop.items
                      },
                      value: params[key] ?? generateDefaultValue(prop),
                      onChange: (newValue) => {
                        setParams({
                          ...params,
                          [key]: newValue
                        });
                        setTimeout(checkValidationErrors, 100);
                      }
                    }
                  ) }) : prop.type === "number" || prop.type === "integer" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      type: "number",
                      id: key,
                      name: key,
                      placeholder: prop.description,
                      value: params[key] === void 0 ? "" : String(params[key]),
                      onChange: (e2) => {
                        const value2 = e2.target.value;
                        if (value2 === "") {
                          setParams({
                            ...params,
                            [key]: void 0
                          });
                        } else {
                          const num = Number(value2);
                          if (!isNaN(num)) {
                            setParams({
                              ...params,
                              [key]: num
                            });
                          } else {
                            setParams({
                              ...params,
                              [key]: value2
                            });
                          }
                        }
                      },
                      className: "mt-1"
                    }
                  ) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    DynamicJsonForm,
                    {
                      ref: (ref2) => formRefs.current[key] = ref2,
                      schema: {
                        type: prop.type,
                        properties: prop.properties,
                        description: prop.description,
                        items: prop.items
                      },
                      value: params[key],
                      onChange: (newValue) => {
                        setParams({
                          ...params,
                          [key]: newValue
                        });
                        setTimeout(checkValidationErrors, 100);
                      }
                    }
                  ) })
                }
              )
            ] }, key);
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "pb-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-sm font-semibold", children: "Tool-specific Metadata:" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                size: "sm",
                variant: "outline",
                className: "h-6 px-2",
                onClick: () => setMetadataEntries((prev) => [
                  ...prev,
                  {
                    id: globalThis.crypto?.randomUUID?.() || Math.random().toString(36).slice(2),
                    key: "",
                    value: ""
                  }
                ]),
                children: "Add Pair"
              }
            )
          ] }),
          metadataEntries.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-muted-foreground", children: "No metadata pairs." }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: metadataEntries.map((entry, index2) => {
            const trimmedKey = entry.key.trim();
            const hasInvalidPrefix = trimmedKey !== "" && !hasValidMetaPrefix(trimmedKey);
            const isReservedKey = trimmedKey !== "" && isReservedMetaKey(trimmedKey);
            const hasInvalidName = trimmedKey !== "" && !hasValidMetaName(trimmedKey);
            const validationMessage = hasInvalidPrefix ? META_PREFIX_RULES_MESSAGE : isReservedKey ? RESERVED_NAMESPACE_MESSAGE : hasInvalidName ? META_NAME_RULES_MESSAGE : null;
            return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 w-full", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Label$1,
                  {
                    htmlFor: `metadata-key-${entry.id}`,
                    className: "text-xs shrink-0",
                    children: "Key"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: `metadata-key-${entry.id}`,
                    value: entry.key,
                    placeholder: "e.g. requestId",
                    onChange: (e2) => {
                      const value = e2.target.value;
                      setMetadataEntries(
                        (prev) => prev.map(
                          (m2, i2) => i2 === index2 ? { ...m2, key: value } : m2
                        )
                      );
                    },
                    className: cn$1(
                      "h-8 flex-1",
                      validationMessage && "border-red-500 focus-visible:ring-red-500 focus-visible:ring-1"
                    ),
                    "aria-invalid": Boolean(validationMessage)
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Label$1,
                  {
                    htmlFor: `metadata-value-${entry.id}`,
                    className: "text-xs shrink-0",
                    children: "Value"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: `metadata-value-${entry.id}`,
                    value: entry.value,
                    placeholder: "e.g. 12345",
                    onChange: (e2) => {
                      const value = e2.target.value;
                      setMetadataEntries(
                        (prev) => prev.map(
                          (m2, i2) => i2 === index2 ? { ...m2, value } : m2
                        )
                      );
                    },
                    className: "h-8 flex-1",
                    disabled: Boolean(validationMessage)
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    size: "sm",
                    variant: "ghost",
                    className: "h-8 w-8 p-0 ml-auto shrink-0",
                    onClick: () => setMetadataEntries(
                      (prev) => prev.filter((_2, i2) => i2 !== index2)
                    ),
                    "aria-label": `Remove meta pair ${index2 + 1}`,
                    children: "-"
                  }
                )
              ] }),
              validationMessage && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-red-600 dark:text-red-400", children: validationMessage })
            ] }, entry.id);
          }) }),
          (hasReservedMetadataEntry || hasInvalidMetaPrefixEntry || hasInvalidMetaNameEntry) && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-red-600 dark:text-red-400", children: "Remove reserved or invalid metadata keys (prefix/name) before running the tool." })
        ] }),
        selectedTool.outputSchema && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900 p-3 rounded-lg", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-sm font-semibold", children: "Output Schema:" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                size: "sm",
                variant: "ghost",
                onClick: () => setIsOutputSchemaExpanded(!isOutputSchemaExpanded),
                className: "h-6 px-2",
                children: isOutputSchemaExpanded ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronUp, { className: "h-3 w-3 mr-1" }),
                  "Collapse"
                ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDown, { className: "h-3 w-3 mr-1" }),
                  "Expand"
                ] })
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: `transition-all ${isOutputSchemaExpanded ? "" : "max-h-[8rem] overflow-y-auto"}`,
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: selectedTool.outputSchema })
            }
          )
        ] }),
        selectedTool && hasMeta(selectedTool) && selectedTool._meta && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900 p-3 rounded-lg", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-sm font-semibold", children: "Meta:" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                size: "sm",
                variant: "ghost",
                onClick: () => setIsMetadataExpanded(!isMetadataExpanded),
                className: "h-6 px-2",
                children: isMetadataExpanded ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronUp, { className: "h-3 w-3 mr-1" }),
                  "Collapse"
                ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDown, { className: "h-3 w-3 mr-1" }),
                  "Expand"
                ] })
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: `transition-all ${isMetadataExpanded ? "" : "max-h-[8rem] overflow-y-auto"}`,
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: selectedTool._meta })
            }
          )
        ] }),
        taskSupport !== "forbidden" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center space-x-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Checkbox,
            {
              id: "run-as-task",
              checked: runAsTask,
              onCheckedChange: (checked) => setRunAsTask(checked),
              disabled: taskSupport === "required"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Label$1,
            {
              htmlFor: "run-as-task",
              className: "text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer",
              children: "Run as task"
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            onClick: async () => {
              if (checkValidationErrors(true)) return;
              try {
                setIsToolRunning(true);
                const metadata2 = metadataEntries.reduce((acc, { key, value }) => {
                  const trimmedKey = key.trim();
                  if (trimmedKey !== "" && hasValidMetaPrefix(trimmedKey) && !isReservedMetaKey(trimmedKey) && hasValidMetaName(trimmedKey)) {
                    acc[trimmedKey] = value;
                  }
                  return acc;
                }, {});
                await callTool(
                  selectedTool.name,
                  params,
                  Object.keys(metadata2).length ? metadata2 : void 0,
                  runAsTask
                );
              } finally {
                setIsToolRunning(false);
              }
            },
            disabled: isToolRunning || isPollingTask || hasValidationErrors || hasReservedMetadataEntry || hasInvalidMetaPrefixEntry || hasInvalidMetaNameEntry,
            children: isToolRunning || isPollingTask ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(LoaderCircle, { className: "w-4 h-4 mr-2 animate-spin" }),
              isPollingTask ? "Polling Task..." : "Running..."
            ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Send, { className: "w-4 h-4 mr-2" }),
              "Run Tool"
            ] })
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: async () => {
              try {
                navigator.clipboard.writeText(
                  JSON.stringify(params, null, 2)
                );
                setCopied(true);
              } catch (error2) {
                toast2({
                  title: "Error",
                  description: `There was an error copying input to the clipboard: ${error2 instanceof Error ? error2.message : String(error2)}`,
                  variant: "destructive"
                });
              }
            },
            children: [
              copied ? /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCheck, { className: "h-4 w-4 mr-2 dark:text-green-700 text-green-600" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "h-4 w-4 mr-2" }),
              "Copy Input"
            ]
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          ToolResults,
          {
            toolResult,
            selectedTool,
            resourceContent,
            onReadResource,
            isPollingTask
          }
        )
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Alert, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { children: "Select a tool from the list to view its details and run it" }) }) })
    ] })
  ] }) });
};
const TaskStatusIcon = ({ status }) => {
  switch (status) {
    case "working":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(Clock, { className: "h-4 w-4 animate-pulse text-blue-500" });
    case "input_required":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(TriangleAlert, { className: "h-4 w-4 text-yellow-500" });
    case "completed":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(CircleCheck, { className: "h-4 w-4 text-green-500" });
    case "failed":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(CircleX, { className: "h-4 w-4 text-red-500" });
    case "cancelled":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(CircleX, { className: "h-4 w-4 text-gray-500" });
    default:
      return /* @__PURE__ */ jsxRuntimeExports.jsx(CirclePlay, { className: "h-4 w-4" });
  }
};
const TasksTab = ({
  tasks,
  listTasks,
  clearTasks,
  cancelTask,
  selectedTask,
  setSelectedTask,
  error,
  nextCursor
}) => {
  const [isCancelling, setIsCancelling] = reactExports.useState(null);
  const displayedTask = selectedTask ? tasks.find((t2) => t2.taskId === selectedTask.taskId) || selectedTask : null;
  const handleCancel = async (taskId) => {
    setIsCancelling(taskId);
    try {
      await cancelTask(taskId);
    } finally {
      setIsCancelling(null);
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(TabsContent, { value: "tasks", className: "flex-1 overflow-hidden p-0 m-0", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex h-full overflow-hidden p-4 gap-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-1/3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      ListPane,
      {
        title: "Tasks",
        items: tasks,
        setSelectedItem: setSelectedTask,
        listItems: listTasks,
        clearItems: clearTasks,
        buttonText: nextCursor ? "List More Tasks" : "List Tasks",
        isButtonDisabled: !nextCursor && tasks.length > 0,
        renderItem: (task) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 overflow-hidden w-full", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(TaskStatusIcon, { status: task.status }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col overflow-hidden", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "truncate font-medium", children: task.taskId }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "truncate text-xs text-muted-foreground", children: [
              task.status,
              " -",
              " ",
              new Date(task.lastUpdatedAt).toLocaleString()
            ] })
          ] })
        ] })
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 overflow-y-auto p-4 bg-background border border-border rounded-lg", children: [
      error && /* @__PURE__ */ jsxRuntimeExports.jsxs(Alert, { variant: "destructive", className: "mb-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CircleAlert, { className: "h-4 w-4" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTitle, { children: "Error" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { children: error })
      ] }),
      displayedTask ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between border-b pb-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-2xl font-bold tracking-tight", children: "Task Details" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-muted-foreground", children: [
              "ID: ",
              displayedTask.taskId
            ] })
          ] }),
          (displayedTask.status === "working" || displayedTask.status === "input_required") && /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "destructive",
              size: "sm",
              "aria-label": `Cancel task ${displayedTask.taskId}`,
              onClick: () => handleCancel(displayedTask.taskId),
              disabled: isCancelling === displayedTask.taskId,
              children: [
                isCancelling === displayedTask.taskId ? /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "mr-2 h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(CircleX, { className: "mr-2 h-4 w-4" }),
                "Cancel Task"
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-lg border p-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-muted-foreground", children: "Status" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-1 flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(TaskStatusIcon, { status: displayedTask.status }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: cn$1(
                    "font-semibold capitalize",
                    displayedTask.status === "working" && "text-blue-500",
                    displayedTask.status === "completed" && "text-green-500",
                    displayedTask.status === "failed" && "text-red-500",
                    displayedTask.status === "cancelled" && "text-gray-500",
                    displayedTask.status === "input_required" && "text-yellow-500"
                  ),
                  children: displayedTask.status.replace("_", " ")
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-lg border p-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-muted-foreground", children: "Last Updated" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 font-medium", children: new Date(displayedTask.lastUpdatedAt).toLocaleString() })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-lg border p-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-muted-foreground", children: "Created At" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 font-medium", children: new Date(displayedTask.createdAt).toLocaleString() })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-lg border p-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-muted-foreground", children: "TTL" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 font-medium", children: displayedTask.ttl === null ? "Infinite" : `${displayedTask.ttl}ms` })
          ] })
        ] }),
        displayedTask.statusMessage && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-lg border p-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-muted-foreground", children: "Status Message" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 whitespace-pre-wrap", children: displayedTask.statusMessage })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold", children: "Full Task Object" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "rounded-md border", children: /* @__PURE__ */ jsxRuntimeExports.jsx(JsonView, { data: displayedTask }) })
        ] })
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex h-full items-center justify-center text-muted-foreground", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Clock, { className: "mx-auto mb-4 h-12 w-12 opacity-20" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-medium", children: "No Task Selected" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Select a task from the list to view its details." }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            size: "sm",
            className: "mt-4",
            onClick: listTasks,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "mr-2 h-4 w-4" }),
              "Refresh Tasks"
            ]
          }
        )
      ] }) })
    ] })
  ] }) });
};
var oc = Object.defineProperty;
var uc = (e2, i2, n) => i2 in e2 ? oc(e2, i2, { enumerable: true, configurable: true, writable: true, value: n }) : e2[i2] = n;
var L = (e2, i2, n) => uc(e2, typeof i2 != "symbol" ? i2 + "" : i2, n);
var Zc = Object.defineProperty, Nc = (e2) => e2;
function Pc(e2, i2) {
  this[e2] = Nc.bind(null, i2);
}
var le = (e2, i2) => {
  for (var n in i2) Zc(e2, n, { get: i2[n], enumerable: true, configurable: true, set: Pc.bind(i2, n) });
}, pa = "2026-01-26", Dc = "ui/notifications/sandbox-proxy-ready", l = {};
le(l, { xor: () => Nd, xid: () => td, void: () => Sd, uuidv7: () => Gl, uuidv6: () => Vl, uuidv4: () => Wl, uuid: () => ql, util: () => S, url: () => Kl, uppercase: () => qt, unknown: () => we, union: () => yi, undefined: () => xd, ulid: () => ed, uint64: () => kd, uint32: () => bd, tuple: () => sr, trim: () => Ht, treeifyError: () => Oa, transform: () => ki, toUpperCase: () => Yt, toLowerCase: () => Xt, toJSONSchema: () => kl, templateLiteral: () => Wd, symbol: () => Id, superRefine: () => Er, success: () => Md, stringbool: () => Yd, stringFormat: () => md, string: () => Pt, strictObject: () => jd, startsWith: () => Vt, slugify: () => Qt, size: () => lt, setErrorMap: () => iv, set: () => Ad, safeParseAsync: () => Pl, safeParse: () => Nl, safeEncodeAsync: () => Ll, safeEncode: () => Rl, safeDecodeAsync: () => Jl, safeDecode: () => Cl, registry: () => mn, regexes: () => ze, regex: () => Mt, refine: () => Dr, record: () => lr, readonly: () => Ur, property: () => An, promise: () => Vd, prettifyError: () => Za, preprocess: () => ec, prefault: () => _r, positive: () => Pn, pipe: () => Ye, partialRecord: () => Dd, parseAsync: () => Zl, parse: () => jl, overwrite: () => ce, optional: () => He, object: () => Od, number: () => Vn, nullish: () => Jd, nullable: () => Xe, null: () => Xn, normalize: () => Bt, nonpositive: () => En, nonoptional: () => kr, nonnegative: () => Tn, never: () => $i, negative: () => Dn, nativeEnum: () => Rd, nanoid: () => Xl, nan: () => Fd, multipleOf: () => Te, minSize: () => ve, minLength: () => xe, mime: () => Kt, meta: () => Hd, maxSize: () => Je, maxLength: () => dt, map: () => Td, mac: () => rd, lte: () => ee, lt: () => fe, lowercase: () => Ft, looseRecord: () => Ed, looseObject: () => Zd, locales: () => cn, literal: () => Cd, length: () => ct, lazy: () => Zr, ksuid: () => id, keyof: () => Ud, jwt: () => cd, json: () => Qd, iso: () => Ln, ipv6: () => ad, ipv4: () => nd, intersection: () => or, int64: () => _d, int32: () => $d, int: () => Dt, instanceof: () => Xd, includes: () => Wt, httpUrl: () => Bl, hostname: () => fd, hex: () => pd, hash: () => vd, guid: () => Fl, gte: () => V, gt: () => pe, globalRegistry: () => Q, getErrorMap: () => nv, function: () => Et, fromJSONSchema: () => uv, formatError: () => qi, float64: () => hd, float32: () => gd, flattenError: () => Fi, file: () => Ld, exactOptional: () => gr, enum: () => _i, endsWith: () => Gt, encodeAsync: () => Tl, encode: () => Dl, emoji: () => Hl, email: () => Ml, e164: () => dd, discriminatedUnion: () => Pd, describe: () => Bd, decodeAsync: () => Al, decode: () => El, date: () => zd, custom: () => Kd, cuid2: () => Ql, cuid: () => Yl, core: () => va, config: () => F, coerce: () => ic, codec: () => qd, clone: () => ie, cidrv6: () => ud, cidrv4: () => od, check: () => Gd, catch: () => wr, boolean: () => Gn, bigint: () => yd, base64url: () => ld, base64: () => sd, array: () => $t, any: () => wd, _function: () => Et, _default: () => br, _ZodString: () => ei, ZodXor: () => nr, ZodXID: () => ui, ZodVoid: () => tr, ZodUnknown: () => Qn, ZodUnion: () => yt, ZodUndefined: () => Bn, ZodUUID: () => oe, ZodURL: () => pt, ZodULID: () => oi, ZodType: () => I, ZodTuple: () => ur, ZodTransform: () => pr, ZodTemplateLiteral: () => Or, ZodSymbol: () => Kn, ZodSuccess: () => Ir, ZodStringFormat: () => N, ZodString: () => ft, ZodSet: () => cr, ZodRecord: () => _t, ZodRealError: () => B, ZodReadonly: () => zr, ZodPromise: () => Nr, ZodPrefault: () => yr, ZodPipe: () => wi, ZodOptional: () => Ii, ZodObject: () => bt, ZodNumberFormat: () => Ue, ZodNumber: () => vt, ZodNullable: () => hr, ZodNull: () => Hn, ZodNonOptional: () => xi, ZodNever: () => er, ZodNanoID: () => ni, ZodNaN: () => Sr, ZodMap: () => dr, ZodMAC: () => Wn, ZodLiteral: () => mr, ZodLazy: () => jr, ZodKSUID: () => si, ZodJWT: () => gi, ZodIssueCode: () => tv, ZodIntersection: () => ar, ZodISOTime: () => Fn, ZodISODuration: () => qn, ZodISODateTime: () => Jn, ZodISODate: () => Mn, ZodIPv6: () => di, ZodIPv4: () => li, ZodGUID: () => Be, ZodFunction: () => Pr, ZodFirstPartyTypeKind: () => Ci, ZodFile: () => fr, ZodExactOptional: () => vr, ZodError: () => ev, ZodEnum: () => Le, ZodEmoji: () => ii, ZodEmail: () => ti, ZodE164: () => vi, ZodDiscriminatedUnion: () => rr, ZodDefault: () => $r, ZodDate: () => bi, ZodCustomStringFormat: () => Me, ZodCustom: () => kt, ZodCodec: () => Si, ZodCatch: () => xr, ZodCUID2: () => ai, ZodCUID: () => ri, ZodCIDRv6: () => mi, ZodCIDRv4: () => ci, ZodBoolean: () => gt, ZodBigIntFormat: () => hi, ZodBigInt: () => ht, ZodBase64URL: () => pi, ZodBase64: () => fi, ZodArray: () => ir, ZodAny: () => Yn, TimePrecision: () => ts, NEVER: () => ga, $output: () => Bu, $input: () => Hu, $brand: () => ha });
var va = {};
le(va, { version: () => No, util: () => S, treeifyError: () => Oa, toJSONSchema: () => kl, toDotPath: () => ja, safeParseAsync: () => Pa, safeParse: () => Na, safeEncodeAsync: () => fm, safeEncode: () => cm, safeDecodeAsync: () => pm, safeDecode: () => mm, registry: () => mn, regexes: () => ze, process: () => O, prettifyError: () => Za, parseAsync: () => Ti, parse: () => Ei, meta: () => Ts, locales: () => cn, isValidJWT: () => nu, isValidBase64URL: () => eu, isValidBase64: () => rn, initializeContext: () => Ae, globalRegistry: () => Q, globalConfig: () => zt, formatError: () => qi, flattenError: () => Fi, finalize: () => Ce, extractDefs: () => Re, encodeAsync: () => lm, encode: () => um, describe: () => Es, decodeAsync: () => dm, decode: () => sm, createToJSONSchemaMethod: () => Rs, createStandardJSONSchemaMethod: () => Ke, config: () => F, clone: () => ie, _xor: () => Op, _xid: () => In, _void: () => ws, _uuidv7: () => hn, _uuidv6: () => gn, _uuidv4: () => vn, _uuid: () => pn, _url: () => Jt, _uppercase: () => qt, _unknown: () => Is, _union: () => Up, _undefined: () => ys, _ulid: () => kn, _uint64: () => $s, _uint32: () => ms, _tuple: () => Np, _trim: () => Ht, _transform: () => Cp, _toUpperCase: () => Yt, _toLowerCase: () => Xt, _templateLiteral: () => Kp, _symbol: () => bs, _superRefine: () => Ps, _success: () => qp, _stringbool: () => As, _stringFormat: () => mt, _string: () => Yu, _startsWith: () => Vt, _slugify: () => Qt, _size: () => lt, _set: () => Ep, _safeParseAsync: () => rt, _safeParse: () => nt, _safeEncodeAsync: () => Xi, _safeEncode: () => Bi, _safeDecodeAsync: () => Yi, _safeDecode: () => Hi, _regex: () => Mt, _refine: () => Ns, _record: () => Pp, _readonly: () => Gp, _property: () => An, _promise: () => Hp, _positive: () => Pn, _pipe: () => Vp, _parseAsync: () => it, _parse: () => tt, _overwrite: () => ce, _optional: () => Lp, _number: () => os, _nullable: () => Jp, _null: () => _s, _normalize: () => Bt, _nonpositive: () => En, _nonoptional: () => Fp, _nonnegative: () => Tn, _never: () => xs, _negative: () => Dn, _nativeEnum: () => Ap, _nanoid: () => bn, _nan: () => Us, _multipleOf: () => Te, _minSize: () => ve, _minLength: () => xe, _min: () => V, _mime: () => Kt, _maxSize: () => Je, _maxLength: () => dt, _max: () => ee, _map: () => Dp, _mac: () => es, _lte: () => ee, _lt: () => fe, _lowercase: () => Ft, _literal: () => Rp, _length: () => ct, _lazy: () => Bp, _ksuid: () => xn, _jwt: () => Nn, _isoTime: () => rs, _isoDuration: () => as, _isoDateTime: () => is, _isoDate: () => ns, _ipv6: () => Sn, _ipv4: () => wn, _intersection: () => Zp, _int64: () => hs, _int32: () => cs, _int: () => ss, _includes: () => Wt, _guid: () => Nt, _gte: () => V, _gt: () => pe, _float64: () => ds, _float32: () => ls, _file: () => js, _enum: () => Tp, _endsWith: () => Gt, _encodeAsync: () => Gi, _encode: () => Wi, _emoji: () => $n, _email: () => fn, _e164: () => Zn, _discriminatedUnion: () => jp, _default: () => Mp, _decodeAsync: () => Ki, _decode: () => Vi, _date: () => Ss, _custom: () => Zs, _cuid2: () => _n, _cuid: () => yn, _coercedString: () => Qu, _coercedNumber: () => us, _coercedDate: () => zs, _coercedBoolean: () => ps, _coercedBigint: () => gs, _cidrv6: () => Un, _cidrv4: () => zn, _check: () => Ds, _catch: () => Wp, _boolean: () => fs, _bigint: () => vs, _base64url: () => jn, _base64: () => On, _array: () => Os, _any: () => ks, TimePrecision: () => ts, NEVER: () => ga, JSONSchemaGenerator: () => Yp, JSONSchema: () => Qp, Doc: () => Zo, $output: () => Bu, $input: () => Hu, $constructor: () => f, $brand: () => ha, $ZodXor: () => _u, $ZodXID: () => Mo, $ZodVoid: () => pu, $ZodUnknown: () => mu, $ZodUnion: () => Lt, $ZodUndefined: () => lu, $ZodUUID: () => Do, $ZodURL: () => To, $ZodULID: () => Jo, $ZodType: () => k, $ZodTuple: () => sn, $ZodTransform: () => ju, $ZodTemplateLiteral: () => Ju, $ZodSymbol: () => su, $ZodSuccess: () => Tu, $ZodStringFormat: () => Z, $ZodString: () => st, $ZodSet: () => Su, $ZodRegistry: () => Xu, $ZodRecord: () => xu, $ZodRealError: () => K, $ZodReadonly: () => Lu, $ZodPromise: () => Fu, $ZodPrefault: () => Du, $ZodPipe: () => Cu, $ZodOptional: () => ln, $ZodObjectJIT: () => yu, $ZodObject: () => bu, $ZodNumberFormat: () => ou, $ZodNumber: () => an, $ZodNullable: () => Nu, $ZodNull: () => du, $ZodNonOptional: () => Eu, $ZodNever: () => fu, $ZodNanoID: () => Ro, $ZodNaN: () => Ru, $ZodMap: () => wu, $ZodMAC: () => Ho, $ZodLiteral: () => Uu, $ZodLazy: () => qu, $ZodKSUID: () => Fo, $ZodJWT: () => ru, $ZodIntersection: () => Iu, $ZodISOTime: () => Vo, $ZodISODuration: () => Go, $ZodISODateTime: () => qo, $ZodISODate: () => Wo, $ZodIPv6: () => Bo, $ZodIPv4: () => Ko, $ZodGUID: () => Po, $ZodFunction: () => Mu, $ZodFile: () => Ou, $ZodExactOptional: () => Zu, $ZodError: () => Mi, $ZodEnum: () => zu, $ZodEncodeError: () => Tt, $ZodEmoji: () => Ao, $ZodEmail: () => Eo, $ZodE164: () => iu, $ZodDiscriminatedUnion: () => ku, $ZodDefault: () => Pu, $ZodDate: () => vu, $ZodCustomStringFormat: () => au, $ZodCustom: () => Wu, $ZodCodec: () => dn, $ZodCheckUpperCase: () => xo, $ZodCheckStringFormat: () => ut, $ZodCheckStartsWith: () => So, $ZodCheckSizeEquals: () => $o, $ZodCheckRegex: () => ko, $ZodCheckProperty: () => Uo, $ZodCheckOverwrite: () => jo, $ZodCheckNumberFormat: () => po, $ZodCheckMultipleOf: () => fo, $ZodCheckMinSize: () => ho, $ZodCheckMinLength: () => yo, $ZodCheckMimeType: () => Oo, $ZodCheckMaxSize: () => go, $ZodCheckMaxLength: () => bo, $ZodCheckLowerCase: () => Io, $ZodCheckLessThan: () => tn, $ZodCheckLengthEquals: () => _o, $ZodCheckIncludes: () => wo, $ZodCheckGreaterThan: () => nn, $ZodCheckEndsWith: () => zo, $ZodCheckBigIntFormat: () => vo, $ZodCheck: () => E, $ZodCatch: () => Au, $ZodCUID2: () => Lo, $ZodCUID: () => Co, $ZodCIDRv6: () => Yo, $ZodCIDRv4: () => Xo, $ZodBoolean: () => on, $ZodBigIntFormat: () => uu, $ZodBigInt: () => un, $ZodBase64URL: () => tu, $ZodBase64: () => Qo, $ZodAsyncError: () => ke, $ZodArray: () => gu, $ZodAny: () => cu });
var ga = Object.freeze({ status: "aborted" });
function f(e2, i2, n) {
  function a2(u2, d) {
    if (u2._zod || Object.defineProperty(u2, "_zod", { value: { def: d, constr: o2, traits: /* @__PURE__ */ new Set() }, enumerable: false }), u2._zod.traits.has(e2)) return;
    u2._zod.traits.add(e2), i2(u2, d);
    let s2 = o2.prototype, m2 = Object.keys(s2);
    for (let c = 0; c < m2.length; c++) {
      let p2 = m2[c];
      p2 in u2 || (u2[p2] = s2[p2].bind(u2));
    }
  }
  let t2 = (n == null ? void 0 : n.Parent) ?? Object;
  class r2 extends t2 {
  }
  Object.defineProperty(r2, "name", { value: e2 });
  function o2(u2) {
    var d;
    let s2 = n != null && n.Parent ? new r2() : this;
    a2(s2, u2), (d = s2._zod).deferred ?? (d.deferred = []);
    for (let m2 of s2._zod.deferred) m2();
    return s2;
  }
  return Object.defineProperty(o2, "init", { value: a2 }), Object.defineProperty(o2, Symbol.hasInstance, { value: (u2) => {
    var d, s2;
    return n != null && n.Parent && u2 instanceof n.Parent ? true : (s2 = (d = u2 == null ? void 0 : u2._zod) == null ? void 0 : d.traits) == null ? void 0 : s2.has(e2);
  } }), Object.defineProperty(o2, "name", { value: e2 }), o2;
}
var ha = /* @__PURE__ */ Symbol("zod_brand");
class ke extends Error {
  constructor() {
    super("Encountered Promise during synchronous parse. Use .parseAsync() instead.");
  }
}
class Tt extends Error {
  constructor(i2) {
    super(`Encountered unidirectional transform during encode: ${i2}`), this.name = "ZodEncodeError";
  }
}
var zt = {};
function F(e2) {
  return e2 && Object.assign(zt, e2), zt;
}
var S = {};
le(S, { unwrapMessage: () => Ge, uint8ArrayToHex: () => am, uint8ArrayToBase64url: () => nm, uint8ArrayToBase64: () => za, stringifyPrimitive: () => b, slugify: () => ba, shallowClone: () => _a, safeExtend: () => Xc, required: () => em, randomString: () => qc, propertyKeyTypes: () => Ot, promiseAllObject: () => Fc, primitiveTypes: () => ka, prefixIssues: () => re, pick: () => Kc, partial: () => Qc, parsedType: () => _, optionalKeys: () => Ia, omit: () => Bc, objectClone: () => Lc, numKeys: () => Wc, nullish: () => Se, normalizeParams: () => g, mergeDefs: () => de, merge: () => Yc, jsonStringifyReplacer: () => Ut, joinValues: () => v, issue: () => jt, isPlainObject: () => Ie, isObject: () => De, hexToUint8Array: () => rm, getSizableOrigin: () => Rt, getParsedType: () => Vc, getLengthableOrigin: () => Ct, getEnumValues: () => Li, getElementAtPath: () => Mc, floatSafeRemainder: () => $a, finalizeIssue: () => te, extend: () => Hc, escapeRegex: () => se, esc: () => Di, defineLazy: () => w, createTransparentProxy: () => Gc, cloneDef: () => Jc, clone: () => ie, cleanRegex: () => At, cleanEnum: () => tm, captureStackTrace: () => Ji, cached: () => et, base64urlToUint8Array: () => im, base64ToUint8Array: () => Sa, assignProp: () => ge, assertNotEqual: () => Tc, assertNever: () => Rc, assertIs: () => Ac, assertEqual: () => Ec, assert: () => Cc, allowsEval: () => ya, aborted: () => _e, NUMBER_FORMAT_RANGES: () => xa, Class: () => om, BIGINT_FORMAT_RANGES: () => wa });
function Ec(e2) {
  return e2;
}
function Tc(e2) {
  return e2;
}
function Ac(e2) {
}
function Rc(e2) {
  throw Error("Unexpected value in exhaustive check");
}
function Cc(e2) {
}
function Li(e2) {
  let i2 = Object.values(e2).filter((n) => typeof n == "number");
  return Object.entries(e2).filter(([n, a2]) => i2.indexOf(+n) === -1).map(([n, a2]) => a2);
}
function v(e2, i2 = "|") {
  return e2.map((n) => b(n)).join(i2);
}
function Ut(e2, i2) {
  return typeof i2 == "bigint" ? i2.toString() : i2;
}
function et(e2) {
  return { get value() {
    {
      let i2 = e2();
      return Object.defineProperty(this, "value", { value: i2 }), i2;
    }
  } };
}
function Se(e2) {
  return e2 == null;
}
function At(e2) {
  let i2 = e2.startsWith("^") ? 1 : 0, n = e2.endsWith("$") ? e2.length - 1 : e2.length;
  return e2.slice(i2, n);
}
function $a(e2, i2) {
  let n = (e2.toString().split(".")[1] || "").length, a2 = i2.toString(), t2 = (a2.split(".")[1] || "").length;
  if (t2 === 0 && /\d?e-\d?/.test(a2)) {
    let d = a2.match(/\d?e-(\d?)/);
    d != null && d[1] && (t2 = Number.parseInt(d[1]));
  }
  let r2 = n > t2 ? n : t2, o2 = Number.parseInt(e2.toFixed(r2).replace(".", "")), u2 = Number.parseInt(i2.toFixed(r2).replace(".", ""));
  return o2 % u2 / 10 ** r2;
}
var Fr = /* @__PURE__ */ Symbol("evaluating");
function w(e2, i2, n) {
  let a2;
  Object.defineProperty(e2, i2, { get() {
    if (a2 !== Fr)
      return a2 === void 0 && (a2 = Fr, a2 = n()), a2;
  }, set(t2) {
    Object.defineProperty(e2, i2, { value: t2 });
  }, configurable: true });
}
function Lc(e2) {
  return Object.create(Object.getPrototypeOf(e2), Object.getOwnPropertyDescriptors(e2));
}
function ge(e2, i2, n) {
  Object.defineProperty(e2, i2, { value: n, writable: true, enumerable: true, configurable: true });
}
function de(...e2) {
  let i2 = {};
  for (let n of e2) {
    let a2 = Object.getOwnPropertyDescriptors(n);
    Object.assign(i2, a2);
  }
  return Object.defineProperties({}, i2);
}
function Jc(e2) {
  return de(e2._zod.def);
}
function Mc(e2, i2) {
  return i2 ? i2.reduce((n, a2) => n == null ? void 0 : n[a2], e2) : e2;
}
function Fc(e2) {
  let i2 = Object.keys(e2), n = i2.map((a2) => e2[a2]);
  return Promise.all(n).then((a2) => {
    let t2 = {};
    for (let r2 = 0; r2 < i2.length; r2++) t2[i2[r2]] = a2[r2];
    return t2;
  });
}
function qc(e2 = 10) {
  let i2 = "";
  for (let n = 0; n < e2; n++) i2 += "abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random() * 26)];
  return i2;
}
function Di(e2) {
  return JSON.stringify(e2);
}
function ba(e2) {
  return e2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
}
var Ji = "captureStackTrace" in Error ? Error.captureStackTrace : (...e2) => {
};
function De(e2) {
  return typeof e2 == "object" && e2 !== null && !Array.isArray(e2);
}
var ya = et(() => {
  var e2;
  if (typeof navigator < "u" && ((e2 = navigator == null ? void 0 : navigator.userAgent) != null && e2.includes("Cloudflare"))) return false;
  try {
    return new Function(""), true;
  } catch {
    return false;
  }
});
function Ie(e2) {
  if (De(e2) === false) return false;
  let i2 = e2.constructor;
  if (i2 === void 0 || typeof i2 != "function") return true;
  let n = i2.prototype;
  return !(De(n) === false || Object.prototype.hasOwnProperty.call(n, "isPrototypeOf") === false);
}
function _a(e2) {
  return Ie(e2) ? { ...e2 } : Array.isArray(e2) ? [...e2] : e2;
}
function Wc(e2) {
  let i2 = 0;
  for (let n in e2) Object.prototype.hasOwnProperty.call(e2, n) && i2++;
  return i2;
}
var Vc = (e2) => {
  let i2 = typeof e2;
  switch (i2) {
    case "undefined":
      return "undefined";
    case "string":
      return "string";
    case "number":
      return Number.isNaN(e2) ? "nan" : "number";
    case "boolean":
      return "boolean";
    case "function":
      return "function";
    case "bigint":
      return "bigint";
    case "symbol":
      return "symbol";
    case "object":
      return Array.isArray(e2) ? "array" : e2 === null ? "null" : e2.then && typeof e2.then == "function" && e2.catch && typeof e2.catch == "function" ? "promise" : typeof Map < "u" && e2 instanceof Map ? "map" : typeof Set < "u" && e2 instanceof Set ? "set" : typeof Date < "u" && e2 instanceof Date ? "date" : typeof File < "u" && e2 instanceof File ? "file" : "object";
    default:
      throw Error(`Unknown data type: ${i2}`);
  }
}, Ot = /* @__PURE__ */ new Set(["string", "number", "symbol"]), ka = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
function se(e2) {
  return e2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function ie(e2, i2, n) {
  let a2 = new e2._zod.constr(i2 ?? e2._zod.def);
  return (!i2 || n != null && n.parent) && (a2._zod.parent = e2), a2;
}
function g(e2) {
  let i2 = e2;
  if (!i2) return {};
  if (typeof i2 == "string") return { error: () => i2 };
  if ((i2 == null ? void 0 : i2.message) !== void 0) {
    if ((i2 == null ? void 0 : i2.error) !== void 0) throw Error("Cannot specify both `message` and `error` params");
    i2.error = i2.message;
  }
  return delete i2.message, typeof i2.error == "string" ? { ...i2, error: () => i2.error } : i2;
}
function Gc(e2) {
  let i2;
  return new Proxy({}, { get(n, a2, t2) {
    return i2 ?? (i2 = e2()), Reflect.get(i2, a2, t2);
  }, set(n, a2, t2, r2) {
    return i2 ?? (i2 = e2()), Reflect.set(i2, a2, t2, r2);
  }, has(n, a2) {
    return i2 ?? (i2 = e2()), Reflect.has(i2, a2);
  }, deleteProperty(n, a2) {
    return i2 ?? (i2 = e2()), Reflect.deleteProperty(i2, a2);
  }, ownKeys(n) {
    return i2 ?? (i2 = e2()), Reflect.ownKeys(i2);
  }, getOwnPropertyDescriptor(n, a2) {
    return i2 ?? (i2 = e2()), Reflect.getOwnPropertyDescriptor(i2, a2);
  }, defineProperty(n, a2, t2) {
    return i2 ?? (i2 = e2()), Reflect.defineProperty(i2, a2, t2);
  } });
}
function b(e2) {
  return typeof e2 == "bigint" ? e2.toString() + "n" : typeof e2 == "string" ? `"${e2}"` : `${e2}`;
}
function Ia(e2) {
  return Object.keys(e2).filter((i2) => e2[i2]._zod.optin === "optional" && e2[i2]._zod.optout === "optional");
}
var xa = { safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] }, wa = { int64: [BigInt("-9223372036854775808"), BigInt("9223372036854775807")], uint64: [BigInt(0), BigInt("18446744073709551615")] };
function Kc(e2, i2) {
  let n = e2._zod.def, a2 = n.checks;
  if (a2 && a2.length > 0) throw Error(".pick() cannot be used on object schemas containing refinements");
  let t2 = de(e2._zod.def, { get shape() {
    let r2 = {};
    for (let o2 in i2) {
      if (!(o2 in n.shape)) throw Error(`Unrecognized key: "${o2}"`);
      i2[o2] && (r2[o2] = n.shape[o2]);
    }
    return ge(this, "shape", r2), r2;
  }, checks: [] });
  return ie(e2, t2);
}
function Bc(e2, i2) {
  let n = e2._zod.def, a2 = n.checks;
  if (a2 && a2.length > 0) throw Error(".omit() cannot be used on object schemas containing refinements");
  let t2 = de(e2._zod.def, { get shape() {
    let r2 = { ...e2._zod.def.shape };
    for (let o2 in i2) {
      if (!(o2 in n.shape)) throw Error(`Unrecognized key: "${o2}"`);
      i2[o2] && delete r2[o2];
    }
    return ge(this, "shape", r2), r2;
  }, checks: [] });
  return ie(e2, t2);
}
function Hc(e2, i2) {
  if (!Ie(i2)) throw Error("Invalid input to extend: expected a plain object");
  let n = e2._zod.def.checks;
  if (n && n.length > 0) {
    let t2 = e2._zod.def.shape;
    for (let r2 in i2) if (Object.getOwnPropertyDescriptor(t2, r2) !== void 0) throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
  }
  let a2 = de(e2._zod.def, { get shape() {
    let t2 = { ...e2._zod.def.shape, ...i2 };
    return ge(this, "shape", t2), t2;
  } });
  return ie(e2, a2);
}
function Xc(e2, i2) {
  if (!Ie(i2)) throw Error("Invalid input to safeExtend: expected a plain object");
  let n = de(e2._zod.def, { get shape() {
    let a2 = { ...e2._zod.def.shape, ...i2 };
    return ge(this, "shape", a2), a2;
  } });
  return ie(e2, n);
}
function Yc(e2, i2) {
  let n = de(e2._zod.def, { get shape() {
    let a2 = { ...e2._zod.def.shape, ...i2._zod.def.shape };
    return ge(this, "shape", a2), a2;
  }, get catchall() {
    return i2._zod.def.catchall;
  }, checks: [] });
  return ie(e2, n);
}
function Qc(e2, i2, n) {
  let a2 = i2._zod.def.checks;
  if (a2 && a2.length > 0) throw Error(".partial() cannot be used on object schemas containing refinements");
  let t2 = de(i2._zod.def, { get shape() {
    let r2 = i2._zod.def.shape, o2 = { ...r2 };
    if (n) for (let u2 in n) {
      if (!(u2 in r2)) throw Error(`Unrecognized key: "${u2}"`);
      n[u2] && (o2[u2] = e2 ? new e2({ type: "optional", innerType: r2[u2] }) : r2[u2]);
    }
    else for (let u2 in r2) o2[u2] = e2 ? new e2({ type: "optional", innerType: r2[u2] }) : r2[u2];
    return ge(this, "shape", o2), o2;
  }, checks: [] });
  return ie(i2, t2);
}
function em(e2, i2, n) {
  let a2 = de(i2._zod.def, { get shape() {
    let t2 = i2._zod.def.shape, r2 = { ...t2 };
    if (n) for (let o2 in n) {
      if (!(o2 in r2)) throw Error(`Unrecognized key: "${o2}"`);
      n[o2] && (r2[o2] = new e2({ type: "nonoptional", innerType: t2[o2] }));
    }
    else for (let o2 in t2) r2[o2] = new e2({ type: "nonoptional", innerType: t2[o2] });
    return ge(this, "shape", r2), r2;
  } });
  return ie(i2, a2);
}
function _e(e2, i2 = 0) {
  var n;
  if (e2.aborted === true) return true;
  for (let a2 = i2; a2 < e2.issues.length; a2++) if (((n = e2.issues[a2]) == null ? void 0 : n.continue) !== true) return true;
  return false;
}
function re(e2, i2) {
  return i2.map((n) => {
    var a2;
    return (a2 = n).path ?? (a2.path = []), n.path.unshift(e2), n;
  });
}
function Ge(e2) {
  return typeof e2 == "string" ? e2 : e2 == null ? void 0 : e2.message;
}
function te(e2, i2, n) {
  var t2, r2, o2, u2, d, s2;
  let a2 = { ...e2, path: e2.path ?? [] };
  if (!e2.message) {
    let m2 = Ge((o2 = (r2 = (t2 = e2.inst) == null ? void 0 : t2._zod.def) == null ? void 0 : r2.error) == null ? void 0 : o2.call(r2, e2)) ?? Ge((u2 = i2 == null ? void 0 : i2.error) == null ? void 0 : u2.call(i2, e2)) ?? Ge((d = n.customError) == null ? void 0 : d.call(n, e2)) ?? Ge((s2 = n.localeError) == null ? void 0 : s2.call(n, e2)) ?? "Invalid input";
    a2.message = m2;
  }
  return delete a2.inst, delete a2.continue, !(i2 != null && i2.reportInput) && delete a2.input, a2;
}
function Rt(e2) {
  return e2 instanceof Set ? "set" : e2 instanceof Map ? "map" : e2 instanceof File ? "file" : "unknown";
}
function Ct(e2) {
  return Array.isArray(e2) ? "array" : typeof e2 == "string" ? "string" : "unknown";
}
function _(e2) {
  let i2 = typeof e2;
  switch (i2) {
    case "number":
      return Number.isNaN(e2) ? "nan" : "number";
    case "object": {
      if (e2 === null) return "null";
      if (Array.isArray(e2)) return "array";
      let n = e2;
      if (n && Object.getPrototypeOf(n) !== Object.prototype && "constructor" in n && n.constructor) return n.constructor.name;
    }
  }
  return i2;
}
function jt(...e2) {
  let [i2, n, a2] = e2;
  return typeof i2 == "string" ? { message: i2, code: "custom", input: n, inst: a2 } : { ...i2 };
}
function tm(e2) {
  return Object.entries(e2).filter(([i2, n]) => Number.isNaN(Number.parseInt(i2, 10))).map((i2) => i2[1]);
}
function Sa(e2) {
  let i2 = atob(e2), n = new Uint8Array(i2.length);
  for (let a2 = 0; a2 < i2.length; a2++) n[a2] = i2.charCodeAt(a2);
  return n;
}
function za(e2) {
  let i2 = "";
  for (let n = 0; n < e2.length; n++) i2 += String.fromCharCode(e2[n]);
  return btoa(i2);
}
function im(e2) {
  let i2 = e2.replace(/-/g, "+").replace(/_/g, "/"), n = "=".repeat((4 - i2.length % 4) % 4);
  return Sa(i2 + n);
}
function nm(e2) {
  return za(e2).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function rm(e2) {
  let i2 = e2.replace(/^0x/, "");
  if (i2.length % 2 !== 0) throw Error("Invalid hex string length");
  let n = new Uint8Array(i2.length / 2);
  for (let a2 = 0; a2 < i2.length; a2 += 2) n[a2 / 2] = Number.parseInt(i2.slice(a2, a2 + 2), 16);
  return n;
}
function am(e2) {
  return Array.from(e2).map((i2) => i2.toString(16).padStart(2, "0")).join("");
}
class om {
  constructor(...i2) {
  }
}
var Ua = (e2, i2) => {
  e2.name = "$ZodError", Object.defineProperty(e2, "_zod", { value: e2._zod, enumerable: false }), Object.defineProperty(e2, "issues", { value: i2, enumerable: false }), e2.message = JSON.stringify(i2, Ut, 2), Object.defineProperty(e2, "toString", { value: () => e2.message, enumerable: false });
}, Mi = f("$ZodError", Ua), K = f("$ZodError", Ua, { Parent: Error });
function Fi(e2, i2 = (n) => n.message) {
  let n = {}, a2 = [];
  for (let t2 of e2.issues) t2.path.length > 0 ? (n[t2.path[0]] = n[t2.path[0]] || [], n[t2.path[0]].push(i2(t2))) : a2.push(i2(t2));
  return { formErrors: a2, fieldErrors: n };
}
function qi(e2, i2 = (n) => n.message) {
  let n = { _errors: [] }, a2 = (t2) => {
    for (let r2 of t2.issues) if (r2.code === "invalid_union" && r2.errors.length) r2.errors.map((o2) => a2({ issues: o2 }));
    else if (r2.code === "invalid_key") a2({ issues: r2.issues });
    else if (r2.code === "invalid_element") a2({ issues: r2.issues });
    else if (r2.path.length === 0) n._errors.push(i2(r2));
    else {
      let o2 = n, u2 = 0;
      for (; u2 < r2.path.length; ) {
        let d = r2.path[u2];
        u2 !== r2.path.length - 1 ? o2[d] = o2[d] || { _errors: [] } : (o2[d] = o2[d] || { _errors: [] }, o2[d]._errors.push(i2(r2))), o2 = o2[d], u2++;
      }
    }
  };
  return a2(e2), n;
}
function Oa(e2, i2 = (n) => n.message) {
  let n = { errors: [] }, a2 = (t2, r2 = []) => {
    var o2, u2;
    for (let d of t2.issues) if (d.code === "invalid_union" && d.errors.length) d.errors.map((s2) => a2({ issues: s2 }, d.path));
    else if (d.code === "invalid_key") a2({ issues: d.issues }, d.path);
    else if (d.code === "invalid_element") a2({ issues: d.issues }, d.path);
    else {
      let s2 = [...r2, ...d.path];
      if (s2.length === 0) {
        n.errors.push(i2(d));
        continue;
      }
      let m2 = n, c = 0;
      for (; c < s2.length; ) {
        let p2 = s2[c], $2 = c === s2.length - 1;
        typeof p2 == "string" ? (m2.properties ?? (m2.properties = {}), (o2 = m2.properties)[p2] ?? (o2[p2] = { errors: [] }), m2 = m2.properties[p2]) : (m2.items ?? (m2.items = []), (u2 = m2.items)[p2] ?? (u2[p2] = { errors: [] }), m2 = m2.items[p2]), $2 && m2.errors.push(i2(d)), c++;
      }
    }
  };
  return a2(e2), n;
}
function ja(e2) {
  let i2 = [], n = e2.map((a2) => typeof a2 == "object" ? a2.key : a2);
  for (let a2 of n) typeof a2 == "number" ? i2.push(`[${a2}]`) : typeof a2 == "symbol" ? i2.push(`[${JSON.stringify(String(a2))}]`) : /[^\w$]/.test(a2) ? i2.push(`[${JSON.stringify(a2)}]`) : (i2.length && i2.push("."), i2.push(a2));
  return i2.join("");
}
function Za(e2) {
  var a2;
  let i2 = [], n = [...e2.issues].sort((t2, r2) => (t2.path ?? []).length - (r2.path ?? []).length);
  for (let t2 of n) i2.push(`✖ ${t2.message}`), (a2 = t2.path) != null && a2.length && i2.push(`  → at ${ja(t2.path)}`);
  return i2.join(`
`);
}
var tt = (e2) => (i2, n, a2, t2) => {
  let r2 = a2 ? Object.assign(a2, { async: false }) : { async: false }, o2 = i2._zod.run({ value: n, issues: [] }, r2);
  if (o2 instanceof Promise) throw new ke();
  if (o2.issues.length) {
    let u2 = new ((t2 == null ? void 0 : t2.Err) ?? e2)(o2.issues.map((d) => te(d, r2, F())));
    throw Ji(u2, t2 == null ? void 0 : t2.callee), u2;
  }
  return o2.value;
}, Ei = tt(K), it = (e2) => async (i2, n, a2, t2) => {
  let r2 = a2 ? Object.assign(a2, { async: true }) : { async: true }, o2 = i2._zod.run({ value: n, issues: [] }, r2);
  if (o2 instanceof Promise && (o2 = await o2), o2.issues.length) {
    let u2 = new ((t2 == null ? void 0 : t2.Err) ?? e2)(o2.issues.map((d) => te(d, r2, F())));
    throw Ji(u2, t2 == null ? void 0 : t2.callee), u2;
  }
  return o2.value;
}, Ti = it(K), nt = (e2) => (i2, n, a2) => {
  let t2 = a2 ? { ...a2, async: false } : { async: false }, r2 = i2._zod.run({ value: n, issues: [] }, t2);
  if (r2 instanceof Promise) throw new ke();
  return r2.issues.length ? { success: false, error: new (e2 ?? Mi)(r2.issues.map((o2) => te(o2, t2, F()))) } : { success: true, data: r2.value };
}, Na = nt(K), rt = (e2) => async (i2, n, a2) => {
  let t2 = a2 ? Object.assign(a2, { async: true }) : { async: true }, r2 = i2._zod.run({ value: n, issues: [] }, t2);
  return r2 instanceof Promise && (r2 = await r2), r2.issues.length ? { success: false, error: new e2(r2.issues.map((o2) => te(o2, t2, F()))) } : { success: true, data: r2.value };
}, Pa = rt(K), Wi = (e2) => (i2, n, a2) => {
  let t2 = a2 ? Object.assign(a2, { direction: "backward" }) : { direction: "backward" };
  return tt(e2)(i2, n, t2);
}, um = Wi(K), Vi = (e2) => (i2, n, a2) => tt(e2)(i2, n, a2), sm = Vi(K), Gi = (e2) => async (i2, n, a2) => {
  let t2 = a2 ? Object.assign(a2, { direction: "backward" }) : { direction: "backward" };
  return it(e2)(i2, n, t2);
}, lm = Gi(K), Ki = (e2) => async (i2, n, a2) => it(e2)(i2, n, a2), dm = Ki(K), Bi = (e2) => (i2, n, a2) => {
  let t2 = a2 ? Object.assign(a2, { direction: "backward" }) : { direction: "backward" };
  return nt(e2)(i2, n, t2);
}, cm = Bi(K), Hi = (e2) => (i2, n, a2) => nt(e2)(i2, n, a2), mm = Hi(K), Xi = (e2) => async (i2, n, a2) => {
  let t2 = a2 ? Object.assign(a2, { direction: "backward" }) : { direction: "backward" };
  return rt(e2)(i2, n, t2);
}, fm = Xi(K), Yi = (e2) => async (i2, n, a2) => rt(e2)(i2, n, a2), pm = Yi(K), ze = {};
le(ze, { xid: () => Aa, uuid7: () => $m, uuid6: () => hm, uuid4: () => gm, uuid: () => Ee, uppercase: () => co, unicodeEmail: () => Fa, undefined: () => so, ulid: () => Ta, time: () => to, string: () => no, sha512_hex: () => Cm, sha512_base64url: () => Jm, sha512_base64: () => Lm, sha384_hex: () => Tm, sha384_base64url: () => Rm, sha384_base64: () => Am, sha256_hex: () => Pm, sha256_base64url: () => Em, sha256_base64: () => Dm, sha1_hex: () => jm, sha1_base64url: () => Nm, sha1_base64: () => Zm, rfc5322Email: () => ym, number: () => en, null: () => uo, nanoid: () => Ca, md5_hex: () => zm, md5_base64url: () => Om, md5_base64: () => Um, mac: () => Ga, lowercase: () => lo, ksuid: () => Ra, ipv6: () => Va, ipv4: () => Wa, integer: () => ao, idnEmail: () => _m, html5Email: () => bm, hostname: () => xm, hex: () => Sm, guid: () => Ja, extendedDuration: () => vm, emoji: () => qa, email: () => Ma, e164: () => Xa, duration: () => La, domain: () => wm, datetime: () => io, date: () => Qa, cuid2: () => Ea, cuid: () => Da, cidrv6: () => Ba, cidrv4: () => Ka, browserEmail: () => km, boolean: () => oo, bigint: () => ro, base64url: () => Qi, base64: () => Ha });
var Da = /^[cC][^\s-]{8,}$/, Ea = /^[0-9a-z]+$/, Ta = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/, Aa = /^[0-9a-vA-V]{20}$/, Ra = /^[A-Za-z0-9]{27}$/, Ca = /^[a-zA-Z0-9_-]{21}$/, La = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/, vm = /^[-+]?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)?)??$/, Ja = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/, Ee = (e2) => e2 ? new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`) : /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/, gm = Ee(4), hm = Ee(6), $m = Ee(7), Ma = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/, bm = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, ym = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, Fa = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u, _m = Fa, km = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, Im = "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";
function qa() {
  return new RegExp(Im, "u");
}
var Wa = /^(?:(?: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])$/, Va = /^(([0-9a-fA-F]{1,4}:){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}|:))$/, Ga = (e2) => {
  let i2 = se(e2 ?? ":");
  return new RegExp(`^(?:[0-9A-F]{2}${i2}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${i2}){5}[0-9a-f]{2}$`);
}, Ka = /^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/, Ba = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, Ha = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/, Qi = /^[A-Za-z0-9_-]*$/, xm = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/, wm = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/, Xa = /^\+[1-9]\d{6,14}$/, Ya = "(?:(?:\\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])))", Qa = new RegExp(`^${Ya}$`);
function eo(e2) {
  return typeof e2.precision == "number" ? e2.precision === -1 ? "(?:[01]\\d|2[0-3]):[0-5]\\d" : e2.precision === 0 ? "(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d" : `(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e2.precision}}` : "(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?";
}
function to(e2) {
  return new RegExp(`^${eo(e2)}$`);
}
function io(e2) {
  let i2 = eo({ precision: e2.precision }), n = ["Z"];
  e2.local && n.push(""), e2.offset && n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");
  let a2 = `${i2}(?:${n.join("|")})`;
  return new RegExp(`^${Ya}T(?:${a2})$`);
}
var no = (e2) => {
  let i2 = e2 ? `[\\s\\S]{${(e2 == null ? void 0 : e2.minimum) ?? 0},${(e2 == null ? void 0 : e2.maximum) ?? ""}}` : "[\\s\\S]*";
  return new RegExp(`^${i2}$`);
}, ro = /^-?\d+n?$/, ao = /^-?\d+$/, en = /^-?\d+(?:\.\d+)?$/, oo = /^(?:true|false)$/i, uo = /^null$/i, so = /^undefined$/i, lo = /^[^A-Z]*$/, co = /^[^a-z]*$/, Sm = /^[0-9a-fA-F]*$/;
function at(e2, i2) {
  return new RegExp(`^[A-Za-z0-9+/]{${e2}}${i2}$`);
}
function ot(e2) {
  return new RegExp(`^[A-Za-z0-9_-]{${e2}}$`);
}
var zm = /^[0-9a-fA-F]{32}$/, Um = at(22, "=="), Om = ot(22), jm = /^[0-9a-fA-F]{40}$/, Zm = at(27, "="), Nm = ot(27), Pm = /^[0-9a-fA-F]{64}$/, Dm = at(43, "="), Em = ot(43), Tm = /^[0-9a-fA-F]{96}$/, Am = at(64, ""), Rm = ot(64), Cm = /^[0-9a-fA-F]{128}$/, Lm = at(86, "=="), Jm = ot(86), E = f("$ZodCheck", (e2, i2) => {
  var n;
  e2._zod ?? (e2._zod = {}), e2._zod.def = i2, (n = e2._zod).onattach ?? (n.onattach = []);
}), mo = { number: "number", bigint: "bigint", object: "date" }, tn = f("$ZodCheckLessThan", (e2, i2) => {
  E.init(e2, i2);
  let n = mo[typeof i2.value];
  e2._zod.onattach.push((a2) => {
    let t2 = a2._zod.bag, r2 = (i2.inclusive ? t2.maximum : t2.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
    i2.value < r2 && (i2.inclusive ? t2.maximum = i2.value : t2.exclusiveMaximum = i2.value);
  }), e2._zod.check = (a2) => {
    (i2.inclusive ? a2.value <= i2.value : a2.value < i2.value) || a2.issues.push({ origin: n, code: "too_big", maximum: typeof i2.value == "object" ? i2.value.getTime() : i2.value, input: a2.value, inclusive: i2.inclusive, inst: e2, continue: !i2.abort });
  };
}), nn = f("$ZodCheckGreaterThan", (e2, i2) => {
  E.init(e2, i2);
  let n = mo[typeof i2.value];
  e2._zod.onattach.push((a2) => {
    let t2 = a2._zod.bag, r2 = (i2.inclusive ? t2.minimum : t2.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
    i2.value > r2 && (i2.inclusive ? t2.minimum = i2.value : t2.exclusiveMinimum = i2.value);
  }), e2._zod.check = (a2) => {
    (i2.inclusive ? a2.value >= i2.value : a2.value > i2.value) || a2.issues.push({ origin: n, code: "too_small", minimum: typeof i2.value == "object" ? i2.value.getTime() : i2.value, input: a2.value, inclusive: i2.inclusive, inst: e2, continue: !i2.abort });
  };
}), fo = f("$ZodCheckMultipleOf", (e2, i2) => {
  E.init(e2, i2), e2._zod.onattach.push((n) => {
    var a2;
    (a2 = n._zod.bag).multipleOf ?? (a2.multipleOf = i2.value);
  }), e2._zod.check = (n) => {
    if (typeof n.value != typeof i2.value) throw Error("Cannot mix number and bigint in multiple_of check.");
    (typeof n.value == "bigint" ? n.value % i2.value === BigInt(0) : $a(n.value, i2.value) === 0) || n.issues.push({ origin: typeof n.value, code: "not_multiple_of", divisor: i2.value, input: n.value, inst: e2, continue: !i2.abort });
  };
}), po = f("$ZodCheckNumberFormat", (e2, i2) => {
  var o2;
  E.init(e2, i2), i2.format = i2.format || "float64";
  let n = (o2 = i2.format) == null ? void 0 : o2.includes("int"), a2 = n ? "int" : "number", [t2, r2] = xa[i2.format];
  e2._zod.onattach.push((u2) => {
    let d = u2._zod.bag;
    d.format = i2.format, d.minimum = t2, d.maximum = r2, n && (d.pattern = ao);
  }), e2._zod.check = (u2) => {
    let d = u2.value;
    if (n) {
      if (!Number.isInteger(d)) {
        u2.issues.push({ expected: a2, format: i2.format, code: "invalid_type", continue: false, input: d, inst: e2 });
        return;
      }
      if (!Number.isSafeInteger(d)) {
        d > 0 ? u2.issues.push({ input: d, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst: e2, origin: a2, inclusive: true, continue: !i2.abort }) : u2.issues.push({ input: d, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst: e2, origin: a2, inclusive: true, continue: !i2.abort });
        return;
      }
    }
    d < t2 && u2.issues.push({ origin: "number", input: d, code: "too_small", minimum: t2, inclusive: true, inst: e2, continue: !i2.abort }), d > r2 && u2.issues.push({ origin: "number", input: d, code: "too_big", maximum: r2, inclusive: true, inst: e2, continue: !i2.abort });
  };
}), vo = f("$ZodCheckBigIntFormat", (e2, i2) => {
  E.init(e2, i2);
  let [n, a2] = wa[i2.format];
  e2._zod.onattach.push((t2) => {
    let r2 = t2._zod.bag;
    r2.format = i2.format, r2.minimum = n, r2.maximum = a2;
  }), e2._zod.check = (t2) => {
    let r2 = t2.value;
    r2 < n && t2.issues.push({ origin: "bigint", input: r2, code: "too_small", minimum: n, inclusive: true, inst: e2, continue: !i2.abort }), r2 > a2 && t2.issues.push({ origin: "bigint", input: r2, code: "too_big", maximum: a2, inclusive: true, inst: e2, continue: !i2.abort });
  };
}), go = f("$ZodCheckMaxSize", (e2, i2) => {
  var n;
  E.init(e2, i2), (n = e2._zod.def).when ?? (n.when = (a2) => {
    let t2 = a2.value;
    return !Se(t2) && t2.size !== void 0;
  }), e2._zod.onattach.push((a2) => {
    let t2 = a2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
    i2.maximum < t2 && (a2._zod.bag.maximum = i2.maximum);
  }), e2._zod.check = (a2) => {
    let t2 = a2.value;
    t2.size <= i2.maximum || a2.issues.push({ origin: Rt(t2), code: "too_big", maximum: i2.maximum, inclusive: true, input: t2, inst: e2, continue: !i2.abort });
  };
}), ho = f("$ZodCheckMinSize", (e2, i2) => {
  var n;
  E.init(e2, i2), (n = e2._zod.def).when ?? (n.when = (a2) => {
    let t2 = a2.value;
    return !Se(t2) && t2.size !== void 0;
  }), e2._zod.onattach.push((a2) => {
    let t2 = a2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
    i2.minimum > t2 && (a2._zod.bag.minimum = i2.minimum);
  }), e2._zod.check = (a2) => {
    let t2 = a2.value;
    t2.size >= i2.minimum || a2.issues.push({ origin: Rt(t2), code: "too_small", minimum: i2.minimum, inclusive: true, input: t2, inst: e2, continue: !i2.abort });
  };
}), $o = f("$ZodCheckSizeEquals", (e2, i2) => {
  var n;
  E.init(e2, i2), (n = e2._zod.def).when ?? (n.when = (a2) => {
    let t2 = a2.value;
    return !Se(t2) && t2.size !== void 0;
  }), e2._zod.onattach.push((a2) => {
    let t2 = a2._zod.bag;
    t2.minimum = i2.size, t2.maximum = i2.size, t2.size = i2.size;
  }), e2._zod.check = (a2) => {
    let t2 = a2.value, r2 = t2.size;
    if (r2 === i2.size) return;
    let o2 = r2 > i2.size;
    a2.issues.push({ origin: Rt(t2), ...o2 ? { code: "too_big", maximum: i2.size } : { code: "too_small", minimum: i2.size }, inclusive: true, exact: true, input: a2.value, inst: e2, continue: !i2.abort });
  };
}), bo = f("$ZodCheckMaxLength", (e2, i2) => {
  var n;
  E.init(e2, i2), (n = e2._zod.def).when ?? (n.when = (a2) => {
    let t2 = a2.value;
    return !Se(t2) && t2.length !== void 0;
  }), e2._zod.onattach.push((a2) => {
    let t2 = a2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
    i2.maximum < t2 && (a2._zod.bag.maximum = i2.maximum);
  }), e2._zod.check = (a2) => {
    let t2 = a2.value;
    if (t2.length <= i2.maximum) return;
    let r2 = Ct(t2);
    a2.issues.push({ origin: r2, code: "too_big", maximum: i2.maximum, inclusive: true, input: t2, inst: e2, continue: !i2.abort });
  };
}), yo = f("$ZodCheckMinLength", (e2, i2) => {
  var n;
  E.init(e2, i2), (n = e2._zod.def).when ?? (n.when = (a2) => {
    let t2 = a2.value;
    return !Se(t2) && t2.length !== void 0;
  }), e2._zod.onattach.push((a2) => {
    let t2 = a2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
    i2.minimum > t2 && (a2._zod.bag.minimum = i2.minimum);
  }), e2._zod.check = (a2) => {
    let t2 = a2.value;
    if (t2.length >= i2.minimum) return;
    let r2 = Ct(t2);
    a2.issues.push({ origin: r2, code: "too_small", minimum: i2.minimum, inclusive: true, input: t2, inst: e2, continue: !i2.abort });
  };
}), _o = f("$ZodCheckLengthEquals", (e2, i2) => {
  var n;
  E.init(e2, i2), (n = e2._zod.def).when ?? (n.when = (a2) => {
    let t2 = a2.value;
    return !Se(t2) && t2.length !== void 0;
  }), e2._zod.onattach.push((a2) => {
    let t2 = a2._zod.bag;
    t2.minimum = i2.length, t2.maximum = i2.length, t2.length = i2.length;
  }), e2._zod.check = (a2) => {
    let t2 = a2.value, r2 = t2.length;
    if (r2 === i2.length) return;
    let o2 = Ct(t2), u2 = r2 > i2.length;
    a2.issues.push({ origin: o2, ...u2 ? { code: "too_big", maximum: i2.length } : { code: "too_small", minimum: i2.length }, inclusive: true, exact: true, input: a2.value, inst: e2, continue: !i2.abort });
  };
}), ut = f("$ZodCheckStringFormat", (e2, i2) => {
  var n, a2;
  E.init(e2, i2), e2._zod.onattach.push((t2) => {
    let r2 = t2._zod.bag;
    r2.format = i2.format, i2.pattern && (r2.patterns ?? (r2.patterns = /* @__PURE__ */ new Set()), r2.patterns.add(i2.pattern));
  }), i2.pattern ? (n = e2._zod).check ?? (n.check = (t2) => {
    i2.pattern.lastIndex = 0, !i2.pattern.test(t2.value) && t2.issues.push({ origin: "string", code: "invalid_format", format: i2.format, input: t2.value, ...i2.pattern ? { pattern: i2.pattern.toString() } : {}, inst: e2, continue: !i2.abort });
  }) : (a2 = e2._zod).check ?? (a2.check = () => {
  });
}), ko = f("$ZodCheckRegex", (e2, i2) => {
  ut.init(e2, i2), e2._zod.check = (n) => {
    i2.pattern.lastIndex = 0, !i2.pattern.test(n.value) && n.issues.push({ origin: "string", code: "invalid_format", format: "regex", input: n.value, pattern: i2.pattern.toString(), inst: e2, continue: !i2.abort });
  };
}), Io = f("$ZodCheckLowerCase", (e2, i2) => {
  i2.pattern ?? (i2.pattern = lo), ut.init(e2, i2);
}), xo = f("$ZodCheckUpperCase", (e2, i2) => {
  i2.pattern ?? (i2.pattern = co), ut.init(e2, i2);
}), wo = f("$ZodCheckIncludes", (e2, i2) => {
  E.init(e2, i2);
  let n = se(i2.includes), a2 = new RegExp(typeof i2.position == "number" ? `^.{${i2.position}}${n}` : n);
  i2.pattern = a2, e2._zod.onattach.push((t2) => {
    let r2 = t2._zod.bag;
    r2.patterns ?? (r2.patterns = /* @__PURE__ */ new Set()), r2.patterns.add(a2);
  }), e2._zod.check = (t2) => {
    t2.value.includes(i2.includes, i2.position) || t2.issues.push({ origin: "string", code: "invalid_format", format: "includes", includes: i2.includes, input: t2.value, inst: e2, continue: !i2.abort });
  };
}), So = f("$ZodCheckStartsWith", (e2, i2) => {
  E.init(e2, i2);
  let n = new RegExp(`^${se(i2.prefix)}.*`);
  i2.pattern ?? (i2.pattern = n), e2._zod.onattach.push((a2) => {
    let t2 = a2._zod.bag;
    t2.patterns ?? (t2.patterns = /* @__PURE__ */ new Set()), t2.patterns.add(n);
  }), e2._zod.check = (a2) => {
    a2.value.startsWith(i2.prefix) || a2.issues.push({ origin: "string", code: "invalid_format", format: "starts_with", prefix: i2.prefix, input: a2.value, inst: e2, continue: !i2.abort });
  };
}), zo = f("$ZodCheckEndsWith", (e2, i2) => {
  E.init(e2, i2);
  let n = new RegExp(`.*${se(i2.suffix)}$`);
  i2.pattern ?? (i2.pattern = n), e2._zod.onattach.push((a2) => {
    let t2 = a2._zod.bag;
    t2.patterns ?? (t2.patterns = /* @__PURE__ */ new Set()), t2.patterns.add(n);
  }), e2._zod.check = (a2) => {
    a2.value.endsWith(i2.suffix) || a2.issues.push({ origin: "string", code: "invalid_format", format: "ends_with", suffix: i2.suffix, input: a2.value, inst: e2, continue: !i2.abort });
  };
});
function qr(e2, i2, n) {
  e2.issues.length && i2.issues.push(...re(n, e2.issues));
}
var Uo = f("$ZodCheckProperty", (e2, i2) => {
  E.init(e2, i2), e2._zod.check = (n) => {
    let a2 = i2.schema._zod.run({ value: n.value[i2.property], issues: [] }, {});
    if (a2 instanceof Promise) return a2.then((t2) => qr(t2, n, i2.property));
    qr(a2, n, i2.property);
  };
}), Oo = f("$ZodCheckMimeType", (e2, i2) => {
  E.init(e2, i2);
  let n = new Set(i2.mime);
  e2._zod.onattach.push((a2) => {
    a2._zod.bag.mime = i2.mime;
  }), e2._zod.check = (a2) => {
    n.has(a2.value.type) || a2.issues.push({ code: "invalid_value", values: i2.mime, input: a2.value.type, inst: e2, continue: !i2.abort });
  };
}), jo = f("$ZodCheckOverwrite", (e2, i2) => {
  E.init(e2, i2), e2._zod.check = (n) => {
    n.value = i2.tx(n.value);
  };
});
class Zo {
  constructor(i2 = []) {
    this.content = [], this.indent = 0, this && (this.args = i2);
  }
  indented(i2) {
    this.indent += 1, i2(this), this.indent -= 1;
  }
  write(i2) {
    if (typeof i2 == "function") {
      i2(this, { execution: "sync" }), i2(this, { execution: "async" });
      return;
    }
    let n = i2.split(`
`).filter((r2) => r2), a2 = Math.min(...n.map((r2) => r2.length - r2.trimStart().length)), t2 = n.map((r2) => r2.slice(a2)).map((r2) => " ".repeat(this.indent * 2) + r2);
    for (let r2 of t2) this.content.push(r2);
  }
  compile() {
    let i2 = Function, n = this == null ? void 0 : this.args, a2 = [...((this == null ? void 0 : this.content) ?? [""]).map((t2) => `  ${t2}`)];
    return new i2(...n, a2.join(`
`));
  }
}
var No = { major: 4, minor: 3, patch: 5 }, k = f("$ZodType", (e2, i2) => {
  var t2;
  var n;
  e2 ?? (e2 = {}), e2._zod.def = i2, e2._zod.bag = e2._zod.bag || {}, e2._zod.version = No;
  let a2 = [...e2._zod.def.checks ?? []];
  e2._zod.traits.has("$ZodCheck") && a2.unshift(e2);
  for (let r2 of a2) for (let o2 of r2._zod.onattach) o2(e2);
  if (a2.length === 0) (n = e2._zod).deferred ?? (n.deferred = []), (t2 = e2._zod.deferred) == null || t2.push(() => {
    e2._zod.run = e2._zod.parse;
  });
  else {
    let r2 = (u2, d, s2) => {
      let m2 = _e(u2), c;
      for (let p2 of d) {
        if (p2._zod.def.when) {
          if (!p2._zod.def.when(u2)) continue;
        } else if (m2) continue;
        let $2 = u2.issues.length, y = p2._zod.check(u2);
        if (y instanceof Promise && (s2 == null ? void 0 : s2.async) === false) throw new ke();
        if (c || y instanceof Promise) c = (c ?? Promise.resolve()).then(async () => {
          await y, u2.issues.length !== $2 && (m2 || (m2 = _e(u2, $2)));
        });
        else {
          if (u2.issues.length === $2) continue;
          m2 || (m2 = _e(u2, $2));
        }
      }
      return c ? c.then(() => u2) : u2;
    }, o2 = (u2, d, s2) => {
      if (_e(u2)) return u2.aborted = true, u2;
      let m2 = r2(d, a2, s2);
      if (m2 instanceof Promise) {
        if (s2.async === false) throw new ke();
        return m2.then((c) => e2._zod.parse(c, s2));
      }
      return e2._zod.parse(m2, s2);
    };
    e2._zod.run = (u2, d) => {
      if (d.skipChecks) return e2._zod.parse(u2, d);
      if (d.direction === "backward") {
        let m2 = e2._zod.parse({ value: u2.value, issues: [] }, { ...d, skipChecks: true });
        return m2 instanceof Promise ? m2.then((c) => o2(c, u2, d)) : o2(m2, u2, d);
      }
      let s2 = e2._zod.parse(u2, d);
      if (s2 instanceof Promise) {
        if (d.async === false) throw new ke();
        return s2.then((m2) => r2(m2, a2, d));
      }
      return r2(s2, a2, d);
    };
  }
  w(e2, "~standard", () => ({ validate: (r2) => {
    var o2;
    try {
      let u2 = Na(e2, r2);
      return u2.success ? { value: u2.data } : { issues: (o2 = u2.error) == null ? void 0 : o2.issues };
    } catch {
      return Pa(e2, r2).then((d) => {
        var s2;
        return d.success ? { value: d.data } : { issues: (s2 = d.error) == null ? void 0 : s2.issues };
      });
    }
  }, vendor: "zod", version: 1 }));
}), st = f("$ZodString", (e2, i2) => {
  var n;
  k.init(e2, i2), e2._zod.pattern = [...((n = e2 == null ? void 0 : e2._zod.bag) == null ? void 0 : n.patterns) ?? []].pop() ?? no(e2._zod.bag), e2._zod.parse = (a2, t2) => {
    if (i2.coerce) try {
      a2.value = String(a2.value);
    } catch {
    }
    return typeof a2.value == "string" || a2.issues.push({ expected: "string", code: "invalid_type", input: a2.value, inst: e2 }), a2;
  };
}), Z = f("$ZodStringFormat", (e2, i2) => {
  ut.init(e2, i2), st.init(e2, i2);
}), Po = f("$ZodGUID", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Ja), Z.init(e2, i2);
}), Do = f("$ZodUUID", (e2, i2) => {
  if (i2.version) {
    let n = { v1: 1, v2: 2, v3: 3, v4: 4, v5: 5, v6: 6, v7: 7, v8: 8 }[i2.version];
    if (n === void 0) throw Error(`Invalid UUID version: "${i2.version}"`);
    i2.pattern ?? (i2.pattern = Ee(n));
  } else i2.pattern ?? (i2.pattern = Ee());
  Z.init(e2, i2);
}), Eo = f("$ZodEmail", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Ma), Z.init(e2, i2);
}), To = f("$ZodURL", (e2, i2) => {
  Z.init(e2, i2), e2._zod.check = (n) => {
    try {
      let a2 = n.value.trim(), t2 = new URL(a2);
      i2.hostname && (i2.hostname.lastIndex = 0, !i2.hostname.test(t2.hostname) && n.issues.push({ code: "invalid_format", format: "url", note: "Invalid hostname", pattern: i2.hostname.source, input: n.value, inst: e2, continue: !i2.abort })), i2.protocol && (i2.protocol.lastIndex = 0, !i2.protocol.test(t2.protocol.endsWith(":") ? t2.protocol.slice(0, -1) : t2.protocol) && n.issues.push({ code: "invalid_format", format: "url", note: "Invalid protocol", pattern: i2.protocol.source, input: n.value, inst: e2, continue: !i2.abort })), i2.normalize ? n.value = t2.href : n.value = a2;
      return;
    } catch {
      n.issues.push({ code: "invalid_format", format: "url", input: n.value, inst: e2, continue: !i2.abort });
    }
  };
}), Ao = f("$ZodEmoji", (e2, i2) => {
  i2.pattern ?? (i2.pattern = qa()), Z.init(e2, i2);
}), Ro = f("$ZodNanoID", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Ca), Z.init(e2, i2);
}), Co = f("$ZodCUID", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Da), Z.init(e2, i2);
}), Lo = f("$ZodCUID2", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Ea), Z.init(e2, i2);
}), Jo = f("$ZodULID", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Ta), Z.init(e2, i2);
}), Mo = f("$ZodXID", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Aa), Z.init(e2, i2);
}), Fo = f("$ZodKSUID", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Ra), Z.init(e2, i2);
}), qo = f("$ZodISODateTime", (e2, i2) => {
  i2.pattern ?? (i2.pattern = io(i2)), Z.init(e2, i2);
}), Wo = f("$ZodISODate", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Qa), Z.init(e2, i2);
}), Vo = f("$ZodISOTime", (e2, i2) => {
  i2.pattern ?? (i2.pattern = to(i2)), Z.init(e2, i2);
}), Go = f("$ZodISODuration", (e2, i2) => {
  i2.pattern ?? (i2.pattern = La), Z.init(e2, i2);
}), Ko = f("$ZodIPv4", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Wa), Z.init(e2, i2), e2._zod.bag.format = "ipv4";
}), Bo = f("$ZodIPv6", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Va), Z.init(e2, i2), e2._zod.bag.format = "ipv6", e2._zod.check = (n) => {
    try {
      new URL(`http://[${n.value}]`);
    } catch {
      n.issues.push({ code: "invalid_format", format: "ipv6", input: n.value, inst: e2, continue: !i2.abort });
    }
  };
}), Ho = f("$ZodMAC", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Ga(i2.delimiter)), Z.init(e2, i2), e2._zod.bag.format = "mac";
}), Xo = f("$ZodCIDRv4", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Ka), Z.init(e2, i2);
}), Yo = f("$ZodCIDRv6", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Ba), Z.init(e2, i2), e2._zod.check = (n) => {
    let a2 = n.value.split("/");
    try {
      if (a2.length !== 2) throw Error();
      let [t2, r2] = a2;
      if (!r2) throw Error();
      let o2 = Number(r2);
      if (`${o2}` !== r2 || o2 < 0 || o2 > 128) throw Error();
      new URL(`http://[${t2}]`);
    } catch {
      n.issues.push({ code: "invalid_format", format: "cidrv6", input: n.value, inst: e2, continue: !i2.abort });
    }
  };
});
function rn(e2) {
  if (e2 === "") return true;
  if (e2.length % 4 !== 0) return false;
  try {
    return atob(e2), true;
  } catch {
    return false;
  }
}
var Qo = f("$ZodBase64", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Ha), Z.init(e2, i2), e2._zod.bag.contentEncoding = "base64", e2._zod.check = (n) => {
    rn(n.value) || n.issues.push({ code: "invalid_format", format: "base64", input: n.value, inst: e2, continue: !i2.abort });
  };
});
function eu(e2) {
  if (!Qi.test(e2)) return false;
  let i2 = e2.replace(/[-_]/g, (a2) => a2 === "-" ? "+" : "/"), n = i2.padEnd(Math.ceil(i2.length / 4) * 4, "=");
  return rn(n);
}
var tu = f("$ZodBase64URL", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Qi), Z.init(e2, i2), e2._zod.bag.contentEncoding = "base64url", e2._zod.check = (n) => {
    eu(n.value) || n.issues.push({ code: "invalid_format", format: "base64url", input: n.value, inst: e2, continue: !i2.abort });
  };
}), iu = f("$ZodE164", (e2, i2) => {
  i2.pattern ?? (i2.pattern = Xa), Z.init(e2, i2);
});
function nu(e2, i2 = null) {
  try {
    let n = e2.split(".");
    if (n.length !== 3) return false;
    let [a2] = n;
    if (!a2) return false;
    let t2 = JSON.parse(atob(a2));
    return !("typ" in t2 && (t2 == null ? void 0 : t2.typ) !== "JWT" || !t2.alg || i2 && (!("alg" in t2) || t2.alg !== i2));
  } catch {
    return false;
  }
}
var ru = f("$ZodJWT", (e2, i2) => {
  Z.init(e2, i2), e2._zod.check = (n) => {
    nu(n.value, i2.alg) || n.issues.push({ code: "invalid_format", format: "jwt", input: n.value, inst: e2, continue: !i2.abort });
  };
}), au = f("$ZodCustomStringFormat", (e2, i2) => {
  Z.init(e2, i2), e2._zod.check = (n) => {
    i2.fn(n.value) || n.issues.push({ code: "invalid_format", format: i2.format, input: n.value, inst: e2, continue: !i2.abort });
  };
}), an = f("$ZodNumber", (e2, i2) => {
  k.init(e2, i2), e2._zod.pattern = e2._zod.bag.pattern ?? en, e2._zod.parse = (n, a2) => {
    if (i2.coerce) try {
      n.value = Number(n.value);
    } catch {
    }
    let t2 = n.value;
    if (typeof t2 == "number" && !Number.isNaN(t2) && Number.isFinite(t2)) return n;
    let r2 = typeof t2 == "number" ? Number.isNaN(t2) ? "NaN" : Number.isFinite(t2) ? void 0 : "Infinity" : void 0;
    return n.issues.push({ expected: "number", code: "invalid_type", input: t2, inst: e2, ...r2 ? { received: r2 } : {} }), n;
  };
}), ou = f("$ZodNumberFormat", (e2, i2) => {
  po.init(e2, i2), an.init(e2, i2);
}), on = f("$ZodBoolean", (e2, i2) => {
  k.init(e2, i2), e2._zod.pattern = oo, e2._zod.parse = (n, a2) => {
    if (i2.coerce) try {
      n.value = !!n.value;
    } catch {
    }
    let t2 = n.value;
    return typeof t2 == "boolean" || n.issues.push({ expected: "boolean", code: "invalid_type", input: t2, inst: e2 }), n;
  };
}), un = f("$ZodBigInt", (e2, i2) => {
  k.init(e2, i2), e2._zod.pattern = ro, e2._zod.parse = (n, a2) => {
    if (i2.coerce) try {
      n.value = BigInt(n.value);
    } catch {
    }
    return typeof n.value == "bigint" || n.issues.push({ expected: "bigint", code: "invalid_type", input: n.value, inst: e2 }), n;
  };
}), uu = f("$ZodBigIntFormat", (e2, i2) => {
  vo.init(e2, i2), un.init(e2, i2);
}), su = f("$ZodSymbol", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => {
    let t2 = n.value;
    return typeof t2 == "symbol" || n.issues.push({ expected: "symbol", code: "invalid_type", input: t2, inst: e2 }), n;
  };
}), lu = f("$ZodUndefined", (e2, i2) => {
  k.init(e2, i2), e2._zod.pattern = so, e2._zod.values = /* @__PURE__ */ new Set([void 0]), e2._zod.optin = "optional", e2._zod.optout = "optional", e2._zod.parse = (n, a2) => {
    let t2 = n.value;
    return typeof t2 > "u" || n.issues.push({ expected: "undefined", code: "invalid_type", input: t2, inst: e2 }), n;
  };
}), du = f("$ZodNull", (e2, i2) => {
  k.init(e2, i2), e2._zod.pattern = uo, e2._zod.values = /* @__PURE__ */ new Set([null]), e2._zod.parse = (n, a2) => {
    let t2 = n.value;
    return t2 === null || n.issues.push({ expected: "null", code: "invalid_type", input: t2, inst: e2 }), n;
  };
}), cu = f("$ZodAny", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n) => n;
}), mu = f("$ZodUnknown", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n) => n;
}), fu = f("$ZodNever", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => (n.issues.push({ expected: "never", code: "invalid_type", input: n.value, inst: e2 }), n);
}), pu = f("$ZodVoid", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => {
    let t2 = n.value;
    return typeof t2 > "u" || n.issues.push({ expected: "void", code: "invalid_type", input: t2, inst: e2 }), n;
  };
}), vu = f("$ZodDate", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => {
    if (i2.coerce) try {
      n.value = new Date(n.value);
    } catch {
    }
    let t2 = n.value, r2 = t2 instanceof Date;
    return r2 && !Number.isNaN(t2.getTime()) || n.issues.push({ expected: "date", code: "invalid_type", input: t2, ...r2 ? { received: "Invalid Date" } : {}, inst: e2 }), n;
  };
});
function Wr(e2, i2, n) {
  e2.issues.length && i2.issues.push(...re(n, e2.issues)), i2.value[n] = e2.value;
}
var gu = f("$ZodArray", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => {
    let t2 = n.value;
    if (!Array.isArray(t2)) return n.issues.push({ expected: "array", code: "invalid_type", input: t2, inst: e2 }), n;
    n.value = Array(t2.length);
    let r2 = [];
    for (let o2 = 0; o2 < t2.length; o2++) {
      let u2 = t2[o2], d = i2.element._zod.run({ value: u2, issues: [] }, a2);
      d instanceof Promise ? r2.push(d.then((s2) => Wr(s2, n, o2))) : Wr(d, n, o2);
    }
    return r2.length ? Promise.all(r2).then(() => n) : n;
  };
});
function Zt(e2, i2, n, a2, t2) {
  if (e2.issues.length) {
    if (t2 && !(n in a2)) return;
    i2.issues.push(...re(n, e2.issues));
  }
  e2.value === void 0 ? n in a2 && (i2.value[n] = void 0) : i2.value[n] = e2.value;
}
function hu(e2) {
  var a2, t2, r2, o2;
  let i2 = Object.keys(e2.shape);
  for (let u2 of i2) if (!((o2 = (r2 = (t2 = (a2 = e2.shape) == null ? void 0 : a2[u2]) == null ? void 0 : t2._zod) == null ? void 0 : r2.traits) != null && o2.has("$ZodType"))) throw Error(`Invalid element at key "${u2}": expected a Zod schema`);
  let n = Ia(e2.shape);
  return { ...e2, keys: i2, keySet: new Set(i2), numKeys: i2.length, optionalKeys: new Set(n) };
}
function $u(e2, i2, n, a2, t2, r2) {
  let o2 = [], u2 = t2.keySet, d = t2.catchall._zod, s2 = d.def.type, m2 = d.optout === "optional";
  for (let c in i2) {
    if (u2.has(c)) continue;
    if (s2 === "never") {
      o2.push(c);
      continue;
    }
    let p2 = d.run({ value: i2[c], issues: [] }, a2);
    p2 instanceof Promise ? e2.push(p2.then(($2) => Zt($2, n, c, i2, m2))) : Zt(p2, n, c, i2, m2);
  }
  return o2.length && n.issues.push({ code: "unrecognized_keys", keys: o2, input: i2, inst: r2 }), e2.length ? Promise.all(e2).then(() => n) : n;
}
var bu = f("$ZodObject", (e2, i2) => {
  var o2;
  if (k.init(e2, i2), !((o2 = Object.getOwnPropertyDescriptor(i2, "shape")) != null && o2.get)) {
    let u2 = i2.shape;
    Object.defineProperty(i2, "shape", { get: () => {
      let d = { ...u2 };
      return Object.defineProperty(i2, "shape", { value: d }), d;
    } });
  }
  let n = et(() => hu(i2));
  w(e2._zod, "propValues", () => {
    let u2 = i2.shape, d = {};
    for (let s2 in u2) {
      let m2 = u2[s2]._zod;
      if (m2.values) {
        d[s2] ?? (d[s2] = /* @__PURE__ */ new Set());
        for (let c of m2.values) d[s2].add(c);
      }
    }
    return d;
  });
  let a2 = De, t2 = i2.catchall, r2;
  e2._zod.parse = (u2, d) => {
    r2 ?? (r2 = n.value);
    let s2 = u2.value;
    if (!a2(s2)) return u2.issues.push({ expected: "object", code: "invalid_type", input: s2, inst: e2 }), u2;
    u2.value = {};
    let m2 = [], c = r2.shape;
    for (let p2 of r2.keys) {
      let $2 = c[p2], y = $2._zod.optout === "optional", x2 = $2._zod.run({ value: s2[p2], issues: [] }, d);
      x2 instanceof Promise ? m2.push(x2.then((z2) => Zt(z2, u2, p2, s2, y))) : Zt(x2, u2, p2, s2, y);
    }
    return t2 ? $u(m2, s2, u2, d, n.value, e2) : m2.length ? Promise.all(m2).then(() => u2) : u2;
  };
}), yu = f("$ZodObjectJIT", (e2, i2) => {
  bu.init(e2, i2);
  let n = e2._zod.parse, a2 = et(() => hu(i2)), t2 = (c) => {
    var W2, ae;
    let p2 = new Zo(["shape", "payload", "ctx"]), $2 = a2.value, y = (A) => {
      let D2 = Di(A);
      return `shape[${D2}]._zod.run({ value: input[${D2}], issues: [] }, ctx)`;
    };
    p2.write("const input = payload.value;");
    let x2 = /* @__PURE__ */ Object.create(null), z2 = 0;
    for (let A of $2.keys) x2[A] = `key_${z2++}`;
    p2.write("const newResult = {};");
    for (let A of $2.keys) {
      let D2 = x2[A], R = Di(A), U2 = ((ae = (W2 = c[A]) == null ? void 0 : W2._zod) == null ? void 0 : ae.optout) === "optional";
      p2.write(`const ${D2} = ${y(A)};`), U2 ? p2.write(`
        if (${D2}.issues.length) {
          if (${R} in input) {
            payload.issues = payload.issues.concat(${D2}.issues.map(iss => ({
              ...iss,
              path: iss.path ? [${R}, ...iss.path] : [${R}]
            })));
          }
        }
        
        if (${D2}.value === undefined) {
          if (${R} in input) {
            newResult[${R}] = undefined;
          }
        } else {
          newResult[${R}] = ${D2}.value;
        }
        
      `) : p2.write(`
        if (${D2}.issues.length) {
          payload.issues = payload.issues.concat(${D2}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${R}, ...iss.path] : [${R}]
          })));
        }
        
        if (${D2}.value === undefined) {
          if (${R} in input) {
            newResult[${R}] = undefined;
          }
        } else {
          newResult[${R}] = ${D2}.value;
        }
        
      `);
    }
    p2.write("payload.value = newResult;"), p2.write("return payload;");
    let P2 = p2.compile();
    return (A, D2) => P2(c, A, D2);
  }, r2, o2 = De, u2 = !zt.jitless, d = u2 && ya.value, s2 = i2.catchall, m2;
  e2._zod.parse = (c, p2) => {
    m2 ?? (m2 = a2.value);
    let $2 = c.value;
    return o2($2) ? u2 && d && (p2 == null ? void 0 : p2.async) === false && p2.jitless !== true ? (r2 || (r2 = t2(i2.shape)), c = r2(c, p2), s2 ? $u([], $2, c, p2, m2, e2) : c) : n(c, p2) : (c.issues.push({ expected: "object", code: "invalid_type", input: $2, inst: e2 }), c);
  };
});
function Vr(e2, i2, n, a2) {
  for (let r2 of e2) if (r2.issues.length === 0) return i2.value = r2.value, i2;
  let t2 = e2.filter((r2) => !_e(r2));
  return t2.length === 1 ? (i2.value = t2[0].value, t2[0]) : (i2.issues.push({ code: "invalid_union", input: i2.value, inst: n, errors: e2.map((r2) => r2.issues.map((o2) => te(o2, a2, F()))) }), i2);
}
var Lt = f("$ZodUnion", (e2, i2) => {
  k.init(e2, i2), w(e2._zod, "optin", () => i2.options.some((t2) => t2._zod.optin === "optional") ? "optional" : void 0), w(e2._zod, "optout", () => i2.options.some((t2) => t2._zod.optout === "optional") ? "optional" : void 0), w(e2._zod, "values", () => {
    if (i2.options.every((t2) => t2._zod.values)) return new Set(i2.options.flatMap((t2) => Array.from(t2._zod.values)));
  }), w(e2._zod, "pattern", () => {
    if (i2.options.every((t2) => t2._zod.pattern)) {
      let t2 = i2.options.map((r2) => r2._zod.pattern);
      return new RegExp(`^(${t2.map((r2) => At(r2.source)).join("|")})$`);
    }
  });
  let n = i2.options.length === 1, a2 = i2.options[0]._zod.run;
  e2._zod.parse = (t2, r2) => {
    if (n) return a2(t2, r2);
    let o2 = false, u2 = [];
    for (let d of i2.options) {
      let s2 = d._zod.run({ value: t2.value, issues: [] }, r2);
      if (s2 instanceof Promise) u2.push(s2), o2 = true;
      else {
        if (s2.issues.length === 0) return s2;
        u2.push(s2);
      }
    }
    return o2 ? Promise.all(u2).then((d) => Vr(d, t2, e2, r2)) : Vr(u2, t2, e2, r2);
  };
});
function Gr(e2, i2, n, a2) {
  let t2 = e2.filter((r2) => r2.issues.length === 0);
  return t2.length === 1 ? (i2.value = t2[0].value, i2) : (t2.length === 0 ? i2.issues.push({ code: "invalid_union", input: i2.value, inst: n, errors: e2.map((r2) => r2.issues.map((o2) => te(o2, a2, F()))) }) : i2.issues.push({ code: "invalid_union", input: i2.value, inst: n, errors: [], inclusive: false }), i2);
}
var _u = f("$ZodXor", (e2, i2) => {
  Lt.init(e2, i2), i2.inclusive = false;
  let n = i2.options.length === 1, a2 = i2.options[0]._zod.run;
  e2._zod.parse = (t2, r2) => {
    if (n) return a2(t2, r2);
    let o2 = false, u2 = [];
    for (let d of i2.options) {
      let s2 = d._zod.run({ value: t2.value, issues: [] }, r2);
      s2 instanceof Promise ? (u2.push(s2), o2 = true) : u2.push(s2);
    }
    return o2 ? Promise.all(u2).then((d) => Gr(d, t2, e2, r2)) : Gr(u2, t2, e2, r2);
  };
}), ku = f("$ZodDiscriminatedUnion", (e2, i2) => {
  i2.inclusive = false, Lt.init(e2, i2);
  let n = e2._zod.parse;
  w(e2._zod, "propValues", () => {
    let t2 = {};
    for (let r2 of i2.options) {
      let o2 = r2._zod.propValues;
      if (!o2 || Object.keys(o2).length === 0) throw Error(`Invalid discriminated union option at index "${i2.options.indexOf(r2)}"`);
      for (let [u2, d] of Object.entries(o2)) {
        t2[u2] || (t2[u2] = /* @__PURE__ */ new Set());
        for (let s2 of d) t2[u2].add(s2);
      }
    }
    return t2;
  });
  let a2 = et(() => {
    var o2;
    let t2 = i2.options, r2 = /* @__PURE__ */ new Map();
    for (let u2 of t2) {
      let d = (o2 = u2._zod.propValues) == null ? void 0 : o2[i2.discriminator];
      if (!d || d.size === 0) throw Error(`Invalid discriminated union option at index "${i2.options.indexOf(u2)}"`);
      for (let s2 of d) {
        if (r2.has(s2)) throw Error(`Duplicate discriminator value "${String(s2)}"`);
        r2.set(s2, u2);
      }
    }
    return r2;
  });
  e2._zod.parse = (t2, r2) => {
    let o2 = t2.value;
    if (!De(o2)) return t2.issues.push({ code: "invalid_type", expected: "object", input: o2, inst: e2 }), t2;
    let u2 = a2.value.get(o2 == null ? void 0 : o2[i2.discriminator]);
    return u2 ? u2._zod.run(t2, r2) : i2.unionFallback ? n(t2, r2) : (t2.issues.push({ code: "invalid_union", errors: [], note: "No matching discriminator", discriminator: i2.discriminator, input: o2, path: [i2.discriminator], inst: e2 }), t2);
  };
}), Iu = f("$ZodIntersection", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => {
    let t2 = n.value, r2 = i2.left._zod.run({ value: t2, issues: [] }, a2), o2 = i2.right._zod.run({ value: t2, issues: [] }, a2);
    return r2 instanceof Promise || o2 instanceof Promise ? Promise.all([r2, o2]).then(([u2, d]) => Kr(n, u2, d)) : Kr(n, r2, o2);
  };
});
function Ai(e2, i2) {
  if (e2 === i2) return { valid: true, data: e2 };
  if (e2 instanceof Date && i2 instanceof Date && +e2 == +i2) return { valid: true, data: e2 };
  if (Ie(e2) && Ie(i2)) {
    let n = Object.keys(i2), a2 = Object.keys(e2).filter((r2) => n.indexOf(r2) !== -1), t2 = { ...e2, ...i2 };
    for (let r2 of a2) {
      let o2 = Ai(e2[r2], i2[r2]);
      if (!o2.valid) return { valid: false, mergeErrorPath: [r2, ...o2.mergeErrorPath] };
      t2[r2] = o2.data;
    }
    return { valid: true, data: t2 };
  }
  if (Array.isArray(e2) && Array.isArray(i2)) {
    if (e2.length !== i2.length) return { valid: false, mergeErrorPath: [] };
    let n = [];
    for (let a2 = 0; a2 < e2.length; a2++) {
      let t2 = e2[a2], r2 = i2[a2], o2 = Ai(t2, r2);
      if (!o2.valid) return { valid: false, mergeErrorPath: [a2, ...o2.mergeErrorPath] };
      n.push(o2.data);
    }
    return { valid: true, data: n };
  }
  return { valid: false, mergeErrorPath: [] };
}
function Kr(e2, i2, n) {
  let a2 = /* @__PURE__ */ new Map(), t2;
  for (let u2 of i2.issues) if (u2.code === "unrecognized_keys") {
    t2 ?? (t2 = u2);
    for (let d of u2.keys)
      a2.has(d) || a2.set(d, {}), a2.get(d).l = true;
  } else e2.issues.push(u2);
  for (let u2 of n.issues) if (u2.code === "unrecognized_keys") for (let d of u2.keys)
    a2.has(d) || a2.set(d, {}), a2.get(d).r = true;
  else e2.issues.push(u2);
  let r2 = [...a2].filter(([, u2]) => u2.l && u2.r).map(([u2]) => u2);
  if (r2.length && t2 && e2.issues.push({ ...t2, keys: r2 }), _e(e2)) return e2;
  let o2 = Ai(i2.value, n.value);
  if (!o2.valid) throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o2.mergeErrorPath)}`);
  return e2.value = o2.data, e2;
}
var sn = f("$ZodTuple", (e2, i2) => {
  k.init(e2, i2);
  let n = i2.items;
  e2._zod.parse = (a2, t2) => {
    let r2 = a2.value;
    if (!Array.isArray(r2)) return a2.issues.push({ input: r2, inst: e2, expected: "tuple", code: "invalid_type" }), a2;
    a2.value = [];
    let o2 = [], u2 = [...n].reverse().findIndex((m2) => m2._zod.optin !== "optional"), d = u2 === -1 ? 0 : n.length - u2;
    if (!i2.rest) {
      let m2 = r2.length > n.length, c = r2.length < d - 1;
      if (m2 || c) return a2.issues.push({ ...m2 ? { code: "too_big", maximum: n.length, inclusive: true } : { code: "too_small", minimum: n.length }, input: r2, inst: e2, origin: "array" }), a2;
    }
    let s2 = -1;
    for (let m2 of n) {
      if (s2++, s2 >= r2.length && s2 >= d)
        continue;
      let c = m2._zod.run({ value: r2[s2], issues: [] }, t2);
      c instanceof Promise ? o2.push(c.then((p2) => It(p2, a2, s2))) : It(c, a2, s2);
    }
    if (i2.rest) {
      let m2 = r2.slice(n.length);
      for (let c of m2) {
        s2++;
        let p2 = i2.rest._zod.run({ value: c, issues: [] }, t2);
        p2 instanceof Promise ? o2.push(p2.then(($2) => It($2, a2, s2))) : It(p2, a2, s2);
      }
    }
    return o2.length ? Promise.all(o2).then(() => a2) : a2;
  };
});
function It(e2, i2, n) {
  e2.issues.length && i2.issues.push(...re(n, e2.issues)), i2.value[n] = e2.value;
}
var xu = f("$ZodRecord", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => {
    let t2 = n.value;
    if (!Ie(t2)) return n.issues.push({ expected: "record", code: "invalid_type", input: t2, inst: e2 }), n;
    let r2 = [], o2 = i2.keyType._zod.values;
    if (o2) {
      n.value = {};
      let u2 = /* @__PURE__ */ new Set();
      for (let s2 of o2) if (typeof s2 == "string" || typeof s2 == "number" || typeof s2 == "symbol") {
        u2.add(typeof s2 == "number" ? s2.toString() : s2);
        let m2 = i2.valueType._zod.run({ value: t2[s2], issues: [] }, a2);
        m2 instanceof Promise ? r2.push(m2.then((c) => {
          c.issues.length && n.issues.push(...re(s2, c.issues)), n.value[s2] = c.value;
        })) : (m2.issues.length && n.issues.push(...re(s2, m2.issues)), n.value[s2] = m2.value);
      }
      let d;
      for (let s2 in t2) u2.has(s2) || (d = d ?? [], d.push(s2));
      d && d.length > 0 && n.issues.push({ code: "unrecognized_keys", input: t2, inst: e2, keys: d });
    } else {
      n.value = {};
      for (let u2 of Reflect.ownKeys(t2)) {
        if (u2 === "__proto__") continue;
        let d = i2.keyType._zod.run({ value: u2, issues: [] }, a2);
        if (d instanceof Promise) throw Error("Async schemas not supported in object keys currently");
        if (typeof u2 == "string" && en.test(u2) && d.issues.length && d.issues.some((m2) => m2.code === "invalid_type" && m2.expected === "number")) {
          let m2 = i2.keyType._zod.run({ value: Number(u2), issues: [] }, a2);
          if (m2 instanceof Promise) throw Error("Async schemas not supported in object keys currently");
          m2.issues.length === 0 && (d = m2);
        }
        if (d.issues.length) {
          i2.mode === "loose" ? n.value[u2] = t2[u2] : n.issues.push({ code: "invalid_key", origin: "record", issues: d.issues.map((m2) => te(m2, a2, F())), input: u2, path: [u2], inst: e2 });
          continue;
        }
        let s2 = i2.valueType._zod.run({ value: t2[u2], issues: [] }, a2);
        s2 instanceof Promise ? r2.push(s2.then((m2) => {
          m2.issues.length && n.issues.push(...re(u2, m2.issues)), n.value[d.value] = m2.value;
        })) : (s2.issues.length && n.issues.push(...re(u2, s2.issues)), n.value[d.value] = s2.value);
      }
    }
    return r2.length ? Promise.all(r2).then(() => n) : n;
  };
}), wu = f("$ZodMap", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => {
    let t2 = n.value;
    if (!(t2 instanceof Map)) return n.issues.push({ expected: "map", code: "invalid_type", input: t2, inst: e2 }), n;
    let r2 = [];
    n.value = /* @__PURE__ */ new Map();
    for (let [o2, u2] of t2) {
      let d = i2.keyType._zod.run({ value: o2, issues: [] }, a2), s2 = i2.valueType._zod.run({ value: u2, issues: [] }, a2);
      d instanceof Promise || s2 instanceof Promise ? r2.push(Promise.all([d, s2]).then(([m2, c]) => {
        Br(m2, c, n, o2, t2, e2, a2);
      })) : Br(d, s2, n, o2, t2, e2, a2);
    }
    return r2.length ? Promise.all(r2).then(() => n) : n;
  };
});
function Br(e2, i2, n, a2, t2, r2, o2) {
  e2.issues.length && (Ot.has(typeof a2) ? n.issues.push(...re(a2, e2.issues)) : n.issues.push({ code: "invalid_key", origin: "map", input: t2, inst: r2, issues: e2.issues.map((u2) => te(u2, o2, F())) })), i2.issues.length && (Ot.has(typeof a2) ? n.issues.push(...re(a2, i2.issues)) : n.issues.push({ origin: "map", code: "invalid_element", input: t2, inst: r2, key: a2, issues: i2.issues.map((u2) => te(u2, o2, F())) })), n.value.set(e2.value, i2.value);
}
var Su = f("$ZodSet", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => {
    let t2 = n.value;
    if (!(t2 instanceof Set)) return n.issues.push({ input: t2, inst: e2, expected: "set", code: "invalid_type" }), n;
    let r2 = [];
    n.value = /* @__PURE__ */ new Set();
    for (let o2 of t2) {
      let u2 = i2.valueType._zod.run({ value: o2, issues: [] }, a2);
      u2 instanceof Promise ? r2.push(u2.then((d) => Hr(d, n))) : Hr(u2, n);
    }
    return r2.length ? Promise.all(r2).then(() => n) : n;
  };
});
function Hr(e2, i2) {
  e2.issues.length && i2.issues.push(...e2.issues), i2.value.add(e2.value);
}
var zu = f("$ZodEnum", (e2, i2) => {
  k.init(e2, i2);
  let n = Li(i2.entries), a2 = new Set(n);
  e2._zod.values = a2, e2._zod.pattern = new RegExp(`^(${n.filter((t2) => Ot.has(typeof t2)).map((t2) => typeof t2 == "string" ? se(t2) : t2.toString()).join("|")})$`), e2._zod.parse = (t2, r2) => {
    let o2 = t2.value;
    return a2.has(o2) || t2.issues.push({ code: "invalid_value", values: n, input: o2, inst: e2 }), t2;
  };
}), Uu = f("$ZodLiteral", (e2, i2) => {
  if (k.init(e2, i2), i2.values.length === 0) throw Error("Cannot create literal schema with no valid values");
  let n = new Set(i2.values);
  e2._zod.values = n, e2._zod.pattern = new RegExp(`^(${i2.values.map((a2) => typeof a2 == "string" ? se(a2) : a2 ? se(a2.toString()) : String(a2)).join("|")})$`), e2._zod.parse = (a2, t2) => {
    let r2 = a2.value;
    return n.has(r2) || a2.issues.push({ code: "invalid_value", values: i2.values, input: r2, inst: e2 }), a2;
  };
}), Ou = f("$ZodFile", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => {
    let t2 = n.value;
    return t2 instanceof File || n.issues.push({ expected: "file", code: "invalid_type", input: t2, inst: e2 }), n;
  };
}), ju = f("$ZodTransform", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => {
    if (a2.direction === "backward") throw new Tt(e2.constructor.name);
    let t2 = i2.transform(n.value, n);
    if (a2.async) return (t2 instanceof Promise ? t2 : Promise.resolve(t2)).then((r2) => (n.value = r2, n));
    if (t2 instanceof Promise) throw new ke();
    return n.value = t2, n;
  };
});
function Xr(e2, i2) {
  return e2.issues.length && i2 === void 0 ? { issues: [], value: void 0 } : e2;
}
var ln = f("$ZodOptional", (e2, i2) => {
  k.init(e2, i2), e2._zod.optin = "optional", e2._zod.optout = "optional", w(e2._zod, "values", () => i2.innerType._zod.values ? /* @__PURE__ */ new Set([...i2.innerType._zod.values, void 0]) : void 0), w(e2._zod, "pattern", () => {
    let n = i2.innerType._zod.pattern;
    return n ? new RegExp(`^(${At(n.source)})?$`) : void 0;
  }), e2._zod.parse = (n, a2) => {
    if (i2.innerType._zod.optin === "optional") {
      let t2 = i2.innerType._zod.run(n, a2);
      return t2 instanceof Promise ? t2.then((r2) => Xr(r2, n.value)) : Xr(t2, n.value);
    }
    return n.value === void 0 ? n : i2.innerType._zod.run(n, a2);
  };
}), Zu = f("$ZodExactOptional", (e2, i2) => {
  ln.init(e2, i2), w(e2._zod, "values", () => i2.innerType._zod.values), w(e2._zod, "pattern", () => i2.innerType._zod.pattern), e2._zod.parse = (n, a2) => i2.innerType._zod.run(n, a2);
}), Nu = f("$ZodNullable", (e2, i2) => {
  k.init(e2, i2), w(e2._zod, "optin", () => i2.innerType._zod.optin), w(e2._zod, "optout", () => i2.innerType._zod.optout), w(e2._zod, "pattern", () => {
    let n = i2.innerType._zod.pattern;
    return n ? new RegExp(`^(${At(n.source)}|null)$`) : void 0;
  }), w(e2._zod, "values", () => i2.innerType._zod.values ? /* @__PURE__ */ new Set([...i2.innerType._zod.values, null]) : void 0), e2._zod.parse = (n, a2) => n.value === null ? n : i2.innerType._zod.run(n, a2);
}), Pu = f("$ZodDefault", (e2, i2) => {
  k.init(e2, i2), e2._zod.optin = "optional", w(e2._zod, "values", () => i2.innerType._zod.values), e2._zod.parse = (n, a2) => {
    if (a2.direction === "backward") return i2.innerType._zod.run(n, a2);
    if (n.value === void 0) return n.value = i2.defaultValue, n;
    let t2 = i2.innerType._zod.run(n, a2);
    return t2 instanceof Promise ? t2.then((r2) => Yr(r2, i2)) : Yr(t2, i2);
  };
});
function Yr(e2, i2) {
  return e2.value === void 0 && (e2.value = i2.defaultValue), e2;
}
var Du = f("$ZodPrefault", (e2, i2) => {
  k.init(e2, i2), e2._zod.optin = "optional", w(e2._zod, "values", () => i2.innerType._zod.values), e2._zod.parse = (n, a2) => (a2.direction === "backward" || n.value === void 0 && (n.value = i2.defaultValue), i2.innerType._zod.run(n, a2));
}), Eu = f("$ZodNonOptional", (e2, i2) => {
  k.init(e2, i2), w(e2._zod, "values", () => {
    let n = i2.innerType._zod.values;
    return n ? new Set([...n].filter((a2) => a2 !== void 0)) : void 0;
  }), e2._zod.parse = (n, a2) => {
    let t2 = i2.innerType._zod.run(n, a2);
    return t2 instanceof Promise ? t2.then((r2) => Qr(r2, e2)) : Qr(t2, e2);
  };
});
function Qr(e2, i2) {
  return !e2.issues.length && e2.value === void 0 && e2.issues.push({ code: "invalid_type", expected: "nonoptional", input: e2.value, inst: i2 }), e2;
}
var Tu = f("$ZodSuccess", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => {
    if (a2.direction === "backward") throw new Tt("ZodSuccess");
    let t2 = i2.innerType._zod.run(n, a2);
    return t2 instanceof Promise ? t2.then((r2) => (n.value = r2.issues.length === 0, n)) : (n.value = t2.issues.length === 0, n);
  };
}), Au = f("$ZodCatch", (e2, i2) => {
  k.init(e2, i2), w(e2._zod, "optin", () => i2.innerType._zod.optin), w(e2._zod, "optout", () => i2.innerType._zod.optout), w(e2._zod, "values", () => i2.innerType._zod.values), e2._zod.parse = (n, a2) => {
    if (a2.direction === "backward") return i2.innerType._zod.run(n, a2);
    let t2 = i2.innerType._zod.run(n, a2);
    return t2 instanceof Promise ? t2.then((r2) => (n.value = r2.value, r2.issues.length && (n.value = i2.catchValue({ ...n, error: { issues: r2.issues.map((o2) => te(o2, a2, F())) }, input: n.value }), n.issues = []), n)) : (n.value = t2.value, t2.issues.length && (n.value = i2.catchValue({ ...n, error: { issues: t2.issues.map((r2) => te(r2, a2, F())) }, input: n.value }), n.issues = []), n);
  };
}), Ru = f("$ZodNaN", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => ((typeof n.value != "number" || !Number.isNaN(n.value)) && n.issues.push({ input: n.value, inst: e2, expected: "nan", code: "invalid_type" }), n);
}), Cu = f("$ZodPipe", (e2, i2) => {
  k.init(e2, i2), w(e2._zod, "values", () => i2.in._zod.values), w(e2._zod, "optin", () => i2.in._zod.optin), w(e2._zod, "optout", () => i2.out._zod.optout), w(e2._zod, "propValues", () => i2.in._zod.propValues), e2._zod.parse = (n, a2) => {
    if (a2.direction === "backward") {
      let r2 = i2.out._zod.run(n, a2);
      return r2 instanceof Promise ? r2.then((o2) => xt(o2, i2.in, a2)) : xt(r2, i2.in, a2);
    }
    let t2 = i2.in._zod.run(n, a2);
    return t2 instanceof Promise ? t2.then((r2) => xt(r2, i2.out, a2)) : xt(t2, i2.out, a2);
  };
});
function xt(e2, i2, n) {
  return e2.issues.length ? (e2.aborted = true, e2) : i2._zod.run({ value: e2.value, issues: e2.issues }, n);
}
var dn = f("$ZodCodec", (e2, i2) => {
  k.init(e2, i2), w(e2._zod, "values", () => i2.in._zod.values), w(e2._zod, "optin", () => i2.in._zod.optin), w(e2._zod, "optout", () => i2.out._zod.optout), w(e2._zod, "propValues", () => i2.in._zod.propValues), e2._zod.parse = (n, a2) => {
    if ((a2.direction || "forward") === "forward") {
      let t2 = i2.in._zod.run(n, a2);
      return t2 instanceof Promise ? t2.then((r2) => wt(r2, i2, a2)) : wt(t2, i2, a2);
    } else {
      let t2 = i2.out._zod.run(n, a2);
      return t2 instanceof Promise ? t2.then((r2) => wt(r2, i2, a2)) : wt(t2, i2, a2);
    }
  };
});
function wt(e2, i2, n) {
  if (e2.issues.length) return e2.aborted = true, e2;
  if ((n.direction || "forward") === "forward") {
    let a2 = i2.transform(e2.value, e2);
    return a2 instanceof Promise ? a2.then((t2) => St(e2, t2, i2.out, n)) : St(e2, a2, i2.out, n);
  } else {
    let a2 = i2.reverseTransform(e2.value, e2);
    return a2 instanceof Promise ? a2.then((t2) => St(e2, t2, i2.in, n)) : St(e2, a2, i2.in, n);
  }
}
function St(e2, i2, n, a2) {
  return e2.issues.length ? (e2.aborted = true, e2) : n._zod.run({ value: i2, issues: e2.issues }, a2);
}
var Lu = f("$ZodReadonly", (e2, i2) => {
  k.init(e2, i2), w(e2._zod, "propValues", () => i2.innerType._zod.propValues), w(e2._zod, "values", () => i2.innerType._zod.values), w(e2._zod, "optin", () => {
    var n, a2;
    return (a2 = (n = i2.innerType) == null ? void 0 : n._zod) == null ? void 0 : a2.optin;
  }), w(e2._zod, "optout", () => {
    var n, a2;
    return (a2 = (n = i2.innerType) == null ? void 0 : n._zod) == null ? void 0 : a2.optout;
  }), e2._zod.parse = (n, a2) => {
    if (a2.direction === "backward") return i2.innerType._zod.run(n, a2);
    let t2 = i2.innerType._zod.run(n, a2);
    return t2 instanceof Promise ? t2.then(ea) : ea(t2);
  };
});
function ea(e2) {
  return e2.value = Object.freeze(e2.value), e2;
}
var Ju = f("$ZodTemplateLiteral", (e2, i2) => {
  k.init(e2, i2);
  let n = [];
  for (let a2 of i2.parts) if (typeof a2 == "object" && a2 !== null) {
    if (!a2._zod.pattern) throw Error(`Invalid template literal part, no pattern found: ${[...a2._zod.traits].shift()}`);
    let t2 = a2._zod.pattern instanceof RegExp ? a2._zod.pattern.source : a2._zod.pattern;
    if (!t2) throw Error(`Invalid template literal part: ${a2._zod.traits}`);
    let r2 = t2.startsWith("^") ? 1 : 0, o2 = t2.endsWith("$") ? t2.length - 1 : t2.length;
    n.push(t2.slice(r2, o2));
  } else if (a2 === null || ka.has(typeof a2)) n.push(se(`${a2}`));
  else throw Error(`Invalid template literal part: ${a2}`);
  e2._zod.pattern = new RegExp(`^${n.join("")}$`), e2._zod.parse = (a2, t2) => typeof a2.value != "string" ? (a2.issues.push({ input: a2.value, inst: e2, expected: "string", code: "invalid_type" }), a2) : (e2._zod.pattern.lastIndex = 0, e2._zod.pattern.test(a2.value) || a2.issues.push({ input: a2.value, inst: e2, code: "invalid_format", format: i2.format ?? "template_literal", pattern: e2._zod.pattern.source }), a2);
}), Mu = f("$ZodFunction", (e2, i2) => (k.init(e2, i2), e2._def = i2, e2._zod.def = i2, e2.implement = (n) => {
  if (typeof n != "function") throw Error("implement() must be called with a function");
  return function(...a2) {
    let t2 = e2._def.input ? Ei(e2._def.input, a2) : a2, r2 = Reflect.apply(n, this, t2);
    return e2._def.output ? Ei(e2._def.output, r2) : r2;
  };
}, e2.implementAsync = (n) => {
  if (typeof n != "function") throw Error("implementAsync() must be called with a function");
  return async function(...a2) {
    let t2 = e2._def.input ? await Ti(e2._def.input, a2) : a2, r2 = await Reflect.apply(n, this, t2);
    return e2._def.output ? await Ti(e2._def.output, r2) : r2;
  };
}, e2._zod.parse = (n, a2) => typeof n.value != "function" ? (n.issues.push({ code: "invalid_type", expected: "function", input: n.value, inst: e2 }), n) : (e2._def.output && e2._def.output._zod.def.type === "promise" ? n.value = e2.implementAsync(n.value) : n.value = e2.implement(n.value), n), e2.input = (...n) => {
  let a2 = e2.constructor;
  return Array.isArray(n[0]) ? new a2({ type: "function", input: new sn({ type: "tuple", items: n[0], rest: n[1] }), output: e2._def.output }) : new a2({ type: "function", input: n[0], output: e2._def.output });
}, e2.output = (n) => new e2.constructor({ type: "function", input: e2._def.input, output: n }), e2)), Fu = f("$ZodPromise", (e2, i2) => {
  k.init(e2, i2), e2._zod.parse = (n, a2) => Promise.resolve(n.value).then((t2) => i2.innerType._zod.run({ value: t2, issues: [] }, a2));
}), qu = f("$ZodLazy", (e2, i2) => {
  k.init(e2, i2), w(e2._zod, "innerType", () => i2.getter()), w(e2._zod, "pattern", () => {
    var n, a2;
    return (a2 = (n = e2._zod.innerType) == null ? void 0 : n._zod) == null ? void 0 : a2.pattern;
  }), w(e2._zod, "propValues", () => {
    var n, a2;
    return (a2 = (n = e2._zod.innerType) == null ? void 0 : n._zod) == null ? void 0 : a2.propValues;
  }), w(e2._zod, "optin", () => {
    var n, a2;
    return ((a2 = (n = e2._zod.innerType) == null ? void 0 : n._zod) == null ? void 0 : a2.optin) ?? void 0;
  }), w(e2._zod, "optout", () => {
    var n, a2;
    return ((a2 = (n = e2._zod.innerType) == null ? void 0 : n._zod) == null ? void 0 : a2.optout) ?? void 0;
  }), e2._zod.parse = (n, a2) => e2._zod.innerType._zod.run(n, a2);
}), Wu = f("$ZodCustom", (e2, i2) => {
  E.init(e2, i2), k.init(e2, i2), e2._zod.parse = (n, a2) => n, e2._zod.check = (n) => {
    let a2 = n.value, t2 = i2.fn(a2);
    if (t2 instanceof Promise) return t2.then((r2) => ta(r2, n, a2, e2));
    ta(t2, n, a2, e2);
  };
});
function ta(e2, i2, n, a2) {
  if (!e2) {
    let t2 = { code: "custom", input: n, inst: a2, path: [...a2._zod.def.path ?? []], continue: !a2._zod.def.abort };
    a2._zod.def.params && (t2.params = a2._zod.def.params), i2.issues.push(jt(t2));
  }
}
var cn = {};
le(cn, { zhTW: () => wp, zhCN: () => Ip, yo: () => zp, vi: () => _p, uz: () => bp, ur: () => hp, uk: () => Ku, ua: () => vp, tr: () => fp, th: () => cp, ta: () => lp, sv: () => up, sl: () => ap, ru: () => np, pt: () => tp, ps: () => Xf, pl: () => Qf, ota: () => Bf, no: () => Gf, nl: () => Wf, ms: () => Ff, mk: () => Jf, lt: () => Cf, ko: () => Af, km: () => Gu, kh: () => Ef, ka: () => Pf, ja: () => Zf, it: () => Of, is: () => zf, id: () => wf, hy: () => If, hu: () => _f, he: () => bf, frCA: () => hf, fr: () => vf, fi: () => ff, fa: () => cf, es: () => lf, eo: () => uf, en: () => Vu, de: () => rf, da: () => tf, cs: () => Qm, ca: () => Xm, bg: () => Bm, be: () => Gm, az: () => Wm, ar: () => Fm });
var Mm = () => {
  let e2 = { string: { unit: "حرف", verb: "أن يحوي" }, file: { unit: "بايت", verb: "أن يحوي" }, array: { unit: "عنصر", verb: "أن يحوي" }, set: { unit: "عنصر", verb: "أن يحوي" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "مدخل", email: "بريد إلكتروني", url: "رابط", emoji: "إيموجي", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "تاريخ ووقت بمعيار ISO", date: "تاريخ بمعيار ISO", time: "وقت بمعيار ISO", duration: "مدة بمعيار ISO", ipv4: "عنوان IPv4", ipv6: "عنوان IPv6", cidrv4: "مدى عناوين بصيغة IPv4", cidrv6: "مدى عناوين بصيغة IPv6", base64: "نَص بترميز base64-encoded", base64url: "نَص بترميز base64url-encoded", json_string: "نَص على هيئة JSON", e164: "رقم هاتف بمعيار E.164", jwt: "JWT", template_literal: "مدخل" }, a2 = { nan: "NaN" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `مدخلات غير مقبولة: يفترض إدخال instanceof ${t2.expected}، ولكن تم إدخال ${u2}` : `مدخلات غير مقبولة: يفترض إدخال ${r2}، ولكن تم إدخال ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `مدخلات غير مقبولة: يفترض إدخال ${b(t2.values[0])}` : `اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? ` أكبر من اللازم: يفترض أن تكون ${t2.origin ?? "القيمة"} ${r2} ${t2.maximum.toString()} ${o2.unit ?? "عنصر"}` : `أكبر من اللازم: يفترض أن تكون ${t2.origin ?? "القيمة"} ${r2} ${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `أصغر من اللازم: يفترض لـ ${t2.origin} أن يكون ${r2} ${t2.minimum.toString()} ${o2.unit}` : `أصغر من اللازم: يفترض لـ ${t2.origin} أن يكون ${r2} ${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `نَص غير مقبول: يجب أن يبدأ بـ "${t2.prefix}"` : r2.format === "ends_with" ? `نَص غير مقبول: يجب أن ينتهي بـ "${r2.suffix}"` : r2.format === "includes" ? `نَص غير مقبول: يجب أن يتضمَّن "${r2.includes}"` : r2.format === "regex" ? `نَص غير مقبول: يجب أن يطابق النمط ${r2.pattern}` : `${n[r2.format] ?? t2.format} غير مقبول`;
      }
      case "not_multiple_of":
        return `رقم غير مقبول: يجب أن يكون من مضاعفات ${t2.divisor}`;
      case "unrecognized_keys":
        return `معرف${t2.keys.length > 1 ? "ات" : ""} غريب${t2.keys.length > 1 ? "ة" : ""}: ${v(t2.keys, "، ")}`;
      case "invalid_key":
        return `معرف غير مقبول في ${t2.origin}`;
      case "invalid_union":
        return "مدخل غير مقبول";
      case "invalid_element":
        return `مدخل غير مقبول في ${t2.origin}`;
      default:
        return "مدخل غير مقبول";
    }
  };
};
function Fm() {
  return { localeError: Mm() };
}
var qm = () => {
  let e2 = { string: { unit: "simvol", verb: "olmalıdır" }, file: { unit: "bayt", verb: "olmalıdır" }, array: { unit: "element", verb: "olmalıdır" }, set: { unit: "element", verb: "olmalıdır" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }, a2 = { nan: "NaN" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Yanlış dəyər: gözlənilən instanceof ${t2.expected}, daxil olan ${u2}` : `Yanlış dəyər: gözlənilən ${r2}, daxil olan ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Yanlış dəyər: gözlənilən ${b(t2.values[0])}` : `Yanlış seçim: aşağıdakılardan biri olmalıdır: ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Çox böyük: gözlənilən ${t2.origin ?? "dəyər"} ${r2}${t2.maximum.toString()} ${o2.unit ?? "element"}` : `Çox böyük: gözlənilən ${t2.origin ?? "dəyər"} ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Çox kiçik: gözlənilən ${t2.origin} ${r2}${t2.minimum.toString()} ${o2.unit}` : `Çox kiçik: gözlənilən ${t2.origin} ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Yanlış mətn: "${r2.prefix}" ilə başlamalıdır` : r2.format === "ends_with" ? `Yanlış mətn: "${r2.suffix}" ilə bitməlidir` : r2.format === "includes" ? `Yanlış mətn: "${r2.includes}" daxil olmalıdır` : r2.format === "regex" ? `Yanlış mətn: ${r2.pattern} şablonuna uyğun olmalıdır` : `Yanlış ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Yanlış ədəd: ${t2.divisor} ilə bölünə bilən olmalıdır`;
      case "unrecognized_keys":
        return `Tanınmayan açar${t2.keys.length > 1 ? "lar" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `${t2.origin} daxilində yanlış açar`;
      case "invalid_union":
        return "Yanlış dəyər";
      case "invalid_element":
        return `${t2.origin} daxilində yanlış dəyər`;
      default:
        return "Yanlış dəyər";
    }
  };
};
function Wm() {
  return { localeError: qm() };
}
function ia(e2, i2, n, a2) {
  let t2 = Math.abs(e2), r2 = t2 % 10, o2 = t2 % 100;
  return o2 >= 11 && o2 <= 19 ? a2 : r2 === 1 ? i2 : r2 >= 2 && r2 <= 4 ? n : a2;
}
var Vm = () => {
  let e2 = { string: { unit: { one: "сімвал", few: "сімвалы", many: "сімвалаў" }, verb: "мець" }, array: { unit: { one: "элемент", few: "элементы", many: "элементаў" }, verb: "мець" }, set: { unit: { one: "элемент", few: "элементы", many: "элементаў" }, verb: "мець" }, file: { unit: { one: "байт", few: "байты", many: "байтаў" }, verb: "мець" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "увод", email: "email адрас", url: "URL", emoji: "эмодзі", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO дата і час", date: "ISO дата", time: "ISO час", duration: "ISO працягласць", ipv4: "IPv4 адрас", ipv6: "IPv6 адрас", cidrv4: "IPv4 дыяпазон", cidrv6: "IPv6 дыяпазон", base64: "радок у фармаце base64", base64url: "радок у фармаце base64url", json_string: "JSON радок", e164: "нумар E.164", jwt: "JWT", template_literal: "увод" }, a2 = { nan: "NaN", number: "лік", array: "масіў" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Няправільны ўвод: чакаўся instanceof ${t2.expected}, атрымана ${u2}` : `Няправільны ўвод: чакаўся ${r2}, атрымана ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Няправільны ўвод: чакалася ${b(t2.values[0])}` : `Няправільны варыянт: чакаўся адзін з ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        if (o2) {
          let u2 = Number(t2.maximum), d = ia(u2, o2.unit.one, o2.unit.few, o2.unit.many);
          return `Занадта вялікі: чакалася, што ${t2.origin ?? "значэнне"} павінна ${o2.verb} ${r2}${t2.maximum.toString()} ${d}`;
        }
        return `Занадта вялікі: чакалася, што ${t2.origin ?? "значэнне"} павінна быць ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        if (o2) {
          let u2 = Number(t2.minimum), d = ia(u2, o2.unit.one, o2.unit.few, o2.unit.many);
          return `Занадта малы: чакалася, што ${t2.origin} павінна ${o2.verb} ${r2}${t2.minimum.toString()} ${d}`;
        }
        return `Занадта малы: чакалася, што ${t2.origin} павінна быць ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Няправільны радок: павінен пачынацца з "${r2.prefix}"` : r2.format === "ends_with" ? `Няправільны радок: павінен заканчвацца на "${r2.suffix}"` : r2.format === "includes" ? `Няправільны радок: павінен змяшчаць "${r2.includes}"` : r2.format === "regex" ? `Няправільны радок: павінен адпавядаць шаблону ${r2.pattern}` : `Няправільны ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Няправільны лік: павінен быць кратным ${t2.divisor}`;
      case "unrecognized_keys":
        return `Нераспазнаны ${t2.keys.length > 1 ? "ключы" : "ключ"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Няправільны ключ у ${t2.origin}`;
      case "invalid_union":
        return "Няправільны ўвод";
      case "invalid_element":
        return `Няправільнае значэнне ў ${t2.origin}`;
      default:
        return "Няправільны ўвод";
    }
  };
};
function Gm() {
  return { localeError: Vm() };
}
var Km = () => {
  let e2 = { string: { unit: "символа", verb: "да съдържа" }, file: { unit: "байта", verb: "да съдържа" }, array: { unit: "елемента", verb: "да съдържа" }, set: { unit: "елемента", verb: "да съдържа" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "вход", email: "имейл адрес", url: "URL", emoji: "емоджи", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO време", date: "ISO дата", time: "ISO време", duration: "ISO продължителност", ipv4: "IPv4 адрес", ipv6: "IPv6 адрес", cidrv4: "IPv4 диапазон", cidrv6: "IPv6 диапазон", base64: "base64-кодиран низ", base64url: "base64url-кодиран низ", json_string: "JSON низ", e164: "E.164 номер", jwt: "JWT", template_literal: "вход" }, a2 = { nan: "NaN", number: "число", array: "масив" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Невалиден вход: очакван instanceof ${t2.expected}, получен ${u2}` : `Невалиден вход: очакван ${r2}, получен ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Невалиден вход: очакван ${b(t2.values[0])}` : `Невалидна опция: очаквано едно от ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Твърде голямо: очаква се ${t2.origin ?? "стойност"} да съдържа ${r2}${t2.maximum.toString()} ${o2.unit ?? "елемента"}` : `Твърде голямо: очаква се ${t2.origin ?? "стойност"} да бъде ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Твърде малко: очаква се ${t2.origin} да съдържа ${r2}${t2.minimum.toString()} ${o2.unit}` : `Твърде малко: очаква се ${t2.origin} да бъде ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        if (r2.format === "starts_with") return `Невалиден низ: трябва да започва с "${r2.prefix}"`;
        if (r2.format === "ends_with") return `Невалиден низ: трябва да завършва с "${r2.suffix}"`;
        if (r2.format === "includes") return `Невалиден низ: трябва да включва "${r2.includes}"`;
        if (r2.format === "regex") return `Невалиден низ: трябва да съвпада с ${r2.pattern}`;
        let o2 = "Невалиден";
        return r2.format === "emoji" && (o2 = "Невалидно"), r2.format === "datetime" && (o2 = "Невалидно"), r2.format === "date" && (o2 = "Невалидна"), r2.format === "time" && (o2 = "Невалидно"), r2.format === "duration" && (o2 = "Невалидна"), `${o2} ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Невалидно число: трябва да бъде кратно на ${t2.divisor}`;
      case "unrecognized_keys":
        return `Неразпознат${t2.keys.length > 1 ? "и" : ""} ключ${t2.keys.length > 1 ? "ове" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Невалиден ключ в ${t2.origin}`;
      case "invalid_union":
        return "Невалиден вход";
      case "invalid_element":
        return `Невалидна стойност в ${t2.origin}`;
      default:
        return "Невалиден вход";
    }
  };
};
function Bm() {
  return { localeError: Km() };
}
var Hm = () => {
  let e2 = { string: { unit: "caràcters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, set: { unit: "elements", verb: "contenir" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "entrada", email: "adreça electrònica", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data i hora ISO", date: "data ISO", time: "hora ISO", duration: "durada ISO", ipv4: "adreça IPv4", ipv6: "adreça IPv6", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "número E.164", jwt: "JWT", template_literal: "entrada" }, a2 = { nan: "NaN" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Tipus invàlid: s'esperava instanceof ${t2.expected}, s'ha rebut ${u2}` : `Tipus invàlid: s'esperava ${r2}, s'ha rebut ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Valor invàlid: s'esperava ${b(t2.values[0])}` : `Opció invàlida: s'esperava una de ${v(t2.values, " o ")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "com a màxim" : "menys de", o2 = i2(t2.origin);
        return o2 ? `Massa gran: s'esperava que ${t2.origin ?? "el valor"} contingués ${r2} ${t2.maximum.toString()} ${o2.unit ?? "elements"}` : `Massa gran: s'esperava que ${t2.origin ?? "el valor"} fos ${r2} ${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? "com a mínim" : "més de", o2 = i2(t2.origin);
        return o2 ? `Massa petit: s'esperava que ${t2.origin} contingués ${r2} ${t2.minimum.toString()} ${o2.unit}` : `Massa petit: s'esperava que ${t2.origin} fos ${r2} ${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Format invàlid: ha de començar amb "${r2.prefix}"` : r2.format === "ends_with" ? `Format invàlid: ha d'acabar amb "${r2.suffix}"` : r2.format === "includes" ? `Format invàlid: ha d'incloure "${r2.includes}"` : r2.format === "regex" ? `Format invàlid: ha de coincidir amb el patró ${r2.pattern}` : `Format invàlid per a ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Número invàlid: ha de ser múltiple de ${t2.divisor}`;
      case "unrecognized_keys":
        return `Clau${t2.keys.length > 1 ? "s" : ""} no reconeguda${t2.keys.length > 1 ? "s" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Clau invàlida a ${t2.origin}`;
      case "invalid_union":
        return "Entrada invàlida";
      case "invalid_element":
        return `Element invàlid a ${t2.origin}`;
      default:
        return "Entrada invàlida";
    }
  };
};
function Xm() {
  return { localeError: Hm() };
}
var Ym = () => {
  let e2 = { string: { unit: "znaků", verb: "mít" }, file: { unit: "bajtů", verb: "mít" }, array: { unit: "prvků", verb: "mít" }, set: { unit: "prvků", verb: "mít" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "regulární výraz", email: "e-mailová adresa", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "datum a čas ve formátu ISO", date: "datum ve formátu ISO", time: "čas ve formátu ISO", duration: "doba trvání ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "řetězec zakódovaný ve formátu base64", base64url: "řetězec zakódovaný ve formátu base64url", json_string: "řetězec ve formátu JSON", e164: "číslo E.164", jwt: "JWT", template_literal: "vstup" }, a2 = { nan: "NaN", number: "číslo", string: "řetězec", function: "funkce", array: "pole" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Neplatný vstup: očekáváno instanceof ${t2.expected}, obdrženo ${u2}` : `Neplatný vstup: očekáváno ${r2}, obdrženo ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Neplatný vstup: očekáváno ${b(t2.values[0])}` : `Neplatná možnost: očekávána jedna z hodnot ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Hodnota je příliš velká: ${t2.origin ?? "hodnota"} musí mít ${r2}${t2.maximum.toString()} ${o2.unit ?? "prvků"}` : `Hodnota je příliš velká: ${t2.origin ?? "hodnota"} musí být ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Hodnota je příliš malá: ${t2.origin ?? "hodnota"} musí mít ${r2}${t2.minimum.toString()} ${o2.unit ?? "prvků"}` : `Hodnota je příliš malá: ${t2.origin ?? "hodnota"} musí být ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Neplatný řetězec: musí začínat na "${r2.prefix}"` : r2.format === "ends_with" ? `Neplatný řetězec: musí končit na "${r2.suffix}"` : r2.format === "includes" ? `Neplatný řetězec: musí obsahovat "${r2.includes}"` : r2.format === "regex" ? `Neplatný řetězec: musí odpovídat vzoru ${r2.pattern}` : `Neplatný formát ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Neplatné číslo: musí být násobkem ${t2.divisor}`;
      case "unrecognized_keys":
        return `Neznámé klíče: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Neplatný klíč v ${t2.origin}`;
      case "invalid_union":
        return "Neplatný vstup";
      case "invalid_element":
        return `Neplatná hodnota v ${t2.origin}`;
      default:
        return "Neplatný vstup";
    }
  };
};
function Qm() {
  return { localeError: Ym() };
}
var ef = () => {
  let e2 = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, set: { unit: "elementer", verb: "indeholdt" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "input", email: "e-mailadresse", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dato- og klokkeslæt", date: "ISO-dato", time: "ISO-klokkeslæt", duration: "ISO-varighed", ipv4: "IPv4-område", ipv6: "IPv6-område", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" }, a2 = { nan: "NaN", string: "streng", number: "tal", boolean: "boolean", array: "liste", object: "objekt", set: "sæt", file: "fil" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Ugyldigt input: forventede instanceof ${t2.expected}, fik ${u2}` : `Ugyldigt input: forventede ${r2}, fik ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Ugyldig værdi: forventede ${b(t2.values[0])}` : `Ugyldigt valg: forventede en af følgende ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin), u2 = a2[t2.origin] ?? t2.origin;
        return o2 ? `For stor: forventede ${u2 ?? "value"} ${o2.verb} ${r2} ${t2.maximum.toString()} ${o2.unit ?? "elementer"}` : `For stor: forventede ${u2 ?? "value"} havde ${r2} ${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin), u2 = a2[t2.origin] ?? t2.origin;
        return o2 ? `For lille: forventede ${u2} ${o2.verb} ${r2} ${t2.minimum.toString()} ${o2.unit}` : `For lille: forventede ${u2} havde ${r2} ${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Ugyldig streng: skal starte med "${r2.prefix}"` : r2.format === "ends_with" ? `Ugyldig streng: skal ende med "${r2.suffix}"` : r2.format === "includes" ? `Ugyldig streng: skal indeholde "${r2.includes}"` : r2.format === "regex" ? `Ugyldig streng: skal matche mønsteret ${r2.pattern}` : `Ugyldig ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Ugyldigt tal: skal være deleligt med ${t2.divisor}`;
      case "unrecognized_keys":
        return `${t2.keys.length > 1 ? "Ukendte nøgler" : "Ukendt nøgle"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig nøgle i ${t2.origin}`;
      case "invalid_union":
        return "Ugyldigt input: matcher ingen af de tilladte typer";
      case "invalid_element":
        return `Ugyldig værdi i ${t2.origin}`;
      default:
        return "Ugyldigt input";
    }
  };
};
function tf() {
  return { localeError: ef() };
}
var nf = () => {
  let e2 = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, set: { unit: "Elemente", verb: "zu haben" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "Eingabe", email: "E-Mail-Adresse", url: "URL", emoji: "Emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-Datum und -Uhrzeit", date: "ISO-Datum", time: "ISO-Uhrzeit", duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", jwt: "JWT", template_literal: "Eingabe" }, a2 = { nan: "NaN", number: "Zahl", array: "Array" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Ungültige Eingabe: erwartet instanceof ${t2.expected}, erhalten ${u2}` : `Ungültige Eingabe: erwartet ${r2}, erhalten ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Ungültige Eingabe: erwartet ${b(t2.values[0])}` : `Ungültige Option: erwartet eine von ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Zu groß: erwartet, dass ${t2.origin ?? "Wert"} ${r2}${t2.maximum.toString()} ${o2.unit ?? "Elemente"} hat` : `Zu groß: erwartet, dass ${t2.origin ?? "Wert"} ${r2}${t2.maximum.toString()} ist`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Zu klein: erwartet, dass ${t2.origin} ${r2}${t2.minimum.toString()} ${o2.unit} hat` : `Zu klein: erwartet, dass ${t2.origin} ${r2}${t2.minimum.toString()} ist`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Ungültiger String: muss mit "${r2.prefix}" beginnen` : r2.format === "ends_with" ? `Ungültiger String: muss mit "${r2.suffix}" enden` : r2.format === "includes" ? `Ungültiger String: muss "${r2.includes}" enthalten` : r2.format === "regex" ? `Ungültiger String: muss dem Muster ${r2.pattern} entsprechen` : `Ungültig: ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Ungültige Zahl: muss ein Vielfaches von ${t2.divisor} sein`;
      case "unrecognized_keys":
        return `${t2.keys.length > 1 ? "Unbekannte Schlüssel" : "Unbekannter Schlüssel"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Ungültiger Schlüssel in ${t2.origin}`;
      case "invalid_union":
        return "Ungültige Eingabe";
      case "invalid_element":
        return `Ungültiger Wert in ${t2.origin}`;
      default:
        return "Ungültige Eingabe";
    }
  };
};
function rf() {
  return { localeError: nf() };
}
var af = () => {
  let e2 = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, array: { unit: "items", verb: "to have" }, set: { unit: "items", verb: "to have" }, map: { unit: "entries", verb: "to have" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }, a2 = { nan: "NaN" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return `Invalid input: expected ${r2}, received ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Invalid input: expected ${b(t2.values[0])}` : `Invalid option: expected one of ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Too big: expected ${t2.origin ?? "value"} to have ${r2}${t2.maximum.toString()} ${o2.unit ?? "elements"}` : `Too big: expected ${t2.origin ?? "value"} to be ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Too small: expected ${t2.origin} to have ${r2}${t2.minimum.toString()} ${o2.unit}` : `Too small: expected ${t2.origin} to be ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Invalid string: must start with "${r2.prefix}"` : r2.format === "ends_with" ? `Invalid string: must end with "${r2.suffix}"` : r2.format === "includes" ? `Invalid string: must include "${r2.includes}"` : r2.format === "regex" ? `Invalid string: must match pattern ${r2.pattern}` : `Invalid ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Invalid number: must be a multiple of ${t2.divisor}`;
      case "unrecognized_keys":
        return `Unrecognized key${t2.keys.length > 1 ? "s" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Invalid key in ${t2.origin}`;
      case "invalid_union":
        return "Invalid input";
      case "invalid_element":
        return `Invalid value in ${t2.origin}`;
      default:
        return "Invalid input";
    }
  };
};
function Vu() {
  return { localeError: af() };
}
var of = () => {
  let e2 = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, set: { unit: "elementojn", verb: "havi" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "enigo", email: "retadreso", url: "URL", emoji: "emoĝio", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datotempo", date: "ISO-dato", time: "ISO-tempo", duration: "ISO-daŭro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", jwt: "JWT", template_literal: "enigo" }, a2 = { nan: "NaN", number: "nombro", array: "tabelo", null: "senvalora" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Nevalida enigo: atendiĝis instanceof ${t2.expected}, riceviĝis ${u2}` : `Nevalida enigo: atendiĝis ${r2}, riceviĝis ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Nevalida enigo: atendiĝis ${b(t2.values[0])}` : `Nevalida opcio: atendiĝis unu el ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Tro granda: atendiĝis ke ${t2.origin ?? "valoro"} havu ${r2}${t2.maximum.toString()} ${o2.unit ?? "elementojn"}` : `Tro granda: atendiĝis ke ${t2.origin ?? "valoro"} havu ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Tro malgranda: atendiĝis ke ${t2.origin} havu ${r2}${t2.minimum.toString()} ${o2.unit}` : `Tro malgranda: atendiĝis ke ${t2.origin} estu ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Nevalida karaktraro: devas komenciĝi per "${r2.prefix}"` : r2.format === "ends_with" ? `Nevalida karaktraro: devas finiĝi per "${r2.suffix}"` : r2.format === "includes" ? `Nevalida karaktraro: devas inkluzivi "${r2.includes}"` : r2.format === "regex" ? `Nevalida karaktraro: devas kongrui kun la modelo ${r2.pattern}` : `Nevalida ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Nevalida nombro: devas esti oblo de ${t2.divisor}`;
      case "unrecognized_keys":
        return `Nekonata${t2.keys.length > 1 ? "j" : ""} ŝlosilo${t2.keys.length > 1 ? "j" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Nevalida ŝlosilo en ${t2.origin}`;
      case "invalid_union":
        return "Nevalida enigo";
      case "invalid_element":
        return `Nevalida valoro en ${t2.origin}`;
      default:
        return "Nevalida enigo";
    }
  };
};
function uf() {
  return { localeError: of() };
}
var sf = () => {
  let e2 = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, array: { unit: "elementos", verb: "tener" }, set: { unit: "elementos", verb: "tener" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "entrada", email: "dirección de correo electrónico", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "fecha y hora ISO", date: "fecha ISO", time: "hora ISO", duration: "duración ISO", ipv4: "dirección IPv4", ipv6: "dirección IPv6", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "número E.164", jwt: "JWT", template_literal: "entrada" }, a2 = { nan: "NaN", string: "texto", number: "número", boolean: "booleano", array: "arreglo", object: "objeto", set: "conjunto", file: "archivo", date: "fecha", bigint: "número grande", symbol: "símbolo", undefined: "indefinido", null: "nulo", function: "función", map: "mapa", record: "registro", tuple: "tupla", enum: "enumeración", union: "unión", literal: "literal", promise: "promesa", void: "vacío", never: "nunca", unknown: "desconocido", any: "cualquiera" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Entrada inválida: se esperaba instanceof ${t2.expected}, recibido ${u2}` : `Entrada inválida: se esperaba ${r2}, recibido ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Entrada inválida: se esperaba ${b(t2.values[0])}` : `Opción inválida: se esperaba una de ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin), u2 = a2[t2.origin] ?? t2.origin;
        return o2 ? `Demasiado grande: se esperaba que ${u2 ?? "valor"} tuviera ${r2}${t2.maximum.toString()} ${o2.unit ?? "elementos"}` : `Demasiado grande: se esperaba que ${u2 ?? "valor"} fuera ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin), u2 = a2[t2.origin] ?? t2.origin;
        return o2 ? `Demasiado pequeño: se esperaba que ${u2} tuviera ${r2}${t2.minimum.toString()} ${o2.unit}` : `Demasiado pequeño: se esperaba que ${u2} fuera ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Cadena inválida: debe comenzar con "${r2.prefix}"` : r2.format === "ends_with" ? `Cadena inválida: debe terminar en "${r2.suffix}"` : r2.format === "includes" ? `Cadena inválida: debe incluir "${r2.includes}"` : r2.format === "regex" ? `Cadena inválida: debe coincidir con el patrón ${r2.pattern}` : `Inválido ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Número inválido: debe ser múltiplo de ${t2.divisor}`;
      case "unrecognized_keys":
        return `Llave${t2.keys.length > 1 ? "s" : ""} desconocida${t2.keys.length > 1 ? "s" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Llave inválida en ${a2[t2.origin] ?? t2.origin}`;
      case "invalid_union":
        return "Entrada inválida";
      case "invalid_element":
        return `Valor inválido en ${a2[t2.origin] ?? t2.origin}`;
      default:
        return "Entrada inválida";
    }
  };
};
function lf() {
  return { localeError: sf() };
}
var df = () => {
  let e2 = { string: { unit: "کاراکتر", verb: "داشته باشد" }, file: { unit: "بایت", verb: "داشته باشد" }, array: { unit: "آیتم", verb: "داشته باشد" }, set: { unit: "آیتم", verb: "داشته باشد" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "ورودی", email: "آدرس ایمیل", url: "URL", emoji: "ایموجی", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "تاریخ و زمان ایزو", date: "تاریخ ایزو", time: "زمان ایزو", duration: "مدت زمان ایزو", ipv4: "IPv4 آدرس", ipv6: "IPv6 آدرس", cidrv4: "IPv4 دامنه", cidrv6: "IPv6 دامنه", base64: "base64-encoded رشته", base64url: "base64url-encoded رشته", json_string: "JSON رشته", e164: "E.164 عدد", jwt: "JWT", template_literal: "ورودی" }, a2 = { nan: "NaN", number: "عدد", array: "آرایه" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `ورودی نامعتبر: می‌بایست instanceof ${t2.expected} می‌بود، ${u2} دریافت شد` : `ورودی نامعتبر: می‌بایست ${r2} می‌بود، ${u2} دریافت شد`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `ورودی نامعتبر: می‌بایست ${b(t2.values[0])} می‌بود` : `گزینه نامعتبر: می‌بایست یکی از ${v(t2.values, "|")} می‌بود`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `خیلی بزرگ: ${t2.origin ?? "مقدار"} باید ${r2}${t2.maximum.toString()} ${o2.unit ?? "عنصر"} باشد` : `خیلی بزرگ: ${t2.origin ?? "مقدار"} باید ${r2}${t2.maximum.toString()} باشد`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `خیلی کوچک: ${t2.origin} باید ${r2}${t2.minimum.toString()} ${o2.unit} باشد` : `خیلی کوچک: ${t2.origin} باید ${r2}${t2.minimum.toString()} باشد`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `رشته نامعتبر: باید با "${r2.prefix}" شروع شود` : r2.format === "ends_with" ? `رشته نامعتبر: باید با "${r2.suffix}" تمام شود` : r2.format === "includes" ? `رشته نامعتبر: باید شامل "${r2.includes}" باشد` : r2.format === "regex" ? `رشته نامعتبر: باید با الگوی ${r2.pattern} مطابقت داشته باشد` : `${n[r2.format] ?? t2.format} نامعتبر`;
      }
      case "not_multiple_of":
        return `عدد نامعتبر: باید مضرب ${t2.divisor} باشد`;
      case "unrecognized_keys":
        return `کلید${t2.keys.length > 1 ? "های" : ""} ناشناس: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `کلید ناشناس در ${t2.origin}`;
      case "invalid_union":
        return "ورودی نامعتبر";
      case "invalid_element":
        return `مقدار نامعتبر در ${t2.origin}`;
      default:
        return "ورودی نامعتبر";
    }
  };
};
function cf() {
  return { localeError: df() };
}
var mf = () => {
  let e2 = { string: { unit: "merkkiä", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, date: { unit: "", subject: "päivämäärän" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "säännöllinen lauseke", email: "sähköpostiosoite", url: "URL-osoite", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-aikaleima", date: "ISO-päivämäärä", time: "ISO-aika", duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", jwt: "JWT", template_literal: "templaattimerkkijono" }, a2 = { nan: "NaN" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Virheellinen tyyppi: odotettiin instanceof ${t2.expected}, oli ${u2}` : `Virheellinen tyyppi: odotettiin ${r2}, oli ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Virheellinen syöte: täytyy olla ${b(t2.values[0])}` : `Virheellinen valinta: täytyy olla yksi seuraavista: ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Liian suuri: ${o2.subject} täytyy olla ${r2}${t2.maximum.toString()} ${o2.unit}`.trim() : `Liian suuri: arvon täytyy olla ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Liian pieni: ${o2.subject} täytyy olla ${r2}${t2.minimum.toString()} ${o2.unit}`.trim() : `Liian pieni: arvon täytyy olla ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Virheellinen syöte: täytyy alkaa "${r2.prefix}"` : r2.format === "ends_with" ? `Virheellinen syöte: täytyy loppua "${r2.suffix}"` : r2.format === "includes" ? `Virheellinen syöte: täytyy sisältää "${r2.includes}"` : r2.format === "regex" ? `Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${r2.pattern}` : `Virheellinen ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Virheellinen luku: täytyy olla luvun ${t2.divisor} monikerta`;
      case "unrecognized_keys":
        return `${t2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return "Virheellinen avain tietueessa";
      case "invalid_union":
        return "Virheellinen unioni";
      case "invalid_element":
        return "Virheellinen arvo joukossa";
      default:
        return "Virheellinen syöte";
    }
  };
};
function ff() {
  return { localeError: mf() };
}
var pf = () => {
  let e2 = { string: { unit: "caractères", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "éléments", verb: "avoir" }, set: { unit: "éléments", verb: "avoir" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "entrée", email: "adresse e-mail", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "date et heure ISO", date: "date ISO", time: "heure ISO", duration: "durée ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "chaîne encodée en base64", base64url: "chaîne encodée en base64url", json_string: "chaîne JSON", e164: "numéro E.164", jwt: "JWT", template_literal: "entrée" }, a2 = { nan: "NaN", number: "nombre", array: "tableau" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Entrée invalide : instanceof ${t2.expected} attendu, ${u2} reçu` : `Entrée invalide : ${r2} attendu, ${u2} reçu`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Entrée invalide : ${b(t2.values[0])} attendu` : `Option invalide : une valeur parmi ${v(t2.values, "|")} attendue`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Trop grand : ${t2.origin ?? "valeur"} doit ${o2.verb} ${r2}${t2.maximum.toString()} ${o2.unit ?? "élément(s)"}` : `Trop grand : ${t2.origin ?? "valeur"} doit être ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Trop petit : ${t2.origin} doit ${o2.verb} ${r2}${t2.minimum.toString()} ${o2.unit}` : `Trop petit : ${t2.origin} doit être ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Chaîne invalide : doit commencer par "${r2.prefix}"` : r2.format === "ends_with" ? `Chaîne invalide : doit se terminer par "${r2.suffix}"` : r2.format === "includes" ? `Chaîne invalide : doit inclure "${r2.includes}"` : r2.format === "regex" ? `Chaîne invalide : doit correspondre au modèle ${r2.pattern}` : `${n[r2.format] ?? t2.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit être un multiple de ${t2.divisor}`;
      case "unrecognized_keys":
        return `Clé${t2.keys.length > 1 ? "s" : ""} non reconnue${t2.keys.length > 1 ? "s" : ""} : ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Clé invalide dans ${t2.origin}`;
      case "invalid_union":
        return "Entrée invalide";
      case "invalid_element":
        return `Valeur invalide dans ${t2.origin}`;
      default:
        return "Entrée invalide";
    }
  };
};
function vf() {
  return { localeError: pf() };
}
var gf = () => {
  let e2 = { string: { unit: "caractères", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "éléments", verb: "avoir" }, set: { unit: "éléments", verb: "avoir" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "entrée", email: "adresse courriel", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "date-heure ISO", date: "date ISO", time: "heure ISO", duration: "durée ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "chaîne encodée en base64", base64url: "chaîne encodée en base64url", json_string: "chaîne JSON", e164: "numéro E.164", jwt: "JWT", template_literal: "entrée" }, a2 = { nan: "NaN" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Entrée invalide : attendu instanceof ${t2.expected}, reçu ${u2}` : `Entrée invalide : attendu ${r2}, reçu ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Entrée invalide : attendu ${b(t2.values[0])}` : `Option invalide : attendu l'une des valeurs suivantes ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "≤" : "<", o2 = i2(t2.origin);
        return o2 ? `Trop grand : attendu que ${t2.origin ?? "la valeur"} ait ${r2}${t2.maximum.toString()} ${o2.unit}` : `Trop grand : attendu que ${t2.origin ?? "la valeur"} soit ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? "≥" : ">", o2 = i2(t2.origin);
        return o2 ? `Trop petit : attendu que ${t2.origin} ait ${r2}${t2.minimum.toString()} ${o2.unit}` : `Trop petit : attendu que ${t2.origin} soit ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Chaîne invalide : doit commencer par "${r2.prefix}"` : r2.format === "ends_with" ? `Chaîne invalide : doit se terminer par "${r2.suffix}"` : r2.format === "includes" ? `Chaîne invalide : doit inclure "${r2.includes}"` : r2.format === "regex" ? `Chaîne invalide : doit correspondre au motif ${r2.pattern}` : `${n[r2.format] ?? t2.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit être un multiple de ${t2.divisor}`;
      case "unrecognized_keys":
        return `Clé${t2.keys.length > 1 ? "s" : ""} non reconnue${t2.keys.length > 1 ? "s" : ""} : ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Clé invalide dans ${t2.origin}`;
      case "invalid_union":
        return "Entrée invalide";
      case "invalid_element":
        return `Valeur invalide dans ${t2.origin}`;
      default:
        return "Entrée invalide";
    }
  };
};
function hf() {
  return { localeError: gf() };
}
var $f = () => {
  let e2 = { string: { label: "מחרוזת", gender: "f" }, number: { label: "מספר", gender: "m" }, boolean: { label: "ערך בוליאני", gender: "m" }, bigint: { label: "BigInt", gender: "m" }, date: { label: "תאריך", gender: "m" }, array: { label: "מערך", gender: "m" }, object: { label: "אובייקט", gender: "m" }, null: { label: "ערך ריק (null)", gender: "m" }, undefined: { label: "ערך לא מוגדר (undefined)", gender: "m" }, symbol: { label: "סימבול (Symbol)", gender: "m" }, function: { label: "פונקציה", gender: "f" }, map: { label: "מפה (Map)", gender: "f" }, set: { label: "קבוצה (Set)", gender: "f" }, file: { label: "קובץ", gender: "m" }, promise: { label: "Promise", gender: "m" }, NaN: { label: "NaN", gender: "m" }, unknown: { label: "ערך לא ידוע", gender: "m" }, value: { label: "ערך", gender: "m" } }, i2 = { string: { unit: "תווים", shortLabel: "קצר", longLabel: "ארוך" }, file: { unit: "בייטים", shortLabel: "קטן", longLabel: "גדול" }, array: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" }, set: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" }, number: { unit: "", shortLabel: "קטן", longLabel: "גדול" } }, n = (s2) => s2 ? e2[s2] : void 0, a2 = (s2) => {
    let m2 = n(s2);
    return m2 ? m2.label : s2 ?? e2.unknown.label;
  }, t2 = (s2) => `ה${a2(s2)}`, r2 = (s2) => {
    var m2;
    return (((m2 = n(s2)) == null ? void 0 : m2.gender) ?? "m") === "f" ? "צריכה להיות" : "צריך להיות";
  }, o2 = (s2) => s2 ? i2[s2] ?? null : null, u2 = { regex: { label: "קלט", gender: "m" }, email: { label: "כתובת אימייל", gender: "f" }, url: { label: "כתובת רשת", gender: "f" }, emoji: { label: "אימוג'י", gender: "m" }, uuid: { label: "UUID", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, cuid2: { label: "cuid2", gender: "m" }, ulid: { label: "ULID", gender: "m" }, xid: { label: "XID", gender: "m" }, ksuid: { label: "KSUID", gender: "m" }, datetime: { label: "תאריך וזמן ISO", gender: "m" }, date: { label: "תאריך ISO", gender: "m" }, time: { label: "זמן ISO", gender: "m" }, duration: { label: "משך זמן ISO", gender: "m" }, ipv4: { label: "כתובת IPv4", gender: "f" }, ipv6: { label: "כתובת IPv6", gender: "f" }, cidrv4: { label: "טווח IPv4", gender: "m" }, cidrv6: { label: "טווח IPv6", gender: "m" }, base64: { label: "מחרוזת בבסיס 64", gender: "f" }, base64url: { label: "מחרוזת בבסיס 64 לכתובות רשת", gender: "f" }, json_string: { label: "מחרוזת JSON", gender: "f" }, e164: { label: "מספר E.164", gender: "m" }, jwt: { label: "JWT", gender: "m" }, ends_with: { label: "קלט", gender: "m" }, includes: { label: "קלט", gender: "m" }, lowercase: { label: "קלט", gender: "m" }, starts_with: { label: "קלט", gender: "m" }, uppercase: { label: "קלט", gender: "m" } }, d = { nan: "NaN" };
  return (s2) => {
    var m2;
    switch (s2.code) {
      case "invalid_type": {
        let c = s2.expected, p2 = d[c ?? ""] ?? a2(c), $2 = _(s2.input), y = d[$2] ?? ((m2 = e2[$2]) == null ? void 0 : m2.label) ?? $2;
        return /^[A-Z]/.test(s2.expected) ? `קלט לא תקין: צריך להיות instanceof ${s2.expected}, התקבל ${y}` : `קלט לא תקין: צריך להיות ${p2}, התקבל ${y}`;
      }
      case "invalid_value": {
        if (s2.values.length === 1) return `ערך לא תקין: הערך חייב להיות ${b(s2.values[0])}`;
        let c = s2.values.map(($2) => b($2));
        if (s2.values.length === 2) return `ערך לא תקין: האפשרויות המתאימות הן ${c[0]} או ${c[1]}`;
        let p2 = c[c.length - 1];
        return `ערך לא תקין: האפשרויות המתאימות הן ${c.slice(0, -1).join(", ")} או ${p2}`;
      }
      case "too_big": {
        let c = o2(s2.origin), p2 = t2(s2.origin ?? "value");
        if (s2.origin === "string") return `${(c == null ? void 0 : c.longLabel) ?? "ארוך"} מדי: ${p2} צריכה להכיל ${s2.maximum.toString()} ${(c == null ? void 0 : c.unit) ?? ""} ${s2.inclusive ? "או פחות" : "לכל היותר"}`.trim();
        if (s2.origin === "number") {
          let x2 = s2.inclusive ? `קטן או שווה ל-${s2.maximum}` : `קטן מ-${s2.maximum}`;
          return `גדול מדי: ${p2} צריך להיות ${x2}`;
        }
        if (s2.origin === "array" || s2.origin === "set") {
          let x2 = s2.origin === "set" ? "צריכה" : "צריך", z2 = s2.inclusive ? `${s2.maximum} ${(c == null ? void 0 : c.unit) ?? ""} או פחות` : `פחות מ-${s2.maximum} ${(c == null ? void 0 : c.unit) ?? ""}`;
          return `גדול מדי: ${p2} ${x2} להכיל ${z2}`.trim();
        }
        let $2 = s2.inclusive ? "<=" : "<", y = r2(s2.origin ?? "value");
        return c != null && c.unit ? `${c.longLabel} מדי: ${p2} ${y} ${$2}${s2.maximum.toString()} ${c.unit}` : `${(c == null ? void 0 : c.longLabel) ?? "גדול"} מדי: ${p2} ${y} ${$2}${s2.maximum.toString()}`;
      }
      case "too_small": {
        let c = o2(s2.origin), p2 = t2(s2.origin ?? "value");
        if (s2.origin === "string") return `${(c == null ? void 0 : c.shortLabel) ?? "קצר"} מדי: ${p2} צריכה להכיל ${s2.minimum.toString()} ${(c == null ? void 0 : c.unit) ?? ""} ${s2.inclusive ? "או יותר" : "לפחות"}`.trim();
        if (s2.origin === "number") {
          let x2 = s2.inclusive ? `גדול או שווה ל-${s2.minimum}` : `גדול מ-${s2.minimum}`;
          return `קטן מדי: ${p2} צריך להיות ${x2}`;
        }
        if (s2.origin === "array" || s2.origin === "set") {
          let x2 = s2.origin === "set" ? "צריכה" : "צריך";
          if (s2.minimum === 1 && s2.inclusive) {
            let P2 = (s2.origin === "set", "לפחות פריט אחד");
            return `קטן מדי: ${p2} ${x2} להכיל ${P2}`;
          }
          let z2 = s2.inclusive ? `${s2.minimum} ${(c == null ? void 0 : c.unit) ?? ""} או יותר` : `יותר מ-${s2.minimum} ${(c == null ? void 0 : c.unit) ?? ""}`;
          return `קטן מדי: ${p2} ${x2} להכיל ${z2}`.trim();
        }
        let $2 = s2.inclusive ? ">=" : ">", y = r2(s2.origin ?? "value");
        return c != null && c.unit ? `${c.shortLabel} מדי: ${p2} ${y} ${$2}${s2.minimum.toString()} ${c.unit}` : `${(c == null ? void 0 : c.shortLabel) ?? "קטן"} מדי: ${p2} ${y} ${$2}${s2.minimum.toString()}`;
      }
      case "invalid_format": {
        let c = s2;
        if (c.format === "starts_with") return `המחרוזת חייבת להתחיל ב "${c.prefix}"`;
        if (c.format === "ends_with") return `המחרוזת חייבת להסתיים ב "${c.suffix}"`;
        if (c.format === "includes") return `המחרוזת חייבת לכלול "${c.includes}"`;
        if (c.format === "regex") return `המחרוזת חייבת להתאים לתבנית ${c.pattern}`;
        let p2 = u2[c.format], $2 = (p2 == null ? void 0 : p2.label) ?? c.format, y = ((p2 == null ? void 0 : p2.gender) ?? "m") === "f" ? "תקינה" : "תקין";
        return `${$2} לא ${y}`;
      }
      case "not_multiple_of":
        return `מספר לא תקין: חייב להיות מכפלה של ${s2.divisor}`;
      case "unrecognized_keys":
        return `מפתח${s2.keys.length > 1 ? "ות" : ""} לא מזוה${s2.keys.length > 1 ? "ים" : "ה"}: ${v(s2.keys, ", ")}`;
      case "invalid_key":
        return "שדה לא תקין באובייקט";
      case "invalid_union":
        return "קלט לא תקין";
      case "invalid_element":
        return `ערך לא תקין ב${t2(s2.origin ?? "array")}`;
      default:
        return "קלט לא תקין";
    }
  };
};
function bf() {
  return { localeError: $f() };
}
var yf = () => {
  let e2 = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, set: { unit: "elem", verb: "legyen" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "bemenet", email: "email cím", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO időbélyeg", date: "ISO dátum", time: "ISO idő", duration: "ISO időintervallum", ipv4: "IPv4 cím", ipv6: "IPv6 cím", cidrv4: "IPv4 tartomány", cidrv6: "IPv6 tartomány", base64: "base64-kódolt string", base64url: "base64url-kódolt string", json_string: "JSON string", e164: "E.164 szám", jwt: "JWT", template_literal: "bemenet" }, a2 = { nan: "NaN", number: "szám", array: "tömb" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Érvénytelen bemenet: a várt érték instanceof ${t2.expected}, a kapott érték ${u2}` : `Érvénytelen bemenet: a várt érték ${r2}, a kapott érték ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Érvénytelen bemenet: a várt érték ${b(t2.values[0])}` : `Érvénytelen opció: valamelyik érték várt ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Túl nagy: ${t2.origin ?? "érték"} mérete túl nagy ${r2}${t2.maximum.toString()} ${o2.unit ?? "elem"}` : `Túl nagy: a bemeneti érték ${t2.origin ?? "érték"} túl nagy: ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Túl kicsi: a bemeneti érték ${t2.origin} mérete túl kicsi ${r2}${t2.minimum.toString()} ${o2.unit}` : `Túl kicsi: a bemeneti érték ${t2.origin} túl kicsi ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Érvénytelen string: "${r2.prefix}" értékkel kell kezdődnie` : r2.format === "ends_with" ? `Érvénytelen string: "${r2.suffix}" értékkel kell végződnie` : r2.format === "includes" ? `Érvénytelen string: "${r2.includes}" értéket kell tartalmaznia` : r2.format === "regex" ? `Érvénytelen string: ${r2.pattern} mintának kell megfelelnie` : `Érvénytelen ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Érvénytelen szám: ${t2.divisor} többszörösének kell lennie`;
      case "unrecognized_keys":
        return `Ismeretlen kulcs${t2.keys.length > 1 ? "s" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Érvénytelen kulcs ${t2.origin}`;
      case "invalid_union":
        return "Érvénytelen bemenet";
      case "invalid_element":
        return `Érvénytelen érték: ${t2.origin}`;
      default:
        return "Érvénytelen bemenet";
    }
  };
};
function _f() {
  return { localeError: yf() };
}
function na(e2, i2, n) {
  return Math.abs(e2) === 1 ? i2 : n;
}
function Ne(e2) {
  if (!e2) return "";
  let i2 = ["ա", "ե", "ը", "ի", "ո", "ու", "օ"], n = e2[e2.length - 1];
  return e2 + (i2.includes(n) ? "ն" : "ը");
}
var kf = () => {
  let e2 = { string: { unit: { one: "նշան", many: "նշաններ" }, verb: "ունենալ" }, file: { unit: { one: "բայթ", many: "բայթեր" }, verb: "ունենալ" }, array: { unit: { one: "տարր", many: "տարրեր" }, verb: "ունենալ" }, set: { unit: { one: "տարր", many: "տարրեր" }, verb: "ունենալ" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "մուտք", email: "էլ. հասցե", url: "URL", emoji: "էմոջի", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO ամսաթիվ և ժամ", date: "ISO ամսաթիվ", time: "ISO ժամ", duration: "ISO տևողություն", ipv4: "IPv4 հասցե", ipv6: "IPv6 հասցե", cidrv4: "IPv4 միջակայք", cidrv6: "IPv6 միջակայք", base64: "base64 ձևաչափով տող", base64url: "base64url ձևաչափով տող", json_string: "JSON տող", e164: "E.164 համար", jwt: "JWT", template_literal: "մուտք" }, a2 = { nan: "NaN", number: "թիվ", array: "զանգված" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Սխալ մուտքագրում․ սպասվում էր instanceof ${t2.expected}, ստացվել է ${u2}` : `Սխալ մուտքագրում․ սպասվում էր ${r2}, ստացվել է ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Սխալ մուտքագրում․ սպասվում էր ${b(t2.values[1])}` : `Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        if (o2) {
          let u2 = Number(t2.maximum), d = na(u2, o2.unit.one, o2.unit.many);
          return `Չափազանց մեծ արժեք․ սպասվում է, որ ${Ne(t2.origin ?? "արժեք")} կունենա ${r2}${t2.maximum.toString()} ${d}`;
        }
        return `Չափազանց մեծ արժեք․ սպասվում է, որ ${Ne(t2.origin ?? "արժեք")} լինի ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        if (o2) {
          let u2 = Number(t2.minimum), d = na(u2, o2.unit.one, o2.unit.many);
          return `Չափազանց փոքր արժեք․ սպասվում է, որ ${Ne(t2.origin)} կունենա ${r2}${t2.minimum.toString()} ${d}`;
        }
        return `Չափազանց փոքր արժեք․ սպասվում է, որ ${Ne(t2.origin)} լինի ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Սխալ տող․ պետք է սկսվի "${r2.prefix}"-ով` : r2.format === "ends_with" ? `Սխալ տող․ պետք է ավարտվի "${r2.suffix}"-ով` : r2.format === "includes" ? `Սխալ տող․ պետք է պարունակի "${r2.includes}"` : r2.format === "regex" ? `Սխալ տող․ պետք է համապատասխանի ${r2.pattern} ձևաչափին` : `Սխալ ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Սխալ թիվ․ պետք է բազմապատիկ լինի ${t2.divisor}-ի`;
      case "unrecognized_keys":
        return `Չճանաչված բանալի${t2.keys.length > 1 ? "ներ" : ""}. ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Սխալ բանալի ${Ne(t2.origin)}-ում`;
      case "invalid_union":
        return "Սխալ մուտքագրում";
      case "invalid_element":
        return `Սխալ արժեք ${Ne(t2.origin)}-ում`;
      default:
        return "Սխալ մուտքագրում";
    }
  };
};
function If() {
  return { localeError: kf() };
}
var xf = () => {
  let e2 = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, set: { unit: "item", verb: "memiliki" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "input", email: "alamat email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "tanggal dan waktu format ISO", date: "tanggal format ISO", time: "jam format ISO", duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", jwt: "JWT", template_literal: "input" }, a2 = { nan: "NaN" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Input tidak valid: diharapkan instanceof ${t2.expected}, diterima ${u2}` : `Input tidak valid: diharapkan ${r2}, diterima ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Input tidak valid: diharapkan ${b(t2.values[0])}` : `Pilihan tidak valid: diharapkan salah satu dari ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Terlalu besar: diharapkan ${t2.origin ?? "value"} memiliki ${r2}${t2.maximum.toString()} ${o2.unit ?? "elemen"}` : `Terlalu besar: diharapkan ${t2.origin ?? "value"} menjadi ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Terlalu kecil: diharapkan ${t2.origin} memiliki ${r2}${t2.minimum.toString()} ${o2.unit}` : `Terlalu kecil: diharapkan ${t2.origin} menjadi ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `String tidak valid: harus dimulai dengan "${r2.prefix}"` : r2.format === "ends_with" ? `String tidak valid: harus berakhir dengan "${r2.suffix}"` : r2.format === "includes" ? `String tidak valid: harus menyertakan "${r2.includes}"` : r2.format === "regex" ? `String tidak valid: harus sesuai pola ${r2.pattern}` : `${n[r2.format] ?? t2.format} tidak valid`;
      }
      case "not_multiple_of":
        return `Angka tidak valid: harus kelipatan dari ${t2.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali ${t2.keys.length > 1 ? "s" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak valid di ${t2.origin}`;
      case "invalid_union":
        return "Input tidak valid";
      case "invalid_element":
        return `Nilai tidak valid di ${t2.origin}`;
      default:
        return "Input tidak valid";
    }
  };
};
function wf() {
  return { localeError: xf() };
}
var Sf = () => {
  let e2 = { string: { unit: "stafi", verb: "að hafa" }, file: { unit: "bæti", verb: "að hafa" }, array: { unit: "hluti", verb: "að hafa" }, set: { unit: "hluti", verb: "að hafa" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "gildi", email: "netfang", url: "vefslóð", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dagsetning og tími", date: "ISO dagsetning", time: "ISO tími", duration: "ISO tímalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 tölugildi", jwt: "JWT", template_literal: "gildi" }, a2 = { nan: "NaN", number: "númer", array: "fylki" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Rangt gildi: Þú slóst inn ${u2} þar sem á að vera instanceof ${t2.expected}` : `Rangt gildi: Þú slóst inn ${u2} þar sem á að vera ${r2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Rangt gildi: gert ráð fyrir ${b(t2.values[0])}` : `Ógilt val: má vera eitt af eftirfarandi ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Of stórt: gert er ráð fyrir að ${t2.origin ?? "gildi"} hafi ${r2}${t2.maximum.toString()} ${o2.unit ?? "hluti"}` : `Of stórt: gert er ráð fyrir að ${t2.origin ?? "gildi"} sé ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Of lítið: gert er ráð fyrir að ${t2.origin} hafi ${r2}${t2.minimum.toString()} ${o2.unit}` : `Of lítið: gert er ráð fyrir að ${t2.origin} sé ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Ógildur strengur: verður að byrja á "${r2.prefix}"` : r2.format === "ends_with" ? `Ógildur strengur: verður að enda á "${r2.suffix}"` : r2.format === "includes" ? `Ógildur strengur: verður að innihalda "${r2.includes}"` : r2.format === "regex" ? `Ógildur strengur: verður að fylgja mynstri ${r2.pattern}` : `Rangt ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Röng tala: verður að vera margfeldi af ${t2.divisor}`;
      case "unrecognized_keys":
        return `Óþekkt ${t2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Rangur lykill í ${t2.origin}`;
      case "invalid_union":
        return "Rangt gildi";
      case "invalid_element":
        return `Rangt gildi í ${t2.origin}`;
      default:
        return "Rangt gildi";
    }
  };
};
function zf() {
  return { localeError: Sf() };
}
var Uf = () => {
  let e2 = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, set: { unit: "elementi", verb: "avere" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "input", email: "indirizzo email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data e ora ISO", date: "data ISO", time: "ora ISO", duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", jwt: "JWT", template_literal: "input" }, a2 = { nan: "NaN", number: "numero", array: "vettore" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Input non valido: atteso instanceof ${t2.expected}, ricevuto ${u2}` : `Input non valido: atteso ${r2}, ricevuto ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Input non valido: atteso ${b(t2.values[0])}` : `Opzione non valida: atteso uno tra ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Troppo grande: ${t2.origin ?? "valore"} deve avere ${r2}${t2.maximum.toString()} ${o2.unit ?? "elementi"}` : `Troppo grande: ${t2.origin ?? "valore"} deve essere ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Troppo piccolo: ${t2.origin} deve avere ${r2}${t2.minimum.toString()} ${o2.unit}` : `Troppo piccolo: ${t2.origin} deve essere ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Stringa non valida: deve iniziare con "${r2.prefix}"` : r2.format === "ends_with" ? `Stringa non valida: deve terminare con "${r2.suffix}"` : r2.format === "includes" ? `Stringa non valida: deve includere "${r2.includes}"` : r2.format === "regex" ? `Stringa non valida: deve corrispondere al pattern ${r2.pattern}` : `Invalid ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Numero non valido: deve essere un multiplo di ${t2.divisor}`;
      case "unrecognized_keys":
        return `Chiav${t2.keys.length > 1 ? "i" : "e"} non riconosciut${t2.keys.length > 1 ? "e" : "a"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Chiave non valida in ${t2.origin}`;
      case "invalid_union":
        return "Input non valido";
      case "invalid_element":
        return `Valore non valido in ${t2.origin}`;
      default:
        return "Input non valido";
    }
  };
};
function Of() {
  return { localeError: Uf() };
}
var jf = () => {
  let e2 = { string: { unit: "文字", verb: "である" }, file: { unit: "バイト", verb: "である" }, array: { unit: "要素", verb: "である" }, set: { unit: "要素", verb: "である" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "入力値", email: "メールアドレス", url: "URL", emoji: "絵文字", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO日時", date: "ISO日付", time: "ISO時刻", duration: "ISO期間", ipv4: "IPv4アドレス", ipv6: "IPv6アドレス", cidrv4: "IPv4範囲", cidrv6: "IPv6範囲", base64: "base64エンコード文字列", base64url: "base64urlエンコード文字列", json_string: "JSON文字列", e164: "E.164番号", jwt: "JWT", template_literal: "入力値" }, a2 = { nan: "NaN", number: "数値", array: "配列" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `無効な入力: instanceof ${t2.expected}が期待されましたが、${u2}が入力されました` : `無効な入力: ${r2}が期待されましたが、${u2}が入力されました`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `無効な入力: ${b(t2.values[0])}が期待されました` : `無効な選択: ${v(t2.values, "、")}のいずれかである必要があります`;
      case "too_big": {
        let r2 = t2.inclusive ? "以下である" : "より小さい", o2 = i2(t2.origin);
        return o2 ? `大きすぎる値: ${t2.origin ?? "値"}は${t2.maximum.toString()}${o2.unit ?? "要素"}${r2}必要があります` : `大きすぎる値: ${t2.origin ?? "値"}は${t2.maximum.toString()}${r2}必要があります`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? "以上である" : "より大きい", o2 = i2(t2.origin);
        return o2 ? `小さすぎる値: ${t2.origin}は${t2.minimum.toString()}${o2.unit}${r2}必要があります` : `小さすぎる値: ${t2.origin}は${t2.minimum.toString()}${r2}必要があります`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `無効な文字列: "${r2.prefix}"で始まる必要があります` : r2.format === "ends_with" ? `無効な文字列: "${r2.suffix}"で終わる必要があります` : r2.format === "includes" ? `無効な文字列: "${r2.includes}"を含む必要があります` : r2.format === "regex" ? `無効な文字列: パターン${r2.pattern}に一致する必要があります` : `無効な${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `無効な数値: ${t2.divisor}の倍数である必要があります`;
      case "unrecognized_keys":
        return `認識されていないキー${t2.keys.length > 1 ? "群" : ""}: ${v(t2.keys, "、")}`;
      case "invalid_key":
        return `${t2.origin}内の無効なキー`;
      case "invalid_union":
        return "無効な入力";
      case "invalid_element":
        return `${t2.origin}内の無効な値`;
      default:
        return "無効な入力";
    }
  };
};
function Zf() {
  return { localeError: jf() };
}
var Nf = () => {
  let e2 = { string: { unit: "სიმბოლო", verb: "უნდა შეიცავდეს" }, file: { unit: "ბაიტი", verb: "უნდა შეიცავდეს" }, array: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" }, set: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "შეყვანა", email: "ელ-ფოსტის მისამართი", url: "URL", emoji: "ემოჯი", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "თარიღი-დრო", date: "თარიღი", time: "დრო", duration: "ხანგრძლივობა", ipv4: "IPv4 მისამართი", ipv6: "IPv6 მისამართი", cidrv4: "IPv4 დიაპაზონი", cidrv6: "IPv6 დიაპაზონი", base64: "base64-კოდირებული სტრინგი", base64url: "base64url-კოდირებული სტრინგი", json_string: "JSON სტრინგი", e164: "E.164 ნომერი", jwt: "JWT", template_literal: "შეყვანა" }, a2 = { nan: "NaN", number: "რიცხვი", string: "სტრინგი", boolean: "ბულეანი", function: "ფუნქცია", array: "მასივი" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `არასწორი შეყვანა: მოსალოდნელი instanceof ${t2.expected}, მიღებული ${u2}` : `არასწორი შეყვანა: მოსალოდნელი ${r2}, მიღებული ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `არასწორი შეყვანა: მოსალოდნელი ${b(t2.values[0])}` : `არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${v(t2.values, "|")}-დან`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `ზედმეტად დიდი: მოსალოდნელი ${t2.origin ?? "მნიშვნელობა"} ${o2.verb} ${r2}${t2.maximum.toString()} ${o2.unit}` : `ზედმეტად დიდი: მოსალოდნელი ${t2.origin ?? "მნიშვნელობა"} იყოს ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `ზედმეტად პატარა: მოსალოდნელი ${t2.origin} ${o2.verb} ${r2}${t2.minimum.toString()} ${o2.unit}` : `ზედმეტად პატარა: მოსალოდნელი ${t2.origin} იყოს ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `არასწორი სტრინგი: უნდა იწყებოდეს "${r2.prefix}"-ით` : r2.format === "ends_with" ? `არასწორი სტრინგი: უნდა მთავრდებოდეს "${r2.suffix}"-ით` : r2.format === "includes" ? `არასწორი სტრინგი: უნდა შეიცავდეს "${r2.includes}"-ს` : r2.format === "regex" ? `არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${r2.pattern}` : `არასწორი ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `არასწორი რიცხვი: უნდა იყოს ${t2.divisor}-ის ჯერადი`;
      case "unrecognized_keys":
        return `უცნობი გასაღებ${t2.keys.length > 1 ? "ები" : "ი"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `არასწორი გასაღები ${t2.origin}-ში`;
      case "invalid_union":
        return "არასწორი შეყვანა";
      case "invalid_element":
        return `არასწორი მნიშვნელობა ${t2.origin}-ში`;
      default:
        return "არასწორი შეყვანა";
    }
  };
};
function Pf() {
  return { localeError: Nf() };
}
var Df = () => {
  let e2 = { string: { unit: "តួអក្សរ", verb: "គួរមាន" }, file: { unit: "បៃ", verb: "គួរមាន" }, array: { unit: "ធាតុ", verb: "គួរមាន" }, set: { unit: "ធាតុ", verb: "គួរមាន" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "ទិន្នន័យបញ្ចូល", email: "អាសយដ្ឋានអ៊ីមែល", url: "URL", emoji: "សញ្ញាអារម្មណ៍", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "កាលបរិច្ឆេទ និងម៉ោង ISO", date: "កាលបរិច្ឆេទ ISO", time: "ម៉ោង ISO", duration: "រយៈពេល ISO", ipv4: "អាសយដ្ឋាន IPv4", ipv6: "អាសយដ្ឋាន IPv6", cidrv4: "ដែនអាសយដ្ឋាន IPv4", cidrv6: "ដែនអាសយដ្ឋាន IPv6", base64: "ខ្សែអក្សរអ៊ិកូដ base64", base64url: "ខ្សែអក្សរអ៊ិកូដ base64url", json_string: "ខ្សែអក្សរ JSON", e164: "លេខ E.164", jwt: "JWT", template_literal: "ទិន្នន័យបញ្ចូល" }, a2 = { nan: "NaN", number: "លេខ", array: "អារេ (Array)", null: "គ្មានតម្លៃ (null)" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${t2.expected} ប៉ុន្តែទទួលបាន ${u2}` : `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${r2} ប៉ុន្តែទទួលបាន ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${b(t2.values[0])}` : `ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `ធំពេក៖ ត្រូវការ ${t2.origin ?? "តម្លៃ"} ${r2} ${t2.maximum.toString()} ${o2.unit ?? "ធាតុ"}` : `ធំពេក៖ ត្រូវការ ${t2.origin ?? "តម្លៃ"} ${r2} ${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `តូចពេក៖ ត្រូវការ ${t2.origin} ${r2} ${t2.minimum.toString()} ${o2.unit}` : `តូចពេក៖ ត្រូវការ ${t2.origin} ${r2} ${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${r2.prefix}"` : r2.format === "ends_with" ? `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${r2.suffix}"` : r2.format === "includes" ? `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${r2.includes}"` : r2.format === "regex" ? `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${r2.pattern}` : `មិនត្រឹមត្រូវ៖ ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${t2.divisor}`;
      case "unrecognized_keys":
        return `រកឃើញសោមិនស្គាល់៖ ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `សោមិនត្រឹមត្រូវនៅក្នុង ${t2.origin}`;
      case "invalid_union":
        return "ទិន្នន័យមិនត្រឹមត្រូវ";
      case "invalid_element":
        return `ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${t2.origin}`;
      default:
        return "ទិន្នន័យមិនត្រឹមត្រូវ";
    }
  };
};
function Gu() {
  return { localeError: Df() };
}
function Ef() {
  return Gu();
}
var Tf = () => {
  let e2 = { string: { unit: "문자", verb: "to have" }, file: { unit: "바이트", verb: "to have" }, array: { unit: "개", verb: "to have" }, set: { unit: "개", verb: "to have" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "입력", email: "이메일 주소", url: "URL", emoji: "이모지", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO 날짜시간", date: "ISO 날짜", time: "ISO 시간", duration: "ISO 기간", ipv4: "IPv4 주소", ipv6: "IPv6 주소", cidrv4: "IPv4 범위", cidrv6: "IPv6 범위", base64: "base64 인코딩 문자열", base64url: "base64url 인코딩 문자열", json_string: "JSON 문자열", e164: "E.164 번호", jwt: "JWT", template_literal: "입력" }, a2 = { nan: "NaN" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `잘못된 입력: 예상 타입은 instanceof ${t2.expected}, 받은 타입은 ${u2}입니다` : `잘못된 입력: 예상 타입은 ${r2}, 받은 타입은 ${u2}입니다`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `잘못된 입력: 값은 ${b(t2.values[0])} 이어야 합니다` : `잘못된 옵션: ${v(t2.values, "또는 ")} 중 하나여야 합니다`;
      case "too_big": {
        let r2 = t2.inclusive ? "이하" : "미만", o2 = r2 === "미만" ? "이어야 합니다" : "여야 합니다", u2 = i2(t2.origin), d = (u2 == null ? void 0 : u2.unit) ?? "요소";
        return u2 ? `${t2.origin ?? "값"}이 너무 큽니다: ${t2.maximum.toString()}${d} ${r2}${o2}` : `${t2.origin ?? "값"}이 너무 큽니다: ${t2.maximum.toString()} ${r2}${o2}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? "이상" : "초과", o2 = r2 === "이상" ? "이어야 합니다" : "여야 합니다", u2 = i2(t2.origin), d = (u2 == null ? void 0 : u2.unit) ?? "요소";
        return u2 ? `${t2.origin ?? "값"}이 너무 작습니다: ${t2.minimum.toString()}${d} ${r2}${o2}` : `${t2.origin ?? "값"}이 너무 작습니다: ${t2.minimum.toString()} ${r2}${o2}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `잘못된 문자열: "${r2.prefix}"(으)로 시작해야 합니다` : r2.format === "ends_with" ? `잘못된 문자열: "${r2.suffix}"(으)로 끝나야 합니다` : r2.format === "includes" ? `잘못된 문자열: "${r2.includes}"을(를) 포함해야 합니다` : r2.format === "regex" ? `잘못된 문자열: 정규식 ${r2.pattern} 패턴과 일치해야 합니다` : `잘못된 ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `잘못된 숫자: ${t2.divisor}의 배수여야 합니다`;
      case "unrecognized_keys":
        return `인식할 수 없는 키: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `잘못된 키: ${t2.origin}`;
      case "invalid_union":
        return "잘못된 입력";
      case "invalid_element":
        return `잘못된 값: ${t2.origin}`;
      default:
        return "잘못된 입력";
    }
  };
};
function Af() {
  return { localeError: Tf() };
}
var Ve = (e2) => e2.charAt(0).toUpperCase() + e2.slice(1);
function ra(e2) {
  let i2 = Math.abs(e2), n = i2 % 10, a2 = i2 % 100;
  return a2 >= 11 && a2 <= 19 || n === 0 ? "many" : n === 1 ? "one" : "few";
}
var Rf = () => {
  let e2 = { string: { unit: { one: "simbolis", few: "simboliai", many: "simbolių" }, verb: { smaller: { inclusive: "turi būti ne ilgesnė kaip", notInclusive: "turi būti trumpesnė kaip" }, bigger: { inclusive: "turi būti ne trumpesnė kaip", notInclusive: "turi būti ilgesnė kaip" } } }, file: { unit: { one: "baitas", few: "baitai", many: "baitų" }, verb: { smaller: { inclusive: "turi būti ne didesnis kaip", notInclusive: "turi būti mažesnis kaip" }, bigger: { inclusive: "turi būti ne mažesnis kaip", notInclusive: "turi būti didesnis kaip" } } }, array: { unit: { one: "elementą", few: "elementus", many: "elementų" }, verb: { smaller: { inclusive: "turi turėti ne daugiau kaip", notInclusive: "turi turėti mažiau kaip" }, bigger: { inclusive: "turi turėti ne mažiau kaip", notInclusive: "turi turėti daugiau kaip" } } }, set: { unit: { one: "elementą", few: "elementus", many: "elementų" }, verb: { smaller: { inclusive: "turi turėti ne daugiau kaip", notInclusive: "turi turėti mažiau kaip" }, bigger: { inclusive: "turi turėti ne mažiau kaip", notInclusive: "turi turėti daugiau kaip" } } } };
  function i2(t2, r2, o2, u2) {
    let d = e2[t2] ?? null;
    return d === null ? d : { unit: d.unit[r2], verb: d.verb[u2][o2 ? "inclusive" : "notInclusive"] };
  }
  let n = { regex: "įvestis", email: "el. pašto adresas", url: "URL", emoji: "jaustukas", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO data ir laikas", date: "ISO data", time: "ISO laikas", duration: "ISO trukmė", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 užkoduota eilutė", base64url: "base64url užkoduota eilutė", json_string: "JSON eilutė", e164: "E.164 numeris", jwt: "JWT", template_literal: "įvestis" }, a2 = { nan: "NaN", number: "skaičius", bigint: "sveikasis skaičius", string: "eilutė", boolean: "loginė reikšmė", undefined: "neapibrėžta reikšmė", function: "funkcija", symbol: "simbolis", array: "masyvas", object: "objektas", null: "nulinė reikšmė" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Gautas tipas ${u2}, o tikėtasi - instanceof ${t2.expected}` : `Gautas tipas ${u2}, o tikėtasi - ${r2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Privalo būti ${b(t2.values[0])}` : `Privalo būti vienas iš ${v(t2.values, "|")} pasirinkimų`;
      case "too_big": {
        let r2 = a2[t2.origin] ?? t2.origin, o2 = i2(t2.origin, ra(Number(t2.maximum)), t2.inclusive ?? false, "smaller");
        if (o2 != null && o2.verb) return `${Ve(r2 ?? t2.origin ?? "reikšmė")} ${o2.verb} ${t2.maximum.toString()} ${o2.unit ?? "elementų"}`;
        let u2 = t2.inclusive ? "ne didesnis kaip" : "mažesnis kaip";
        return `${Ve(r2 ?? t2.origin ?? "reikšmė")} turi būti ${u2} ${t2.maximum.toString()} ${o2 == null ? void 0 : o2.unit}`;
      }
      case "too_small": {
        let r2 = a2[t2.origin] ?? t2.origin, o2 = i2(t2.origin, ra(Number(t2.minimum)), t2.inclusive ?? false, "bigger");
        if (o2 != null && o2.verb) return `${Ve(r2 ?? t2.origin ?? "reikšmė")} ${o2.verb} ${t2.minimum.toString()} ${o2.unit ?? "elementų"}`;
        let u2 = t2.inclusive ? "ne mažesnis kaip" : "didesnis kaip";
        return `${Ve(r2 ?? t2.origin ?? "reikšmė")} turi būti ${u2} ${t2.minimum.toString()} ${o2 == null ? void 0 : o2.unit}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Eilutė privalo prasidėti "${r2.prefix}"` : r2.format === "ends_with" ? `Eilutė privalo pasibaigti "${r2.suffix}"` : r2.format === "includes" ? `Eilutė privalo įtraukti "${r2.includes}"` : r2.format === "regex" ? `Eilutė privalo atitikti ${r2.pattern}` : `Neteisingas ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Skaičius privalo būti ${t2.divisor} kartotinis.`;
      case "unrecognized_keys":
        return `Neatpažint${t2.keys.length > 1 ? "i" : "as"} rakt${t2.keys.length > 1 ? "ai" : "as"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return "Rastas klaidingas raktas";
      case "invalid_union":
        return "Klaidinga įvestis";
      case "invalid_element": {
        let r2 = a2[t2.origin] ?? t2.origin;
        return `${Ve(r2 ?? t2.origin ?? "reikšmė")} turi klaidingą įvestį`;
      }
      default:
        return "Klaidinga įvestis";
    }
  };
};
function Cf() {
  return { localeError: Rf() };
}
var Lf = () => {
  let e2 = { string: { unit: "знаци", verb: "да имаат" }, file: { unit: "бајти", verb: "да имаат" }, array: { unit: "ставки", verb: "да имаат" }, set: { unit: "ставки", verb: "да имаат" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "внес", email: "адреса на е-пошта", url: "URL", emoji: "емоџи", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO датум и време", date: "ISO датум", time: "ISO време", duration: "ISO времетраење", ipv4: "IPv4 адреса", ipv6: "IPv6 адреса", cidrv4: "IPv4 опсег", cidrv6: "IPv6 опсег", base64: "base64-енкодирана низа", base64url: "base64url-енкодирана низа", json_string: "JSON низа", e164: "E.164 број", jwt: "JWT", template_literal: "внес" }, a2 = { nan: "NaN", number: "број", array: "низа" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Грешен внес: се очекува instanceof ${t2.expected}, примено ${u2}` : `Грешен внес: се очекува ${r2}, примено ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Invalid input: expected ${b(t2.values[0])}` : `Грешана опција: се очекува една ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Премногу голем: се очекува ${t2.origin ?? "вредноста"} да има ${r2}${t2.maximum.toString()} ${o2.unit ?? "елементи"}` : `Премногу голем: се очекува ${t2.origin ?? "вредноста"} да биде ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Премногу мал: се очекува ${t2.origin} да има ${r2}${t2.minimum.toString()} ${o2.unit}` : `Премногу мал: се очекува ${t2.origin} да биде ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Неважечка низа: мора да започнува со "${r2.prefix}"` : r2.format === "ends_with" ? `Неважечка низа: мора да завршува со "${r2.suffix}"` : r2.format === "includes" ? `Неважечка низа: мора да вклучува "${r2.includes}"` : r2.format === "regex" ? `Неважечка низа: мора да одгоара на патернот ${r2.pattern}` : `Invalid ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Грешен број: мора да биде делив со ${t2.divisor}`;
      case "unrecognized_keys":
        return `${t2.keys.length > 1 ? "Непрепознаени клучеви" : "Непрепознаен клуч"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Грешен клуч во ${t2.origin}`;
      case "invalid_union":
        return "Грешен внес";
      case "invalid_element":
        return `Грешна вредност во ${t2.origin}`;
      default:
        return "Грешен внес";
    }
  };
};
function Jf() {
  return { localeError: Lf() };
}
var Mf = () => {
  let e2 = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, set: { unit: "elemen", verb: "mempunyai" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "input", email: "alamat e-mel", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "tarikh masa ISO", date: "tarikh ISO", time: "masa ISO", duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", jwt: "JWT", template_literal: "input" }, a2 = { nan: "NaN", number: "nombor" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Input tidak sah: dijangka instanceof ${t2.expected}, diterima ${u2}` : `Input tidak sah: dijangka ${r2}, diterima ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Input tidak sah: dijangka ${b(t2.values[0])}` : `Pilihan tidak sah: dijangka salah satu daripada ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Terlalu besar: dijangka ${t2.origin ?? "nilai"} ${o2.verb} ${r2}${t2.maximum.toString()} ${o2.unit ?? "elemen"}` : `Terlalu besar: dijangka ${t2.origin ?? "nilai"} adalah ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Terlalu kecil: dijangka ${t2.origin} ${o2.verb} ${r2}${t2.minimum.toString()} ${o2.unit}` : `Terlalu kecil: dijangka ${t2.origin} adalah ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `String tidak sah: mesti bermula dengan "${r2.prefix}"` : r2.format === "ends_with" ? `String tidak sah: mesti berakhir dengan "${r2.suffix}"` : r2.format === "includes" ? `String tidak sah: mesti mengandungi "${r2.includes}"` : r2.format === "regex" ? `String tidak sah: mesti sepadan dengan corak ${r2.pattern}` : `${n[r2.format] ?? t2.format} tidak sah`;
      }
      case "not_multiple_of":
        return `Nombor tidak sah: perlu gandaan ${t2.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak sah dalam ${t2.origin}`;
      case "invalid_union":
        return "Input tidak sah";
      case "invalid_element":
        return `Nilai tidak sah dalam ${t2.origin}`;
      default:
        return "Input tidak sah";
    }
  };
};
function Ff() {
  return { localeError: Mf() };
}
var qf = () => {
  let e2 = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, set: { unit: "elementen", verb: "heeft" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "invoer", email: "emailadres", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum en tijd", date: "ISO datum", time: "ISO tijd", duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", jwt: "JWT", template_literal: "invoer" }, a2 = { nan: "NaN", number: "getal" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Ongeldige invoer: verwacht instanceof ${t2.expected}, ontving ${u2}` : `Ongeldige invoer: verwacht ${r2}, ontving ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Ongeldige invoer: verwacht ${b(t2.values[0])}` : `Ongeldige optie: verwacht één van ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin), u2 = t2.origin === "date" ? "laat" : t2.origin === "string" ? "lang" : "groot";
        return o2 ? `Te ${u2}: verwacht dat ${t2.origin ?? "waarde"} ${r2}${t2.maximum.toString()} ${o2.unit ?? "elementen"} ${o2.verb}` : `Te ${u2}: verwacht dat ${t2.origin ?? "waarde"} ${r2}${t2.maximum.toString()} is`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin), u2 = t2.origin === "date" ? "vroeg" : t2.origin === "string" ? "kort" : "klein";
        return o2 ? `Te ${u2}: verwacht dat ${t2.origin} ${r2}${t2.minimum.toString()} ${o2.unit} ${o2.verb}` : `Te ${u2}: verwacht dat ${t2.origin} ${r2}${t2.minimum.toString()} is`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Ongeldige tekst: moet met "${r2.prefix}" beginnen` : r2.format === "ends_with" ? `Ongeldige tekst: moet op "${r2.suffix}" eindigen` : r2.format === "includes" ? `Ongeldige tekst: moet "${r2.includes}" bevatten` : r2.format === "regex" ? `Ongeldige tekst: moet overeenkomen met patroon ${r2.pattern}` : `Ongeldig: ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Ongeldig getal: moet een veelvoud van ${t2.divisor} zijn`;
      case "unrecognized_keys":
        return `Onbekende key${t2.keys.length > 1 ? "s" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Ongeldige key in ${t2.origin}`;
      case "invalid_union":
        return "Ongeldige invoer";
      case "invalid_element":
        return `Ongeldige waarde in ${t2.origin}`;
      default:
        return "Ongeldige invoer";
    }
  };
};
function Wf() {
  return { localeError: qf() };
}
var Vf = () => {
  let e2 = { string: { unit: "tegn", verb: "å ha" }, file: { unit: "bytes", verb: "å ha" }, array: { unit: "elementer", verb: "å inneholde" }, set: { unit: "elementer", verb: "å inneholde" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "input", email: "e-postadresse", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dato- og klokkeslett", date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", ipv4: "IPv4-område", ipv6: "IPv6-område", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" }, a2 = { nan: "NaN", number: "tall", array: "liste" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Ugyldig input: forventet instanceof ${t2.expected}, fikk ${u2}` : `Ugyldig input: forventet ${r2}, fikk ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Ugyldig verdi: forventet ${b(t2.values[0])}` : `Ugyldig valg: forventet en av ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `For stor(t): forventet ${t2.origin ?? "value"} til å ha ${r2}${t2.maximum.toString()} ${o2.unit ?? "elementer"}` : `For stor(t): forventet ${t2.origin ?? "value"} til å ha ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `For lite(n): forventet ${t2.origin} til å ha ${r2}${t2.minimum.toString()} ${o2.unit}` : `For lite(n): forventet ${t2.origin} til å ha ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Ugyldig streng: må starte med "${r2.prefix}"` : r2.format === "ends_with" ? `Ugyldig streng: må ende med "${r2.suffix}"` : r2.format === "includes" ? `Ugyldig streng: må inneholde "${r2.includes}"` : r2.format === "regex" ? `Ugyldig streng: må matche mønsteret ${r2.pattern}` : `Ugyldig ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Ugyldig tall: må være et multiplum av ${t2.divisor}`;
      case "unrecognized_keys":
        return `${t2.keys.length > 1 ? "Ukjente nøkler" : "Ukjent nøkkel"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig nøkkel i ${t2.origin}`;
      case "invalid_union":
        return "Ugyldig input";
      case "invalid_element":
        return `Ugyldig verdi i ${t2.origin}`;
      default:
        return "Ugyldig input";
    }
  };
};
function Gf() {
  return { localeError: Vf() };
}
var Kf = () => {
  let e2 = { string: { unit: "harf", verb: "olmalıdır" }, file: { unit: "bayt", verb: "olmalıdır" }, array: { unit: "unsur", verb: "olmalıdır" }, set: { unit: "unsur", verb: "olmalıdır" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "giren", email: "epostagâh", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO hengâmı", date: "ISO tarihi", time: "ISO zamanı", duration: "ISO müddeti", ipv4: "IPv4 nişânı", ipv6: "IPv6 nişânı", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-şifreli metin", base64url: "base64url-şifreli metin", json_string: "JSON metin", e164: "E.164 sayısı", jwt: "JWT", template_literal: "giren" }, a2 = { nan: "NaN", number: "numara", array: "saf", null: "gayb" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Fâsit giren: umulan instanceof ${t2.expected}, alınan ${u2}` : `Fâsit giren: umulan ${r2}, alınan ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Fâsit giren: umulan ${b(t2.values[0])}` : `Fâsit tercih: mûteberler ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Fazla büyük: ${t2.origin ?? "value"}, ${r2}${t2.maximum.toString()} ${o2.unit ?? "elements"} sahip olmalıydı.` : `Fazla büyük: ${t2.origin ?? "value"}, ${r2}${t2.maximum.toString()} olmalıydı.`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Fazla küçük: ${t2.origin}, ${r2}${t2.minimum.toString()} ${o2.unit} sahip olmalıydı.` : `Fazla küçük: ${t2.origin}, ${r2}${t2.minimum.toString()} olmalıydı.`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Fâsit metin: "${r2.prefix}" ile başlamalı.` : r2.format === "ends_with" ? `Fâsit metin: "${r2.suffix}" ile bitmeli.` : r2.format === "includes" ? `Fâsit metin: "${r2.includes}" ihtivâ etmeli.` : r2.format === "regex" ? `Fâsit metin: ${r2.pattern} nakşına uymalı.` : `Fâsit ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Fâsit sayı: ${t2.divisor} katı olmalıydı.`;
      case "unrecognized_keys":
        return `Tanınmayan anahtar ${t2.keys.length > 1 ? "s" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `${t2.origin} için tanınmayan anahtar var.`;
      case "invalid_union":
        return "Giren tanınamadı.";
      case "invalid_element":
        return `${t2.origin} için tanınmayan kıymet var.`;
      default:
        return "Kıymet tanınamadı.";
    }
  };
};
function Bf() {
  return { localeError: Kf() };
}
var Hf = () => {
  let e2 = { string: { unit: "توکي", verb: "ولري" }, file: { unit: "بایټس", verb: "ولري" }, array: { unit: "توکي", verb: "ولري" }, set: { unit: "توکي", verb: "ولري" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "ورودي", email: "بریښنالیک", url: "یو آر ال", emoji: "ایموجي", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "نیټه او وخت", date: "نېټه", time: "وخت", duration: "موده", ipv4: "د IPv4 پته", ipv6: "د IPv6 پته", cidrv4: "د IPv4 ساحه", cidrv6: "د IPv6 ساحه", base64: "base64-encoded متن", base64url: "base64url-encoded متن", json_string: "JSON متن", e164: "د E.164 شمېره", jwt: "JWT", template_literal: "ورودي" }, a2 = { nan: "NaN", number: "عدد", array: "ارې" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `ناسم ورودي: باید instanceof ${t2.expected} وای, مګر ${u2} ترلاسه شو` : `ناسم ورودي: باید ${r2} وای, مګر ${u2} ترلاسه شو`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `ناسم ورودي: باید ${b(t2.values[0])} وای` : `ناسم انتخاب: باید یو له ${v(t2.values, "|")} څخه وای`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `ډیر لوی: ${t2.origin ?? "ارزښت"} باید ${r2}${t2.maximum.toString()} ${o2.unit ?? "عنصرونه"} ولري` : `ډیر لوی: ${t2.origin ?? "ارزښت"} باید ${r2}${t2.maximum.toString()} وي`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `ډیر کوچنی: ${t2.origin} باید ${r2}${t2.minimum.toString()} ${o2.unit} ولري` : `ډیر کوچنی: ${t2.origin} باید ${r2}${t2.minimum.toString()} وي`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `ناسم متن: باید د "${r2.prefix}" سره پیل شي` : r2.format === "ends_with" ? `ناسم متن: باید د "${r2.suffix}" سره پای ته ورسيږي` : r2.format === "includes" ? `ناسم متن: باید "${r2.includes}" ولري` : r2.format === "regex" ? `ناسم متن: باید د ${r2.pattern} سره مطابقت ولري` : `${n[r2.format] ?? t2.format} ناسم دی`;
      }
      case "not_multiple_of":
        return `ناسم عدد: باید د ${t2.divisor} مضرب وي`;
      case "unrecognized_keys":
        return `ناسم ${t2.keys.length > 1 ? "کلیډونه" : "کلیډ"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `ناسم کلیډ په ${t2.origin} کې`;
      case "invalid_union":
        return "ناسمه ورودي";
      case "invalid_element":
        return `ناسم عنصر په ${t2.origin} کې`;
      default:
        return "ناسمه ورودي";
    }
  };
};
function Xf() {
  return { localeError: Hf() };
}
var Yf = () => {
  let e2 = { string: { unit: "znaków", verb: "mieć" }, file: { unit: "bajtów", verb: "mieć" }, array: { unit: "elementów", verb: "mieć" }, set: { unit: "elementów", verb: "mieć" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "wyrażenie", email: "adres email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data i godzina w formacie ISO", date: "data w formacie ISO", time: "godzina w formacie ISO", duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ciąg znaków zakodowany w formacie base64", base64url: "ciąg znaków zakodowany w formacie base64url", json_string: "ciąg znaków w formacie JSON", e164: "liczba E.164", jwt: "JWT", template_literal: "wejście" }, a2 = { nan: "NaN", number: "liczba", array: "tablica" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Nieprawidłowe dane wejściowe: oczekiwano instanceof ${t2.expected}, otrzymano ${u2}` : `Nieprawidłowe dane wejściowe: oczekiwano ${r2}, otrzymano ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Nieprawidłowe dane wejściowe: oczekiwano ${b(t2.values[0])}` : `Nieprawidłowa opcja: oczekiwano jednej z wartości ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Za duża wartość: oczekiwano, że ${t2.origin ?? "wartość"} będzie mieć ${r2}${t2.maximum.toString()} ${o2.unit ?? "elementów"}` : `Zbyt duż(y/a/e): oczekiwano, że ${t2.origin ?? "wartość"} będzie wynosić ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Za mała wartość: oczekiwano, że ${t2.origin ?? "wartość"} będzie mieć ${r2}${t2.minimum.toString()} ${o2.unit ?? "elementów"}` : `Zbyt mał(y/a/e): oczekiwano, że ${t2.origin ?? "wartość"} będzie wynosić ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Nieprawidłowy ciąg znaków: musi zaczynać się od "${r2.prefix}"` : r2.format === "ends_with" ? `Nieprawidłowy ciąg znaków: musi kończyć się na "${r2.suffix}"` : r2.format === "includes" ? `Nieprawidłowy ciąg znaków: musi zawierać "${r2.includes}"` : r2.format === "regex" ? `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${r2.pattern}` : `Nieprawidłow(y/a/e) ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Nieprawidłowa liczba: musi być wielokrotnością ${t2.divisor}`;
      case "unrecognized_keys":
        return `Nierozpoznane klucze${t2.keys.length > 1 ? "s" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Nieprawidłowy klucz w ${t2.origin}`;
      case "invalid_union":
        return "Nieprawidłowe dane wejściowe";
      case "invalid_element":
        return `Nieprawidłowa wartość w ${t2.origin}`;
      default:
        return "Nieprawidłowe dane wejściowe";
    }
  };
};
function Qf() {
  return { localeError: Yf() };
}
var ep = () => {
  let e2 = { string: { unit: "caracteres", verb: "ter" }, file: { unit: "bytes", verb: "ter" }, array: { unit: "itens", verb: "ter" }, set: { unit: "itens", verb: "ter" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "padrão", email: "endereço de e-mail", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data e hora ISO", date: "data ISO", time: "hora ISO", duration: "duração ISO", ipv4: "endereço IPv4", ipv6: "endereço IPv6", cidrv4: "faixa de IPv4", cidrv6: "faixa de IPv6", base64: "texto codificado em base64", base64url: "URL codificada em base64", json_string: "texto JSON", e164: "número E.164", jwt: "JWT", template_literal: "entrada" }, a2 = { nan: "NaN", number: "número", null: "nulo" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Tipo inválido: esperado instanceof ${t2.expected}, recebido ${u2}` : `Tipo inválido: esperado ${r2}, recebido ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Entrada inválida: esperado ${b(t2.values[0])}` : `Opção inválida: esperada uma das ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Muito grande: esperado que ${t2.origin ?? "valor"} tivesse ${r2}${t2.maximum.toString()} ${o2.unit ?? "elementos"}` : `Muito grande: esperado que ${t2.origin ?? "valor"} fosse ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Muito pequeno: esperado que ${t2.origin} tivesse ${r2}${t2.minimum.toString()} ${o2.unit}` : `Muito pequeno: esperado que ${t2.origin} fosse ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Texto inválido: deve começar com "${r2.prefix}"` : r2.format === "ends_with" ? `Texto inválido: deve terminar com "${r2.suffix}"` : r2.format === "includes" ? `Texto inválido: deve incluir "${r2.includes}"` : r2.format === "regex" ? `Texto inválido: deve corresponder ao padrão ${r2.pattern}` : `${n[r2.format] ?? t2.format} inválido`;
      }
      case "not_multiple_of":
        return `Número inválido: deve ser múltiplo de ${t2.divisor}`;
      case "unrecognized_keys":
        return `Chave${t2.keys.length > 1 ? "s" : ""} desconhecida${t2.keys.length > 1 ? "s" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Chave inválida em ${t2.origin}`;
      case "invalid_union":
        return "Entrada inválida";
      case "invalid_element":
        return `Valor inválido em ${t2.origin}`;
      default:
        return "Campo inválido";
    }
  };
};
function tp() {
  return { localeError: ep() };
}
function aa(e2, i2, n, a2) {
  let t2 = Math.abs(e2), r2 = t2 % 10, o2 = t2 % 100;
  return o2 >= 11 && o2 <= 19 ? a2 : r2 === 1 ? i2 : r2 >= 2 && r2 <= 4 ? n : a2;
}
var ip = () => {
  let e2 = { string: { unit: { one: "символ", few: "символа", many: "символов" }, verb: "иметь" }, file: { unit: { one: "байт", few: "байта", many: "байт" }, verb: "иметь" }, array: { unit: { one: "элемент", few: "элемента", many: "элементов" }, verb: "иметь" }, set: { unit: { one: "элемент", few: "элемента", many: "элементов" }, verb: "иметь" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "ввод", email: "email адрес", url: "URL", emoji: "эмодзи", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO дата и время", date: "ISO дата", time: "ISO время", duration: "ISO длительность", ipv4: "IPv4 адрес", ipv6: "IPv6 адрес", cidrv4: "IPv4 диапазон", cidrv6: "IPv6 диапазон", base64: "строка в формате base64", base64url: "строка в формате base64url", json_string: "JSON строка", e164: "номер E.164", jwt: "JWT", template_literal: "ввод" }, a2 = { nan: "NaN", number: "число", array: "массив" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Неверный ввод: ожидалось instanceof ${t2.expected}, получено ${u2}` : `Неверный ввод: ожидалось ${r2}, получено ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Неверный ввод: ожидалось ${b(t2.values[0])}` : `Неверный вариант: ожидалось одно из ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        if (o2) {
          let u2 = Number(t2.maximum), d = aa(u2, o2.unit.one, o2.unit.few, o2.unit.many);
          return `Слишком большое значение: ожидалось, что ${t2.origin ?? "значение"} будет иметь ${r2}${t2.maximum.toString()} ${d}`;
        }
        return `Слишком большое значение: ожидалось, что ${t2.origin ?? "значение"} будет ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        if (o2) {
          let u2 = Number(t2.minimum), d = aa(u2, o2.unit.one, o2.unit.few, o2.unit.many);
          return `Слишком маленькое значение: ожидалось, что ${t2.origin} будет иметь ${r2}${t2.minimum.toString()} ${d}`;
        }
        return `Слишком маленькое значение: ожидалось, что ${t2.origin} будет ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Неверная строка: должна начинаться с "${r2.prefix}"` : r2.format === "ends_with" ? `Неверная строка: должна заканчиваться на "${r2.suffix}"` : r2.format === "includes" ? `Неверная строка: должна содержать "${r2.includes}"` : r2.format === "regex" ? `Неверная строка: должна соответствовать шаблону ${r2.pattern}` : `Неверный ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Неверное число: должно быть кратным ${t2.divisor}`;
      case "unrecognized_keys":
        return `Нераспознанн${t2.keys.length > 1 ? "ые" : "ый"} ключ${t2.keys.length > 1 ? "и" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Неверный ключ в ${t2.origin}`;
      case "invalid_union":
        return "Неверные входные данные";
      case "invalid_element":
        return `Неверное значение в ${t2.origin}`;
      default:
        return "Неверные входные данные";
    }
  };
};
function np() {
  return { localeError: ip() };
}
var rp = () => {
  let e2 = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, set: { unit: "elementov", verb: "imeti" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "vnos", email: "e-poštni naslov", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum in čas", date: "ISO datum", time: "ISO čas", duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 številka", jwt: "JWT", template_literal: "vnos" }, a2 = { nan: "NaN", number: "število", array: "tabela" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Neveljaven vnos: pričakovano instanceof ${t2.expected}, prejeto ${u2}` : `Neveljaven vnos: pričakovano ${r2}, prejeto ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Neveljaven vnos: pričakovano ${b(t2.values[0])}` : `Neveljavna možnost: pričakovano eno izmed ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Preveliko: pričakovano, da bo ${t2.origin ?? "vrednost"} imelo ${r2}${t2.maximum.toString()} ${o2.unit ?? "elementov"}` : `Preveliko: pričakovano, da bo ${t2.origin ?? "vrednost"} ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Premajhno: pričakovano, da bo ${t2.origin} imelo ${r2}${t2.minimum.toString()} ${o2.unit}` : `Premajhno: pričakovano, da bo ${t2.origin} ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Neveljaven niz: mora se začeti z "${r2.prefix}"` : r2.format === "ends_with" ? `Neveljaven niz: mora se končati z "${r2.suffix}"` : r2.format === "includes" ? `Neveljaven niz: mora vsebovati "${r2.includes}"` : r2.format === "regex" ? `Neveljaven niz: mora ustrezati vzorcu ${r2.pattern}` : `Neveljaven ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Neveljavno število: mora biti večkratnik ${t2.divisor}`;
      case "unrecognized_keys":
        return `Neprepoznan${t2.keys.length > 1 ? "i ključi" : " ključ"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Neveljaven ključ v ${t2.origin}`;
      case "invalid_union":
        return "Neveljaven vnos";
      case "invalid_element":
        return `Neveljavna vrednost v ${t2.origin}`;
      default:
        return "Neveljaven vnos";
    }
  };
};
function ap() {
  return { localeError: rp() };
}
var op = () => {
  let e2 = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att innehålla" }, set: { unit: "objekt", verb: "att innehålla" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "reguljärt uttryck", email: "e-postadress", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datum och tid", date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", ipv4: "IPv4-intervall", ipv6: "IPv6-intervall", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad sträng", base64url: "base64url-kodad sträng", json_string: "JSON-sträng", e164: "E.164-nummer", jwt: "JWT", template_literal: "mall-literal" }, a2 = { nan: "NaN", number: "antal", array: "lista" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Ogiltig inmatning: förväntat instanceof ${t2.expected}, fick ${u2}` : `Ogiltig inmatning: förväntat ${r2}, fick ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Ogiltig inmatning: förväntat ${b(t2.values[0])}` : `Ogiltigt val: förväntade en av ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `För stor(t): förväntade ${t2.origin ?? "värdet"} att ha ${r2}${t2.maximum.toString()} ${o2.unit ?? "element"}` : `För stor(t): förväntat ${t2.origin ?? "värdet"} att ha ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `För lite(t): förväntade ${t2.origin ?? "värdet"} att ha ${r2}${t2.minimum.toString()} ${o2.unit}` : `För lite(t): förväntade ${t2.origin ?? "värdet"} att ha ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Ogiltig sträng: måste börja med "${r2.prefix}"` : r2.format === "ends_with" ? `Ogiltig sträng: måste sluta med "${r2.suffix}"` : r2.format === "includes" ? `Ogiltig sträng: måste innehålla "${r2.includes}"` : r2.format === "regex" ? `Ogiltig sträng: måste matcha mönstret "${r2.pattern}"` : `Ogiltig(t) ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Ogiltigt tal: måste vara en multipel av ${t2.divisor}`;
      case "unrecognized_keys":
        return `${t2.keys.length > 1 ? "Okända nycklar" : "Okänd nyckel"}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Ogiltig nyckel i ${t2.origin ?? "värdet"}`;
      case "invalid_union":
        return "Ogiltig input";
      case "invalid_element":
        return `Ogiltigt värde i ${t2.origin ?? "värdet"}`;
      default:
        return "Ogiltig input";
    }
  };
};
function up() {
  return { localeError: op() };
}
var sp = () => {
  let e2 = { string: { unit: "எழுத்துக்கள்", verb: "கொண்டிருக்க வேண்டும்" }, file: { unit: "பைட்டுகள்", verb: "கொண்டிருக்க வேண்டும்" }, array: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, set: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "உள்ளீடு", email: "மின்னஞ்சல் முகவரி", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO தேதி நேரம்", date: "ISO தேதி", time: "ISO நேரம்", duration: "ISO கால அளவு", ipv4: "IPv4 முகவரி", ipv6: "IPv6 முகவரி", cidrv4: "IPv4 வரம்பு", cidrv6: "IPv6 வரம்பு", base64: "base64-encoded சரம்", base64url: "base64url-encoded சரம்", json_string: "JSON சரம்", e164: "E.164 எண்", jwt: "JWT", template_literal: "input" }, a2 = { nan: "NaN", number: "எண்", array: "அணி", null: "வெறுமை" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${t2.expected}, பெறப்பட்டது ${u2}` : `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${r2}, பெறப்பட்டது ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${b(t2.values[0])}` : `தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${v(t2.values, "|")} இல் ஒன்று`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${t2.origin ?? "மதிப்பு"} ${r2}${t2.maximum.toString()} ${o2.unit ?? "உறுப்புகள்"} ஆக இருக்க வேண்டும்` : `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${t2.origin ?? "மதிப்பு"} ${r2}${t2.maximum.toString()} ஆக இருக்க வேண்டும்`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${t2.origin} ${r2}${t2.minimum.toString()} ${o2.unit} ஆக இருக்க வேண்டும்` : `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${t2.origin} ${r2}${t2.minimum.toString()} ஆக இருக்க வேண்டும்`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `தவறான சரம்: "${r2.prefix}" இல் தொடங்க வேண்டும்` : r2.format === "ends_with" ? `தவறான சரம்: "${r2.suffix}" இல் முடிவடைய வேண்டும்` : r2.format === "includes" ? `தவறான சரம்: "${r2.includes}" ஐ உள்ளடக்க வேண்டும்` : r2.format === "regex" ? `தவறான சரம்: ${r2.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்` : `தவறான ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `தவறான எண்: ${t2.divisor} இன் பலமாக இருக்க வேண்டும்`;
      case "unrecognized_keys":
        return `அடையாளம் தெரியாத விசை${t2.keys.length > 1 ? "கள்" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `${t2.origin} இல் தவறான விசை`;
      case "invalid_union":
        return "தவறான உள்ளீடு";
      case "invalid_element":
        return `${t2.origin} இல் தவறான மதிப்பு`;
      default:
        return "தவறான உள்ளீடு";
    }
  };
};
function lp() {
  return { localeError: sp() };
}
var dp = () => {
  let e2 = { string: { unit: "ตัวอักษร", verb: "ควรมี" }, file: { unit: "ไบต์", verb: "ควรมี" }, array: { unit: "รายการ", verb: "ควรมี" }, set: { unit: "รายการ", verb: "ควรมี" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "ข้อมูลที่ป้อน", email: "ที่อยู่อีเมล", url: "URL", emoji: "อิโมจิ", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "วันที่เวลาแบบ ISO", date: "วันที่แบบ ISO", time: "เวลาแบบ ISO", duration: "ช่วงเวลาแบบ ISO", ipv4: "ที่อยู่ IPv4", ipv6: "ที่อยู่ IPv6", cidrv4: "ช่วง IP แบบ IPv4", cidrv6: "ช่วง IP แบบ IPv6", base64: "ข้อความแบบ Base64", base64url: "ข้อความแบบ Base64 สำหรับ URL", json_string: "ข้อความแบบ JSON", e164: "เบอร์โทรศัพท์ระหว่างประเทศ (E.164)", jwt: "โทเคน JWT", template_literal: "ข้อมูลที่ป้อน" }, a2 = { nan: "NaN", number: "ตัวเลข", array: "อาร์เรย์ (Array)", null: "ไม่มีค่า (null)" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${t2.expected} แต่ได้รับ ${u2}` : `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${r2} แต่ได้รับ ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `ค่าไม่ถูกต้อง: ควรเป็น ${b(t2.values[0])}` : `ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "ไม่เกิน" : "น้อยกว่า", o2 = i2(t2.origin);
        return o2 ? `เกินกำหนด: ${t2.origin ?? "ค่า"} ควรมี${r2} ${t2.maximum.toString()} ${o2.unit ?? "รายการ"}` : `เกินกำหนด: ${t2.origin ?? "ค่า"} ควรมี${r2} ${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? "อย่างน้อย" : "มากกว่า", o2 = i2(t2.origin);
        return o2 ? `น้อยกว่ากำหนด: ${t2.origin} ควรมี${r2} ${t2.minimum.toString()} ${o2.unit}` : `น้อยกว่ากำหนด: ${t2.origin} ควรมี${r2} ${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${r2.prefix}"` : r2.format === "ends_with" ? `รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${r2.suffix}"` : r2.format === "includes" ? `รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${r2.includes}" อยู่ในข้อความ` : r2.format === "regex" ? `รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${r2.pattern}` : `รูปแบบไม่ถูกต้อง: ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${t2.divisor} ได้ลงตัว`;
      case "unrecognized_keys":
        return `พบคีย์ที่ไม่รู้จัก: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `คีย์ไม่ถูกต้องใน ${t2.origin}`;
      case "invalid_union":
        return "ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";
      case "invalid_element":
        return `ข้อมูลไม่ถูกต้องใน ${t2.origin}`;
      default:
        return "ข้อมูลไม่ถูกต้อง";
    }
  };
};
function cp() {
  return { localeError: dp() };
}
var mp = () => {
  let e2 = { string: { unit: "karakter", verb: "olmalı" }, file: { unit: "bayt", verb: "olmalı" }, array: { unit: "öğe", verb: "olmalı" }, set: { unit: "öğe", verb: "olmalı" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "girdi", email: "e-posta adresi", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO tarih ve saat", date: "ISO tarih", time: "ISO saat", duration: "ISO süre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", cidrv4: "IPv4 aralığı", cidrv6: "IPv6 aralığı", base64: "base64 ile şifrelenmiş metin", base64url: "base64url ile şifrelenmiş metin", json_string: "JSON dizesi", e164: "E.164 sayısı", jwt: "JWT", template_literal: "Şablon dizesi" }, a2 = { nan: "NaN" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Geçersiz değer: beklenen instanceof ${t2.expected}, alınan ${u2}` : `Geçersiz değer: beklenen ${r2}, alınan ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Geçersiz değer: beklenen ${b(t2.values[0])}` : `Geçersiz seçenek: aşağıdakilerden biri olmalı: ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Çok büyük: beklenen ${t2.origin ?? "değer"} ${r2}${t2.maximum.toString()} ${o2.unit ?? "öğe"}` : `Çok büyük: beklenen ${t2.origin ?? "değer"} ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Çok küçük: beklenen ${t2.origin} ${r2}${t2.minimum.toString()} ${o2.unit}` : `Çok küçük: beklenen ${t2.origin} ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Geçersiz metin: "${r2.prefix}" ile başlamalı` : r2.format === "ends_with" ? `Geçersiz metin: "${r2.suffix}" ile bitmeli` : r2.format === "includes" ? `Geçersiz metin: "${r2.includes}" içermeli` : r2.format === "regex" ? `Geçersiz metin: ${r2.pattern} desenine uymalı` : `Geçersiz ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Geçersiz sayı: ${t2.divisor} ile tam bölünebilmeli`;
      case "unrecognized_keys":
        return `Tanınmayan anahtar${t2.keys.length > 1 ? "lar" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `${t2.origin} içinde geçersiz anahtar`;
      case "invalid_union":
        return "Geçersiz değer";
      case "invalid_element":
        return `${t2.origin} içinde geçersiz değer`;
      default:
        return "Geçersiz değer";
    }
  };
};
function fp() {
  return { localeError: mp() };
}
var pp = () => {
  let e2 = { string: { unit: "символів", verb: "матиме" }, file: { unit: "байтів", verb: "матиме" }, array: { unit: "елементів", verb: "матиме" }, set: { unit: "елементів", verb: "матиме" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "вхідні дані", email: "адреса електронної пошти", url: "URL", emoji: "емодзі", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "дата та час ISO", date: "дата ISO", time: "час ISO", duration: "тривалість ISO", ipv4: "адреса IPv4", ipv6: "адреса IPv6", cidrv4: "діапазон IPv4", cidrv6: "діапазон IPv6", base64: "рядок у кодуванні base64", base64url: "рядок у кодуванні base64url", json_string: "рядок JSON", e164: "номер E.164", jwt: "JWT", template_literal: "вхідні дані" }, a2 = { nan: "NaN", number: "число", array: "масив" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Неправильні вхідні дані: очікується instanceof ${t2.expected}, отримано ${u2}` : `Неправильні вхідні дані: очікується ${r2}, отримано ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Неправильні вхідні дані: очікується ${b(t2.values[0])}` : `Неправильна опція: очікується одне з ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Занадто велике: очікується, що ${t2.origin ?? "значення"} ${o2.verb} ${r2}${t2.maximum.toString()} ${o2.unit ?? "елементів"}` : `Занадто велике: очікується, що ${t2.origin ?? "значення"} буде ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Занадто мале: очікується, що ${t2.origin} ${o2.verb} ${r2}${t2.minimum.toString()} ${o2.unit}` : `Занадто мале: очікується, що ${t2.origin} буде ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Неправильний рядок: повинен починатися з "${r2.prefix}"` : r2.format === "ends_with" ? `Неправильний рядок: повинен закінчуватися на "${r2.suffix}"` : r2.format === "includes" ? `Неправильний рядок: повинен містити "${r2.includes}"` : r2.format === "regex" ? `Неправильний рядок: повинен відповідати шаблону ${r2.pattern}` : `Неправильний ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Неправильне число: повинно бути кратним ${t2.divisor}`;
      case "unrecognized_keys":
        return `Нерозпізнаний ключ${t2.keys.length > 1 ? "і" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Неправильний ключ у ${t2.origin}`;
      case "invalid_union":
        return "Неправильні вхідні дані";
      case "invalid_element":
        return `Неправильне значення у ${t2.origin}`;
      default:
        return "Неправильні вхідні дані";
    }
  };
};
function Ku() {
  return { localeError: pp() };
}
function vp() {
  return Ku();
}
var gp = () => {
  let e2 = { string: { unit: "حروف", verb: "ہونا" }, file: { unit: "بائٹس", verb: "ہونا" }, array: { unit: "آئٹمز", verb: "ہونا" }, set: { unit: "آئٹمز", verb: "ہونا" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "ان پٹ", email: "ای میل ایڈریس", url: "یو آر ایل", emoji: "ایموجی", uuid: "یو یو آئی ڈی", uuidv4: "یو یو آئی ڈی وی 4", uuidv6: "یو یو آئی ڈی وی 6", nanoid: "نینو آئی ڈی", guid: "جی یو آئی ڈی", cuid: "سی یو آئی ڈی", cuid2: "سی یو آئی ڈی 2", ulid: "یو ایل آئی ڈی", xid: "ایکس آئی ڈی", ksuid: "کے ایس یو آئی ڈی", datetime: "آئی ایس او ڈیٹ ٹائم", date: "آئی ایس او تاریخ", time: "آئی ایس او وقت", duration: "آئی ایس او مدت", ipv4: "آئی پی وی 4 ایڈریس", ipv6: "آئی پی وی 6 ایڈریس", cidrv4: "آئی پی وی 4 رینج", cidrv6: "آئی پی وی 6 رینج", base64: "بیس 64 ان کوڈڈ سٹرنگ", base64url: "بیس 64 یو آر ایل ان کوڈڈ سٹرنگ", json_string: "جے ایس او این سٹرنگ", e164: "ای 164 نمبر", jwt: "جے ڈبلیو ٹی", template_literal: "ان پٹ" }, a2 = { nan: "NaN", number: "نمبر", array: "آرے", null: "نل" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `غلط ان پٹ: instanceof ${t2.expected} متوقع تھا، ${u2} موصول ہوا` : `غلط ان پٹ: ${r2} متوقع تھا، ${u2} موصول ہوا`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `غلط ان پٹ: ${b(t2.values[0])} متوقع تھا` : `غلط آپشن: ${v(t2.values, "|")} میں سے ایک متوقع تھا`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `بہت بڑا: ${t2.origin ?? "ویلیو"} کے ${r2}${t2.maximum.toString()} ${o2.unit ?? "عناصر"} ہونے متوقع تھے` : `بہت بڑا: ${t2.origin ?? "ویلیو"} کا ${r2}${t2.maximum.toString()} ہونا متوقع تھا`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `بہت چھوٹا: ${t2.origin} کے ${r2}${t2.minimum.toString()} ${o2.unit} ہونے متوقع تھے` : `بہت چھوٹا: ${t2.origin} کا ${r2}${t2.minimum.toString()} ہونا متوقع تھا`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `غلط سٹرنگ: "${r2.prefix}" سے شروع ہونا چاہیے` : r2.format === "ends_with" ? `غلط سٹرنگ: "${r2.suffix}" پر ختم ہونا چاہیے` : r2.format === "includes" ? `غلط سٹرنگ: "${r2.includes}" شامل ہونا چاہیے` : r2.format === "regex" ? `غلط سٹرنگ: پیٹرن ${r2.pattern} سے میچ ہونا چاہیے` : `غلط ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `غلط نمبر: ${t2.divisor} کا مضاعف ہونا چاہیے`;
      case "unrecognized_keys":
        return `غیر تسلیم شدہ کی${t2.keys.length > 1 ? "ز" : ""}: ${v(t2.keys, "، ")}`;
      case "invalid_key":
        return `${t2.origin} میں غلط کی`;
      case "invalid_union":
        return "غلط ان پٹ";
      case "invalid_element":
        return `${t2.origin} میں غلط ویلیو`;
      default:
        return "غلط ان پٹ";
    }
  };
};
function hp() {
  return { localeError: gp() };
}
var $p = () => {
  let e2 = { string: { unit: "belgi", verb: "bo‘lishi kerak" }, file: { unit: "bayt", verb: "bo‘lishi kerak" }, array: { unit: "element", verb: "bo‘lishi kerak" }, set: { unit: "element", verb: "bo‘lishi kerak" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "kirish", email: "elektron pochta manzili", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO sana va vaqti", date: "ISO sana", time: "ISO vaqt", duration: "ISO davomiylik", ipv4: "IPv4 manzil", ipv6: "IPv6 manzil", mac: "MAC manzil", cidrv4: "IPv4 diapazon", cidrv6: "IPv6 diapazon", base64: "base64 kodlangan satr", base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", jwt: "JWT", template_literal: "kirish" }, a2 = { nan: "NaN", number: "raqam", array: "massiv" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Noto‘g‘ri kirish: kutilgan instanceof ${t2.expected}, qabul qilingan ${u2}` : `Noto‘g‘ri kirish: kutilgan ${r2}, qabul qilingan ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Noto‘g‘ri kirish: kutilgan ${b(t2.values[0])}` : `Noto‘g‘ri variant: quyidagilardan biri kutilgan ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Juda katta: kutilgan ${t2.origin ?? "qiymat"} ${r2}${t2.maximum.toString()} ${o2.unit} ${o2.verb}` : `Juda katta: kutilgan ${t2.origin ?? "qiymat"} ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Juda kichik: kutilgan ${t2.origin} ${r2}${t2.minimum.toString()} ${o2.unit} ${o2.verb}` : `Juda kichik: kutilgan ${t2.origin} ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Noto‘g‘ri satr: "${r2.prefix}" bilan boshlanishi kerak` : r2.format === "ends_with" ? `Noto‘g‘ri satr: "${r2.suffix}" bilan tugashi kerak` : r2.format === "includes" ? `Noto‘g‘ri satr: "${r2.includes}" ni o‘z ichiga olishi kerak` : r2.format === "regex" ? `Noto‘g‘ri satr: ${r2.pattern} shabloniga mos kelishi kerak` : `Noto‘g‘ri ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Noto‘g‘ri raqam: ${t2.divisor} ning karralisi bo‘lishi kerak`;
      case "unrecognized_keys":
        return `Noma’lum kalit${t2.keys.length > 1 ? "lar" : ""}: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `${t2.origin} dagi kalit noto‘g‘ri`;
      case "invalid_union":
        return "Noto‘g‘ri kirish";
      case "invalid_element":
        return `${t2.origin} da noto‘g‘ri qiymat`;
      default:
        return "Noto‘g‘ri kirish";
    }
  };
};
function bp() {
  return { localeError: $p() };
}
var yp = () => {
  let e2 = { string: { unit: "ký tự", verb: "có" }, file: { unit: "byte", verb: "có" }, array: { unit: "phần tử", verb: "có" }, set: { unit: "phần tử", verb: "có" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "đầu vào", email: "địa chỉ email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ngày giờ ISO", date: "ngày ISO", time: "giờ ISO", duration: "khoảng thời gian ISO", ipv4: "địa chỉ IPv4", ipv6: "địa chỉ IPv6", cidrv4: "dải IPv4", cidrv6: "dải IPv6", base64: "chuỗi mã hóa base64", base64url: "chuỗi mã hóa base64url", json_string: "chuỗi JSON", e164: "số E.164", jwt: "JWT", template_literal: "đầu vào" }, a2 = { nan: "NaN", number: "số", array: "mảng" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Đầu vào không hợp lệ: mong đợi instanceof ${t2.expected}, nhận được ${u2}` : `Đầu vào không hợp lệ: mong đợi ${r2}, nhận được ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Đầu vào không hợp lệ: mong đợi ${b(t2.values[0])}` : `Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Quá lớn: mong đợi ${t2.origin ?? "giá trị"} ${o2.verb} ${r2}${t2.maximum.toString()} ${o2.unit ?? "phần tử"}` : `Quá lớn: mong đợi ${t2.origin ?? "giá trị"} ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Quá nhỏ: mong đợi ${t2.origin} ${o2.verb} ${r2}${t2.minimum.toString()} ${o2.unit}` : `Quá nhỏ: mong đợi ${t2.origin} ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Chuỗi không hợp lệ: phải bắt đầu bằng "${r2.prefix}"` : r2.format === "ends_with" ? `Chuỗi không hợp lệ: phải kết thúc bằng "${r2.suffix}"` : r2.format === "includes" ? `Chuỗi không hợp lệ: phải bao gồm "${r2.includes}"` : r2.format === "regex" ? `Chuỗi không hợp lệ: phải khớp với mẫu ${r2.pattern}` : `${n[r2.format] ?? t2.format} không hợp lệ`;
      }
      case "not_multiple_of":
        return `Số không hợp lệ: phải là bội số của ${t2.divisor}`;
      case "unrecognized_keys":
        return `Khóa không được nhận dạng: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Khóa không hợp lệ trong ${t2.origin}`;
      case "invalid_union":
        return "Đầu vào không hợp lệ";
      case "invalid_element":
        return `Giá trị không hợp lệ trong ${t2.origin}`;
      default:
        return "Đầu vào không hợp lệ";
    }
  };
};
function _p() {
  return { localeError: yp() };
}
var kp = () => {
  let e2 = { string: { unit: "字符", verb: "包含" }, file: { unit: "字节", verb: "包含" }, array: { unit: "项", verb: "包含" }, set: { unit: "项", verb: "包含" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "输入", email: "电子邮件", url: "URL", emoji: "表情符号", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO日期时间", date: "ISO日期", time: "ISO时间", duration: "ISO时长", ipv4: "IPv4地址", ipv6: "IPv6地址", cidrv4: "IPv4网段", cidrv6: "IPv6网段", base64: "base64编码字符串", base64url: "base64url编码字符串", json_string: "JSON字符串", e164: "E.164号码", jwt: "JWT", template_literal: "输入" }, a2 = { nan: "NaN", number: "数字", array: "数组", null: "空值(null)" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `无效输入：期望 instanceof ${t2.expected}，实际接收 ${u2}` : `无效输入：期望 ${r2}，实际接收 ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `无效输入：期望 ${b(t2.values[0])}` : `无效选项：期望以下之一 ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `数值过大：期望 ${t2.origin ?? "值"} ${r2}${t2.maximum.toString()} ${o2.unit ?? "个元素"}` : `数值过大：期望 ${t2.origin ?? "值"} ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `数值过小：期望 ${t2.origin} ${r2}${t2.minimum.toString()} ${o2.unit}` : `数值过小：期望 ${t2.origin} ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `无效字符串：必须以 "${r2.prefix}" 开头` : r2.format === "ends_with" ? `无效字符串：必须以 "${r2.suffix}" 结尾` : r2.format === "includes" ? `无效字符串：必须包含 "${r2.includes}"` : r2.format === "regex" ? `无效字符串：必须满足正则表达式 ${r2.pattern}` : `无效${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `无效数字：必须是 ${t2.divisor} 的倍数`;
      case "unrecognized_keys":
        return `出现未知的键(key): ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `${t2.origin} 中的键(key)无效`;
      case "invalid_union":
        return "无效输入";
      case "invalid_element":
        return `${t2.origin} 中包含无效值(value)`;
      default:
        return "无效输入";
    }
  };
};
function Ip() {
  return { localeError: kp() };
}
var xp = () => {
  let e2 = { string: { unit: "字元", verb: "擁有" }, file: { unit: "位元組", verb: "擁有" }, array: { unit: "項目", verb: "擁有" }, set: { unit: "項目", verb: "擁有" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "輸入", email: "郵件地址", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO 日期時間", date: "ISO 日期", time: "ISO 時間", duration: "ISO 期間", ipv4: "IPv4 位址", ipv6: "IPv6 位址", cidrv4: "IPv4 範圍", cidrv6: "IPv6 範圍", base64: "base64 編碼字串", base64url: "base64url 編碼字串", json_string: "JSON 字串", e164: "E.164 數值", jwt: "JWT", template_literal: "輸入" }, a2 = { nan: "NaN" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `無效的輸入值：預期為 instanceof ${t2.expected}，但收到 ${u2}` : `無效的輸入值：預期為 ${r2}，但收到 ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `無效的輸入值：預期為 ${b(t2.values[0])}` : `無效的選項：預期為以下其中之一 ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `數值過大：預期 ${t2.origin ?? "值"} 應為 ${r2}${t2.maximum.toString()} ${o2.unit ?? "個元素"}` : `數值過大：預期 ${t2.origin ?? "值"} 應為 ${r2}${t2.maximum.toString()}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `數值過小：預期 ${t2.origin} 應為 ${r2}${t2.minimum.toString()} ${o2.unit}` : `數值過小：預期 ${t2.origin} 應為 ${r2}${t2.minimum.toString()}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `無效的字串：必須以 "${r2.prefix}" 開頭` : r2.format === "ends_with" ? `無效的字串：必須以 "${r2.suffix}" 結尾` : r2.format === "includes" ? `無效的字串：必須包含 "${r2.includes}"` : r2.format === "regex" ? `無效的字串：必須符合格式 ${r2.pattern}` : `無效的 ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `無效的數字：必須為 ${t2.divisor} 的倍數`;
      case "unrecognized_keys":
        return `無法識別的鍵值${t2.keys.length > 1 ? "們" : ""}：${v(t2.keys, "、")}`;
      case "invalid_key":
        return `${t2.origin} 中有無效的鍵值`;
      case "invalid_union":
        return "無效的輸入值";
      case "invalid_element":
        return `${t2.origin} 中有無效的值`;
      default:
        return "無效的輸入值";
    }
  };
};
function wp() {
  return { localeError: xp() };
}
var Sp = () => {
  let e2 = { string: { unit: "àmi", verb: "ní" }, file: { unit: "bytes", verb: "ní" }, array: { unit: "nkan", verb: "ní" }, set: { unit: "nkan", verb: "ní" } };
  function i2(t2) {
    return e2[t2] ?? null;
  }
  let n = { regex: "ẹ̀rọ ìbáwọlé", email: "àdírẹ́sì ìmẹ́lì", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "àkókò ISO", date: "ọjọ́ ISO", time: "àkókò ISO", duration: "àkókò tó pé ISO", ipv4: "àdírẹ́sì IPv4", ipv6: "àdírẹ́sì IPv6", cidrv4: "àgbègbè IPv4", cidrv6: "àgbègbè IPv6", base64: "ọ̀rọ̀ tí a kọ́ ní base64", base64url: "ọ̀rọ̀ base64url", json_string: "ọ̀rọ̀ JSON", e164: "nọ́mbà E.164", jwt: "JWT", template_literal: "ẹ̀rọ ìbáwọlé" }, a2 = { nan: "NaN", number: "nọ́mbà", array: "akopọ" };
  return (t2) => {
    switch (t2.code) {
      case "invalid_type": {
        let r2 = a2[t2.expected] ?? t2.expected, o2 = _(t2.input), u2 = a2[o2] ?? o2;
        return /^[A-Z]/.test(t2.expected) ? `Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${t2.expected}, àmọ̀ a rí ${u2}` : `Ìbáwọlé aṣìṣe: a ní láti fi ${r2}, àmọ̀ a rí ${u2}`;
      }
      case "invalid_value":
        return t2.values.length === 1 ? `Ìbáwọlé aṣìṣe: a ní láti fi ${b(t2.values[0])}` : `Àṣàyàn aṣìṣe: yan ọ̀kan lára ${v(t2.values, "|")}`;
      case "too_big": {
        let r2 = t2.inclusive ? "<=" : "<", o2 = i2(t2.origin);
        return o2 ? `Tó pọ̀ jù: a ní láti jẹ́ pé ${t2.origin ?? "iye"} ${o2.verb} ${r2}${t2.maximum} ${o2.unit}` : `Tó pọ̀ jù: a ní láti jẹ́ ${r2}${t2.maximum}`;
      }
      case "too_small": {
        let r2 = t2.inclusive ? ">=" : ">", o2 = i2(t2.origin);
        return o2 ? `Kéré ju: a ní láti jẹ́ pé ${t2.origin} ${o2.verb} ${r2}${t2.minimum} ${o2.unit}` : `Kéré ju: a ní láti jẹ́ ${r2}${t2.minimum}`;
      }
      case "invalid_format": {
        let r2 = t2;
        return r2.format === "starts_with" ? `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${r2.prefix}"` : r2.format === "ends_with" ? `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${r2.suffix}"` : r2.format === "includes" ? `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${r2.includes}"` : r2.format === "regex" ? `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${r2.pattern}` : `Aṣìṣe: ${n[r2.format] ?? t2.format}`;
      }
      case "not_multiple_of":
        return `Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${t2.divisor}`;
      case "unrecognized_keys":
        return `Bọtìnì àìmọ̀: ${v(t2.keys, ", ")}`;
      case "invalid_key":
        return `Bọtìnì aṣìṣe nínú ${t2.origin}`;
      case "invalid_union":
        return "Ìbáwọlé aṣìṣe";
      case "invalid_element":
        return `Iye aṣìṣe nínú ${t2.origin}`;
      default:
        return "Ìbáwọlé aṣìṣe";
    }
  };
};
function zp() {
  return { localeError: Sp() };
}
var oa, Bu = /* @__PURE__ */ Symbol("ZodOutput"), Hu = /* @__PURE__ */ Symbol("ZodInput");
class Xu {
  constructor() {
    this._map = /* @__PURE__ */ new WeakMap(), this._idmap = /* @__PURE__ */ new Map();
  }
  add(i2, ...n) {
    let a2 = n[0];
    return this._map.set(i2, a2), a2 && typeof a2 == "object" && "id" in a2 && this._idmap.set(a2.id, i2), this;
  }
  clear() {
    return this._map = /* @__PURE__ */ new WeakMap(), this._idmap = /* @__PURE__ */ new Map(), this;
  }
  remove(i2) {
    let n = this._map.get(i2);
    return n && typeof n == "object" && "id" in n && this._idmap.delete(n.id), this._map.delete(i2), this;
  }
  get(i2) {
    let n = i2._zod.parent;
    if (n) {
      let a2 = { ...this.get(n) ?? {} };
      delete a2.id;
      let t2 = { ...a2, ...this._map.get(i2) };
      return Object.keys(t2).length ? t2 : void 0;
    }
    return this._map.get(i2);
  }
  has(i2) {
    return this._map.has(i2);
  }
}
function mn() {
  return new Xu();
}
(oa = globalThis).__zod_globalRegistry ?? (oa.__zod_globalRegistry = mn());
var Q = globalThis.__zod_globalRegistry;
function Yu(e2, i2) {
  return new e2({ type: "string", ...g(i2) });
}
function Qu(e2, i2) {
  return new e2({ type: "string", coerce: true, ...g(i2) });
}
function fn(e2, i2) {
  return new e2({ type: "string", format: "email", check: "string_format", abort: false, ...g(i2) });
}
function Nt(e2, i2) {
  return new e2({ type: "string", format: "guid", check: "string_format", abort: false, ...g(i2) });
}
function pn(e2, i2) {
  return new e2({ type: "string", format: "uuid", check: "string_format", abort: false, ...g(i2) });
}
function vn(e2, i2) {
  return new e2({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v4", ...g(i2) });
}
function gn(e2, i2) {
  return new e2({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v6", ...g(i2) });
}
function hn(e2, i2) {
  return new e2({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v7", ...g(i2) });
}
function Jt(e2, i2) {
  return new e2({ type: "string", format: "url", check: "string_format", abort: false, ...g(i2) });
}
function $n(e2, i2) {
  return new e2({ type: "string", format: "emoji", check: "string_format", abort: false, ...g(i2) });
}
function bn(e2, i2) {
  return new e2({ type: "string", format: "nanoid", check: "string_format", abort: false, ...g(i2) });
}
function yn(e2, i2) {
  return new e2({ type: "string", format: "cuid", check: "string_format", abort: false, ...g(i2) });
}
function _n(e2, i2) {
  return new e2({ type: "string", format: "cuid2", check: "string_format", abort: false, ...g(i2) });
}
function kn(e2, i2) {
  return new e2({ type: "string", format: "ulid", check: "string_format", abort: false, ...g(i2) });
}
function In(e2, i2) {
  return new e2({ type: "string", format: "xid", check: "string_format", abort: false, ...g(i2) });
}
function xn(e2, i2) {
  return new e2({ type: "string", format: "ksuid", check: "string_format", abort: false, ...g(i2) });
}
function wn(e2, i2) {
  return new e2({ type: "string", format: "ipv4", check: "string_format", abort: false, ...g(i2) });
}
function Sn(e2, i2) {
  return new e2({ type: "string", format: "ipv6", check: "string_format", abort: false, ...g(i2) });
}
function es(e2, i2) {
  return new e2({ type: "string", format: "mac", check: "string_format", abort: false, ...g(i2) });
}
function zn(e2, i2) {
  return new e2({ type: "string", format: "cidrv4", check: "string_format", abort: false, ...g(i2) });
}
function Un(e2, i2) {
  return new e2({ type: "string", format: "cidrv6", check: "string_format", abort: false, ...g(i2) });
}
function On(e2, i2) {
  return new e2({ type: "string", format: "base64", check: "string_format", abort: false, ...g(i2) });
}
function jn(e2, i2) {
  return new e2({ type: "string", format: "base64url", check: "string_format", abort: false, ...g(i2) });
}
function Zn(e2, i2) {
  return new e2({ type: "string", format: "e164", check: "string_format", abort: false, ...g(i2) });
}
function Nn(e2, i2) {
  return new e2({ type: "string", format: "jwt", check: "string_format", abort: false, ...g(i2) });
}
var ts = { Any: null, Minute: -1, Second: 0, Millisecond: 3, Microsecond: 6 };
function is(e2, i2) {
  return new e2({ type: "string", format: "datetime", check: "string_format", offset: false, local: false, precision: null, ...g(i2) });
}
function ns(e2, i2) {
  return new e2({ type: "string", format: "date", check: "string_format", ...g(i2) });
}
function rs(e2, i2) {
  return new e2({ type: "string", format: "time", check: "string_format", precision: null, ...g(i2) });
}
function as(e2, i2) {
  return new e2({ type: "string", format: "duration", check: "string_format", ...g(i2) });
}
function os(e2, i2) {
  return new e2({ type: "number", checks: [], ...g(i2) });
}
function us(e2, i2) {
  return new e2({ type: "number", coerce: true, checks: [], ...g(i2) });
}
function ss(e2, i2) {
  return new e2({ type: "number", check: "number_format", abort: false, format: "safeint", ...g(i2) });
}
function ls(e2, i2) {
  return new e2({ type: "number", check: "number_format", abort: false, format: "float32", ...g(i2) });
}
function ds(e2, i2) {
  return new e2({ type: "number", check: "number_format", abort: false, format: "float64", ...g(i2) });
}
function cs(e2, i2) {
  return new e2({ type: "number", check: "number_format", abort: false, format: "int32", ...g(i2) });
}
function ms(e2, i2) {
  return new e2({ type: "number", check: "number_format", abort: false, format: "uint32", ...g(i2) });
}
function fs(e2, i2) {
  return new e2({ type: "boolean", ...g(i2) });
}
function ps(e2, i2) {
  return new e2({ type: "boolean", coerce: true, ...g(i2) });
}
function vs(e2, i2) {
  return new e2({ type: "bigint", ...g(i2) });
}
function gs(e2, i2) {
  return new e2({ type: "bigint", coerce: true, ...g(i2) });
}
function hs(e2, i2) {
  return new e2({ type: "bigint", check: "bigint_format", abort: false, format: "int64", ...g(i2) });
}
function $s(e2, i2) {
  return new e2({ type: "bigint", check: "bigint_format", abort: false, format: "uint64", ...g(i2) });
}
function bs(e2, i2) {
  return new e2({ type: "symbol", ...g(i2) });
}
function ys(e2, i2) {
  return new e2({ type: "undefined", ...g(i2) });
}
function _s(e2, i2) {
  return new e2({ type: "null", ...g(i2) });
}
function ks(e2) {
  return new e2({ type: "any" });
}
function Is(e2) {
  return new e2({ type: "unknown" });
}
function xs(e2, i2) {
  return new e2({ type: "never", ...g(i2) });
}
function ws(e2, i2) {
  return new e2({ type: "void", ...g(i2) });
}
function Ss(e2, i2) {
  return new e2({ type: "date", ...g(i2) });
}
function zs(e2, i2) {
  return new e2({ type: "date", coerce: true, ...g(i2) });
}
function Us(e2, i2) {
  return new e2({ type: "nan", ...g(i2) });
}
function fe(e2, i2) {
  return new tn({ check: "less_than", ...g(i2), value: e2, inclusive: false });
}
function ee(e2, i2) {
  return new tn({ check: "less_than", ...g(i2), value: e2, inclusive: true });
}
function pe(e2, i2) {
  return new nn({ check: "greater_than", ...g(i2), value: e2, inclusive: false });
}
function V(e2, i2) {
  return new nn({ check: "greater_than", ...g(i2), value: e2, inclusive: true });
}
function Pn(e2) {
  return pe(0, e2);
}
function Dn(e2) {
  return fe(0, e2);
}
function En(e2) {
  return ee(0, e2);
}
function Tn(e2) {
  return V(0, e2);
}
function Te(e2, i2) {
  return new fo({ check: "multiple_of", ...g(i2), value: e2 });
}
function Je(e2, i2) {
  return new go({ check: "max_size", ...g(i2), maximum: e2 });
}
function ve(e2, i2) {
  return new ho({ check: "min_size", ...g(i2), minimum: e2 });
}
function lt(e2, i2) {
  return new $o({ check: "size_equals", ...g(i2), size: e2 });
}
function dt(e2, i2) {
  return new bo({ check: "max_length", ...g(i2), maximum: e2 });
}
function xe(e2, i2) {
  return new yo({ check: "min_length", ...g(i2), minimum: e2 });
}
function ct(e2, i2) {
  return new _o({ check: "length_equals", ...g(i2), length: e2 });
}
function Mt(e2, i2) {
  return new ko({ check: "string_format", format: "regex", ...g(i2), pattern: e2 });
}
function Ft(e2) {
  return new Io({ check: "string_format", format: "lowercase", ...g(e2) });
}
function qt(e2) {
  return new xo({ check: "string_format", format: "uppercase", ...g(e2) });
}
function Wt(e2, i2) {
  return new wo({ check: "string_format", format: "includes", ...g(i2), includes: e2 });
}
function Vt(e2, i2) {
  return new So({ check: "string_format", format: "starts_with", ...g(i2), prefix: e2 });
}
function Gt(e2, i2) {
  return new zo({ check: "string_format", format: "ends_with", ...g(i2), suffix: e2 });
}
function An(e2, i2, n) {
  return new Uo({ check: "property", property: e2, schema: i2, ...g(n) });
}
function Kt(e2, i2) {
  return new Oo({ check: "mime_type", mime: e2, ...g(i2) });
}
function ce(e2) {
  return new jo({ check: "overwrite", tx: e2 });
}
function Bt(e2) {
  return ce((i2) => i2.normalize(e2));
}
function Ht() {
  return ce((e2) => e2.trim());
}
function Xt() {
  return ce((e2) => e2.toLowerCase());
}
function Yt() {
  return ce((e2) => e2.toUpperCase());
}
function Qt() {
  return ce((e2) => ba(e2));
}
function Os(e2, i2, n) {
  return new e2({ type: "array", element: i2, ...g(n) });
}
function Up(e2, i2, n) {
  return new e2({ type: "union", options: i2, ...g(n) });
}
function Op(e2, i2, n) {
  return new e2({ type: "union", options: i2, inclusive: false, ...g(n) });
}
function jp(e2, i2, n, a2) {
  return new e2({ type: "union", options: n, discriminator: i2, ...g(a2) });
}
function Zp(e2, i2, n) {
  return new e2({ type: "intersection", left: i2, right: n });
}
function Np(e2, i2, n, a2) {
  let t2 = n instanceof k;
  return new e2({ type: "tuple", items: i2, rest: t2 ? n : null, ...g(t2 ? a2 : n) });
}
function Pp(e2, i2, n, a2) {
  return new e2({ type: "record", keyType: i2, valueType: n, ...g(a2) });
}
function Dp(e2, i2, n, a2) {
  return new e2({ type: "map", keyType: i2, valueType: n, ...g(a2) });
}
function Ep(e2, i2, n) {
  return new e2({ type: "set", valueType: i2, ...g(n) });
}
function Tp(e2, i2, n) {
  let a2 = Array.isArray(i2) ? Object.fromEntries(i2.map((t2) => [t2, t2])) : i2;
  return new e2({ type: "enum", entries: a2, ...g(n) });
}
function Ap(e2, i2, n) {
  return new e2({ type: "enum", entries: i2, ...g(n) });
}
function Rp(e2, i2, n) {
  return new e2({ type: "literal", values: Array.isArray(i2) ? i2 : [i2], ...g(n) });
}
function js(e2, i2) {
  return new e2({ type: "file", ...g(i2) });
}
function Cp(e2, i2) {
  return new e2({ type: "transform", transform: i2 });
}
function Lp(e2, i2) {
  return new e2({ type: "optional", innerType: i2 });
}
function Jp(e2, i2) {
  return new e2({ type: "nullable", innerType: i2 });
}
function Mp(e2, i2, n) {
  return new e2({ type: "default", innerType: i2, get defaultValue() {
    return typeof n == "function" ? n() : _a(n);
  } });
}
function Fp(e2, i2, n) {
  return new e2({ type: "nonoptional", innerType: i2, ...g(n) });
}
function qp(e2, i2) {
  return new e2({ type: "success", innerType: i2 });
}
function Wp(e2, i2, n) {
  return new e2({ type: "catch", innerType: i2, catchValue: typeof n == "function" ? n : () => n });
}
function Vp(e2, i2, n) {
  return new e2({ type: "pipe", in: i2, out: n });
}
function Gp(e2, i2) {
  return new e2({ type: "readonly", innerType: i2 });
}
function Kp(e2, i2, n) {
  return new e2({ type: "template_literal", parts: i2, ...g(n) });
}
function Bp(e2, i2) {
  return new e2({ type: "lazy", getter: i2 });
}
function Hp(e2, i2) {
  return new e2({ type: "promise", innerType: i2 });
}
function Zs(e2, i2, n) {
  let a2 = g(n);
  return a2.abort ?? (a2.abort = true), new e2({ type: "custom", check: "custom", fn: i2, ...a2 });
}
function Ns(e2, i2, n) {
  return new e2({ type: "custom", check: "custom", fn: i2, ...g(n) });
}
function Ps(e2) {
  let i2 = Ds((n) => (n.addIssue = (a2) => {
    if (typeof a2 == "string") n.issues.push(jt(a2, n.value, i2._zod.def));
    else {
      let t2 = a2;
      t2.fatal && (t2.continue = false), t2.code ?? (t2.code = "custom"), t2.input ?? (t2.input = n.value), t2.inst ?? (t2.inst = i2), t2.continue ?? (t2.continue = !i2._zod.def.abort), n.issues.push(jt(t2));
    }
  }, e2(n.value, n)));
  return i2;
}
function Ds(e2, i2) {
  let n = new E({ check: "custom", ...g(i2) });
  return n._zod.check = e2, n;
}
function Es(e2) {
  let i2 = new E({ check: "describe" });
  return i2._zod.onattach = [(n) => {
    let a2 = Q.get(n) ?? {};
    Q.add(n, { ...a2, description: e2 });
  }], i2._zod.check = () => {
  }, i2;
}
function Ts(e2) {
  let i2 = new E({ check: "meta" });
  return i2._zod.onattach = [(n) => {
    let a2 = Q.get(n) ?? {};
    Q.add(n, { ...a2, ...e2 });
  }], i2._zod.check = () => {
  }, i2;
}
function As(e2, i2) {
  let n = g(i2), a2 = n.truthy ?? ["true", "1", "yes", "on", "y", "enabled"], t2 = n.falsy ?? ["false", "0", "no", "off", "n", "disabled"];
  n.case !== "sensitive" && (a2 = a2.map((p2) => typeof p2 == "string" ? p2.toLowerCase() : p2), t2 = t2.map((p2) => typeof p2 == "string" ? p2.toLowerCase() : p2));
  let r2 = new Set(a2), o2 = new Set(t2), u2 = e2.Codec ?? dn, d = e2.Boolean ?? on, s2 = new (e2.String ?? st)({ type: "string", error: n.error }), m2 = new d({ type: "boolean", error: n.error }), c = new u2({ type: "pipe", in: s2, out: m2, transform: (p2, $2) => {
    let y = p2;
    return n.case !== "sensitive" && (y = y.toLowerCase()), r2.has(y) ? true : o2.has(y) ? false : ($2.issues.push({ code: "invalid_value", expected: "stringbool", values: [...r2, ...o2], input: $2.value, inst: c, continue: false }), {});
  }, reverseTransform: (p2, $2) => p2 === true ? a2[0] || "true" : t2[0] || "false", error: n.error });
  return c;
}
function mt(e2, i2, n, a2 = {}) {
  let t2 = g(a2), r2 = { ...g(a2), check: "string_format", type: "string", format: i2, fn: typeof n == "function" ? n : (o2) => n.test(o2), ...t2 };
  return n instanceof RegExp && (r2.pattern = n), new e2(r2);
}
function Ae(e2) {
  let i2 = (e2 == null ? void 0 : e2.target) ?? "draft-2020-12";
  return i2 === "draft-4" && (i2 = "draft-04"), i2 === "draft-7" && (i2 = "draft-07"), { processors: e2.processors ?? {}, metadataRegistry: (e2 == null ? void 0 : e2.metadata) ?? Q, target: i2, unrepresentable: (e2 == null ? void 0 : e2.unrepresentable) ?? "throw", override: (e2 == null ? void 0 : e2.override) ?? (() => {
  }), io: (e2 == null ? void 0 : e2.io) ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), cycles: (e2 == null ? void 0 : e2.cycles) ?? "ref", reused: (e2 == null ? void 0 : e2.reused) ?? "inline", external: (e2 == null ? void 0 : e2.external) ?? void 0 };
}
function O(e2, i2, n = { path: [], schemaPath: [] }) {
  var s2, m2;
  var a2;
  let t2 = e2._zod.def, r2 = i2.seen.get(e2);
  if (r2)
    return r2.count++, n.schemaPath.includes(e2) && (r2.cycle = n.path), r2.schema;
  let o2 = { schema: {}, count: 1, cycle: void 0, path: n.path };
  i2.seen.set(e2, o2);
  let u2 = (m2 = (s2 = e2._zod).toJSONSchema) == null ? void 0 : m2.call(s2);
  if (u2) o2.schema = u2;
  else {
    let c = { ...n, schemaPath: [...n.schemaPath, e2], path: n.path };
    if (e2._zod.processJSONSchema) e2._zod.processJSONSchema(i2, o2.schema, c);
    else {
      let $2 = o2.schema, y = i2.processors[t2.type];
      if (!y) throw Error(`[toJSONSchema]: Non-representable type encountered: ${t2.type}`);
      y(e2, i2, $2, c);
    }
    let p2 = e2._zod.parent;
    p2 && (o2.ref || (o2.ref = p2), O(p2, i2, c), i2.seen.get(p2).isParent = true);
  }
  let d = i2.metadataRegistry.get(e2);
  return d && Object.assign(o2.schema, d), i2.io === "input" && q(e2) && (delete o2.schema.examples, delete o2.schema.default), i2.io === "input" && o2.schema._prefault && ((a2 = o2.schema).default ?? (a2.default = o2.schema._prefault)), delete o2.schema._prefault, i2.seen.get(e2).schema;
}
function Re(e2, i2) {
  var o2, u2, d, s2;
  let n = e2.seen.get(i2);
  if (!n) throw Error("Unprocessed schema. This is a bug in Zod.");
  let a2 = /* @__PURE__ */ new Map();
  for (let m2 of e2.seen.entries()) {
    let c = (o2 = e2.metadataRegistry.get(m2[0])) == null ? void 0 : o2.id;
    if (c) {
      let p2 = a2.get(c);
      if (p2 && p2 !== m2[0]) throw Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
      a2.set(c, m2[0]);
    }
  }
  let t2 = (m2) => {
    var y;
    let c = e2.target === "draft-2020-12" ? "$defs" : "definitions";
    if (e2.external) {
      let x2 = (y = e2.external.registry.get(m2[0])) == null ? void 0 : y.id, z2 = e2.external.uri ?? ((W2) => W2);
      if (x2) return { ref: z2(x2) };
      let P2 = m2[1].defId ?? m2[1].schema.id ?? `schema${e2.counter++}`;
      return m2[1].defId = P2, { defId: P2, ref: `${z2("__shared")}#/${c}/${P2}` };
    }
    if (m2[1] === n) return { ref: "#" };
    let p2 = `#/${c}/`, $2 = m2[1].schema.id ?? `__schema${e2.counter++}`;
    return { defId: $2, ref: p2 + $2 };
  }, r2 = (m2) => {
    if (m2[1].schema.$ref) return;
    let c = m2[1], { ref: p2, defId: $2 } = t2(m2);
    c.def = { ...c.schema }, $2 && (c.defId = $2);
    let y = c.schema;
    for (let x2 in y) delete y[x2];
    y.$ref = p2;
  };
  if (e2.cycles === "throw") for (let m2 of e2.seen.entries()) {
    let c = m2[1];
    if (c.cycle) throw Error(`Cycle detected: #/${(u2 = c.cycle) == null ? void 0 : u2.join("/")}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
  }
  for (let m2 of e2.seen.entries()) {
    let c = m2[1];
    if (i2 === m2[0]) {
      r2(m2);
      continue;
    }
    if (e2.external) {
      let p2 = (d = e2.external.registry.get(m2[0])) == null ? void 0 : d.id;
      if (i2 !== m2[0] && p2) {
        r2(m2);
        continue;
      }
    }
    if ((s2 = e2.metadataRegistry.get(m2[0])) != null && s2.id) {
      r2(m2);
      continue;
    }
    if (c.cycle) {
      r2(m2);
      continue;
    }
    if (c.count > 1 && e2.reused === "ref") {
      r2(m2);
      continue;
    }
  }
}
function Ce(e2, i2) {
  var o2, u2, d;
  let n = e2.seen.get(i2);
  if (!n) throw Error("Unprocessed schema. This is a bug in Zod.");
  let a2 = (s2) => {
    let m2 = e2.seen.get(s2);
    if (m2.ref === null) return;
    let c = m2.def ?? m2.schema, p2 = { ...c }, $2 = m2.ref;
    if (m2.ref = null, $2) {
      a2($2);
      let x2 = e2.seen.get($2), z2 = x2.schema;
      if (z2.$ref && (e2.target === "draft-07" || e2.target === "draft-04" || e2.target === "openapi-3.0") ? (c.allOf = c.allOf ?? [], c.allOf.push(z2)) : Object.assign(c, z2), Object.assign(c, p2), s2._zod.parent === $2) for (let P2 in c)
        P2 === "$ref" || P2 === "allOf" || P2 in p2 || delete c[P2];
      if (z2.$ref) for (let P2 in c)
        P2 === "$ref" || P2 === "allOf" || P2 in x2.def && JSON.stringify(c[P2]) === JSON.stringify(x2.def[P2]) && delete c[P2];
    }
    let y = s2._zod.parent;
    if (y && y !== $2) {
      a2(y);
      let x2 = e2.seen.get(y);
      if (x2 != null && x2.schema.$ref && (c.$ref = x2.schema.$ref, x2.def))
        for (let z2 in c)
          z2 === "$ref" || z2 === "allOf" || z2 in x2.def && JSON.stringify(c[z2]) === JSON.stringify(x2.def[z2]) && delete c[z2];
    }
    e2.override({ zodSchema: s2, jsonSchema: c, path: m2.path ?? [] });
  };
  for (let s2 of [...e2.seen.entries()].reverse()) a2(s2[0]);
  let t2 = {};
  if (e2.target === "draft-2020-12" ? t2.$schema = "https://json-schema.org/draft/2020-12/schema" : e2.target === "draft-07" ? t2.$schema = "http://json-schema.org/draft-07/schema#" : e2.target === "draft-04" ? t2.$schema = "http://json-schema.org/draft-04/schema#" : e2.target, (o2 = e2.external) != null && o2.uri) {
    let s2 = (u2 = e2.external.registry.get(i2)) == null ? void 0 : u2.id;
    if (!s2) throw Error("Schema is missing an `id` property");
    t2.$id = e2.external.uri(s2);
  }
  Object.assign(t2, n.def ?? n.schema);
  let r2 = ((d = e2.external) == null ? void 0 : d.defs) ?? {};
  for (let s2 of e2.seen.entries()) {
    let m2 = s2[1];
    m2.def && m2.defId && (r2[m2.defId] = m2.def);
  }
  e2.external || Object.keys(r2).length > 0 && (e2.target === "draft-2020-12" ? t2.$defs = r2 : t2.definitions = r2);
  try {
    let s2 = JSON.parse(JSON.stringify(t2));
    return Object.defineProperty(s2, "~standard", { value: { ...i2["~standard"], jsonSchema: { input: Ke(i2, "input", e2.processors), output: Ke(i2, "output", e2.processors) } }, enumerable: false, writable: false }), s2;
  } catch {
    throw Error("Error converting schema to JSON.");
  }
}
function q(e2, i2) {
  let n = i2 ?? { seen: /* @__PURE__ */ new Set() };
  if (n.seen.has(e2)) return false;
  n.seen.add(e2);
  let a2 = e2._zod.def;
  if (a2.type === "transform") return true;
  if (a2.type === "array") return q(a2.element, n);
  if (a2.type === "set") return q(a2.valueType, n);
  if (a2.type === "lazy") return q(a2.getter(), n);
  if (a2.type === "promise" || a2.type === "optional" || a2.type === "nonoptional" || a2.type === "nullable" || a2.type === "readonly" || a2.type === "default" || a2.type === "prefault") return q(a2.innerType, n);
  if (a2.type === "intersection") return q(a2.left, n) || q(a2.right, n);
  if (a2.type === "record" || a2.type === "map") return q(a2.keyType, n) || q(a2.valueType, n);
  if (a2.type === "pipe") return q(a2.in, n) || q(a2.out, n);
  if (a2.type === "object") {
    for (let t2 in a2.shape) if (q(a2.shape[t2], n)) return true;
    return false;
  }
  if (a2.type === "union") {
    for (let t2 of a2.options) if (q(t2, n)) return true;
    return false;
  }
  if (a2.type === "tuple") {
    for (let t2 of a2.items) if (q(t2, n)) return true;
    return !!(a2.rest && q(a2.rest, n));
  }
  return false;
}
var Rs = (e2, i2 = {}) => (n) => {
  let a2 = Ae({ ...n, processors: i2 });
  return O(e2, a2), Re(a2, e2), Ce(a2, e2);
}, Ke = (e2, i2, n = {}) => (a2) => {
  let { libraryOptions: t2, target: r2 } = a2 ?? {}, o2 = Ae({ ...t2 ?? {}, target: r2, io: i2, processors: n });
  return O(e2, o2), Re(o2, e2), Ce(o2, e2);
}, Xp = { guid: "uuid", url: "uri", datetime: "date-time", json_string: "json-string", regex: "" }, Cs = (e2, i2, n, a2) => {
  let t2 = n;
  t2.type = "string";
  let { minimum: r2, maximum: o2, format: u2, patterns: d, contentEncoding: s2 } = e2._zod.bag;
  if (typeof r2 == "number" && (t2.minLength = r2), typeof o2 == "number" && (t2.maxLength = o2), u2 && (t2.format = Xp[u2] ?? u2, t2.format === "" && delete t2.format, u2 === "time" && delete t2.format), s2 && (t2.contentEncoding = s2), d && d.size > 0) {
    let m2 = [...d];
    m2.length === 1 ? t2.pattern = m2[0].source : m2.length > 1 && (t2.allOf = [...m2.map((c) => ({ ...i2.target === "draft-07" || i2.target === "draft-04" || i2.target === "openapi-3.0" ? { type: "string" } : {}, pattern: c.source }))]);
  }
}, Ls = (e2, i2, n, a2) => {
  let t2 = n, { minimum: r2, maximum: o2, format: u2, multipleOf: d, exclusiveMaximum: s2, exclusiveMinimum: m2 } = e2._zod.bag;
  typeof u2 == "string" && u2.includes("int") ? t2.type = "integer" : t2.type = "number", typeof m2 == "number" && (i2.target === "draft-04" || i2.target === "openapi-3.0" ? (t2.minimum = m2, t2.exclusiveMinimum = true) : t2.exclusiveMinimum = m2), typeof r2 == "number" && (t2.minimum = r2, typeof m2 == "number" && i2.target !== "draft-04" && (m2 >= r2 ? delete t2.minimum : delete t2.exclusiveMinimum)), typeof s2 == "number" && (i2.target === "draft-04" || i2.target === "openapi-3.0" ? (t2.maximum = s2, t2.exclusiveMaximum = true) : t2.exclusiveMaximum = s2), typeof o2 == "number" && (t2.maximum = o2, typeof s2 == "number" && i2.target !== "draft-04" && (s2 <= o2 ? delete t2.maximum : delete t2.exclusiveMaximum)), typeof d == "number" && (t2.multipleOf = d);
}, Js = (e2, i2, n, a2) => {
  n.type = "boolean";
}, Ms = (e2, i2, n, a2) => {
  if (i2.unrepresentable === "throw") throw Error("BigInt cannot be represented in JSON Schema");
}, Fs = (e2, i2, n, a2) => {
  if (i2.unrepresentable === "throw") throw Error("Symbols cannot be represented in JSON Schema");
}, qs = (e2, i2, n, a2) => {
  i2.target === "openapi-3.0" ? (n.type = "string", n.nullable = true, n.enum = [null]) : n.type = "null";
}, Ws = (e2, i2, n, a2) => {
  if (i2.unrepresentable === "throw") throw Error("Undefined cannot be represented in JSON Schema");
}, Vs = (e2, i2, n, a2) => {
  if (i2.unrepresentable === "throw") throw Error("Void cannot be represented in JSON Schema");
}, Gs = (e2, i2, n, a2) => {
  n.not = {};
}, Ks = (e2, i2, n, a2) => {
}, Bs = (e2, i2, n, a2) => {
}, Hs = (e2, i2, n, a2) => {
  if (i2.unrepresentable === "throw") throw Error("Date cannot be represented in JSON Schema");
}, Xs = (e2, i2, n, a2) => {
  let t2 = e2._zod.def, r2 = Li(t2.entries);
  r2.every((o2) => typeof o2 == "number") && (n.type = "number"), r2.every((o2) => typeof o2 == "string") && (n.type = "string"), n.enum = r2;
}, Ys = (e2, i2, n, a2) => {
  let t2 = e2._zod.def, r2 = [];
  for (let o2 of t2.values) if (o2 === void 0) {
    if (i2.unrepresentable === "throw") throw Error("Literal `undefined` cannot be represented in JSON Schema");
  } else if (typeof o2 == "bigint") {
    if (i2.unrepresentable === "throw") throw Error("BigInt literals cannot be represented in JSON Schema");
    r2.push(Number(o2));
  } else r2.push(o2);
  if (r2.length !== 0) if (r2.length === 1) {
    let o2 = r2[0];
    n.type = o2 === null ? "null" : typeof o2, i2.target === "draft-04" || i2.target === "openapi-3.0" ? n.enum = [o2] : n.const = o2;
  } else
    r2.every((o2) => typeof o2 == "number") && (n.type = "number"), r2.every((o2) => typeof o2 == "string") && (n.type = "string"), r2.every((o2) => typeof o2 == "boolean") && (n.type = "boolean"), r2.every((o2) => o2 === null) && (n.type = "null"), n.enum = r2;
}, Qs = (e2, i2, n, a2) => {
  if (i2.unrepresentable === "throw") throw Error("NaN cannot be represented in JSON Schema");
}, el = (e2, i2, n, a2) => {
  let t2 = n, r2 = e2._zod.pattern;
  if (!r2) throw Error("Pattern not found in template literal");
  t2.type = "string", t2.pattern = r2.source;
}, tl = (e2, i2, n, a2) => {
  let t2 = n, r2 = { type: "string", format: "binary", contentEncoding: "binary" }, { minimum: o2, maximum: u2, mime: d } = e2._zod.bag;
  o2 !== void 0 && (r2.minLength = o2), u2 !== void 0 && (r2.maxLength = u2), d ? d.length === 1 ? (r2.contentMediaType = d[0], Object.assign(t2, r2)) : (Object.assign(t2, r2), t2.anyOf = d.map((s2) => ({ contentMediaType: s2 }))) : Object.assign(t2, r2);
}, il = (e2, i2, n, a2) => {
  n.type = "boolean";
}, nl = (e2, i2, n, a2) => {
  if (i2.unrepresentable === "throw") throw Error("Custom types cannot be represented in JSON Schema");
}, rl = (e2, i2, n, a2) => {
  if (i2.unrepresentable === "throw") throw Error("Function types cannot be represented in JSON Schema");
}, al = (e2, i2, n, a2) => {
  if (i2.unrepresentable === "throw") throw Error("Transforms cannot be represented in JSON Schema");
}, ol = (e2, i2, n, a2) => {
  if (i2.unrepresentable === "throw") throw Error("Map cannot be represented in JSON Schema");
}, ul = (e2, i2, n, a2) => {
  if (i2.unrepresentable === "throw") throw Error("Set cannot be represented in JSON Schema");
}, sl = (e2, i2, n, a2) => {
  let t2 = n, r2 = e2._zod.def, { minimum: o2, maximum: u2 } = e2._zod.bag;
  typeof o2 == "number" && (t2.minItems = o2), typeof u2 == "number" && (t2.maxItems = u2), t2.type = "array", t2.items = O(r2.element, i2, { ...a2, path: [...a2.path, "items"] });
}, ll = (e2, i2, n, a2) => {
  var s2;
  let t2 = n, r2 = e2._zod.def;
  t2.type = "object", t2.properties = {};
  let o2 = r2.shape;
  for (let m2 in o2) t2.properties[m2] = O(o2[m2], i2, { ...a2, path: [...a2.path, "properties", m2] });
  let u2 = new Set(Object.keys(o2)), d = new Set([...u2].filter((m2) => {
    let c = r2.shape[m2]._zod;
    return i2.io === "input" ? c.optin === void 0 : c.optout === void 0;
  }));
  d.size > 0 && (t2.required = Array.from(d)), ((s2 = r2.catchall) == null ? void 0 : s2._zod.def.type) === "never" ? t2.additionalProperties = false : r2.catchall ? r2.catchall && (t2.additionalProperties = O(r2.catchall, i2, { ...a2, path: [...a2.path, "additionalProperties"] })) : i2.io === "output" && (t2.additionalProperties = false);
}, Rn = (e2, i2, n, a2) => {
  let t2 = e2._zod.def, r2 = t2.inclusive === false, o2 = t2.options.map((u2, d) => O(u2, i2, { ...a2, path: [...a2.path, r2 ? "oneOf" : "anyOf", d] }));
  r2 ? n.oneOf = o2 : n.anyOf = o2;
}, dl = (e2, i2, n, a2) => {
  let t2 = e2._zod.def, r2 = O(t2.left, i2, { ...a2, path: [...a2.path, "allOf", 0] }), o2 = O(t2.right, i2, { ...a2, path: [...a2.path, "allOf", 1] }), u2 = (s2) => "allOf" in s2 && Object.keys(s2).length === 1, d = [...u2(r2) ? r2.allOf : [r2], ...u2(o2) ? o2.allOf : [o2]];
  n.allOf = d;
}, cl = (e2, i2, n, a2) => {
  let t2 = n, r2 = e2._zod.def;
  t2.type = "array";
  let o2 = i2.target === "draft-2020-12" ? "prefixItems" : "items", u2 = i2.target === "draft-2020-12" || i2.target === "openapi-3.0" ? "items" : "additionalItems", d = r2.items.map((p2, $2) => O(p2, i2, { ...a2, path: [...a2.path, o2, $2] })), s2 = r2.rest ? O(r2.rest, i2, { ...a2, path: [...a2.path, u2, ...i2.target === "openapi-3.0" ? [r2.items.length] : []] }) : null;
  i2.target === "draft-2020-12" ? (t2.prefixItems = d, s2 && (t2.items = s2)) : i2.target === "openapi-3.0" ? (t2.items = { anyOf: d }, s2 && t2.items.anyOf.push(s2), t2.minItems = d.length, !s2 && (t2.maxItems = d.length)) : (t2.items = d, s2 && (t2.additionalItems = s2));
  let { minimum: m2, maximum: c } = e2._zod.bag;
  typeof m2 == "number" && (t2.minItems = m2), typeof c == "number" && (t2.maxItems = c);
}, ml = (e2, i2, n, a2) => {
  var s2;
  let t2 = n, r2 = e2._zod.def;
  t2.type = "object";
  let o2 = r2.keyType, u2 = (s2 = o2._zod.bag) == null ? void 0 : s2.patterns;
  if (r2.mode === "loose" && u2 && u2.size > 0) {
    let m2 = O(r2.valueType, i2, { ...a2, path: [...a2.path, "patternProperties", "*"] });
    t2.patternProperties = {};
    for (let c of u2) t2.patternProperties[c.source] = m2;
  } else
    (i2.target === "draft-07" || i2.target === "draft-2020-12") && (t2.propertyNames = O(r2.keyType, i2, { ...a2, path: [...a2.path, "propertyNames"] })), t2.additionalProperties = O(r2.valueType, i2, { ...a2, path: [...a2.path, "additionalProperties"] });
  let d = o2._zod.values;
  if (d) {
    let m2 = [...d].filter((c) => typeof c == "string" || typeof c == "number");
    m2.length > 0 && (t2.required = m2);
  }
}, fl = (e2, i2, n, a2) => {
  let t2 = e2._zod.def, r2 = O(t2.innerType, i2, a2), o2 = i2.seen.get(e2);
  i2.target === "openapi-3.0" ? (o2.ref = t2.innerType, n.nullable = true) : n.anyOf = [r2, { type: "null" }];
}, pl = (e2, i2, n, a2) => {
  let t2 = e2._zod.def;
  O(t2.innerType, i2, a2);
  let r2 = i2.seen.get(e2);
  r2.ref = t2.innerType;
}, vl = (e2, i2, n, a2) => {
  let t2 = e2._zod.def;
  O(t2.innerType, i2, a2);
  let r2 = i2.seen.get(e2);
  r2.ref = t2.innerType, n.default = JSON.parse(JSON.stringify(t2.defaultValue));
}, gl = (e2, i2, n, a2) => {
  let t2 = e2._zod.def;
  O(t2.innerType, i2, a2);
  let r2 = i2.seen.get(e2);
  r2.ref = t2.innerType, i2.io === "input" && (n._prefault = JSON.parse(JSON.stringify(t2.defaultValue)));
}, hl = (e2, i2, n, a2) => {
  let t2 = e2._zod.def;
  O(t2.innerType, i2, a2);
  let r2 = i2.seen.get(e2);
  r2.ref = t2.innerType;
  let o2;
  try {
    o2 = t2.catchValue(void 0);
  } catch {
    throw Error("Dynamic catch values are not supported in JSON Schema");
  }
  n.default = o2;
}, $l = (e2, i2, n, a2) => {
  let t2 = e2._zod.def, r2 = i2.io === "input" ? t2.in._zod.def.type === "transform" ? t2.out : t2.in : t2.out;
  O(r2, i2, a2);
  let o2 = i2.seen.get(e2);
  o2.ref = r2;
}, bl = (e2, i2, n, a2) => {
  let t2 = e2._zod.def;
  O(t2.innerType, i2, a2);
  let r2 = i2.seen.get(e2);
  r2.ref = t2.innerType, n.readOnly = true;
}, yl = (e2, i2, n, a2) => {
  let t2 = e2._zod.def;
  O(t2.innerType, i2, a2);
  let r2 = i2.seen.get(e2);
  r2.ref = t2.innerType;
}, Cn = (e2, i2, n, a2) => {
  let t2 = e2._zod.def;
  O(t2.innerType, i2, a2);
  let r2 = i2.seen.get(e2);
  r2.ref = t2.innerType;
}, _l = (e2, i2, n, a2) => {
  let t2 = e2._zod.innerType;
  O(t2, i2, a2);
  let r2 = i2.seen.get(e2);
  r2.ref = t2;
}, Ri = { string: Cs, number: Ls, boolean: Js, bigint: Ms, symbol: Fs, null: qs, undefined: Ws, void: Vs, never: Gs, any: Ks, unknown: Bs, date: Hs, enum: Xs, literal: Ys, nan: Qs, template_literal: el, file: tl, success: il, custom: nl, function: rl, transform: al, map: ol, set: ul, array: sl, object: ll, union: Rn, intersection: dl, tuple: cl, record: ml, nullable: fl, nonoptional: pl, default: vl, prefault: gl, catch: hl, pipe: $l, readonly: bl, promise: yl, optional: Cn, lazy: _l };
function kl(e2, i2) {
  if ("_idmap" in e2) {
    let a2 = e2, t2 = Ae({ ...i2, processors: Ri }), r2 = {};
    for (let d of a2._idmap.entries()) {
      let [s2, m2] = d;
      O(m2, t2);
    }
    let o2 = {}, u2 = { registry: a2, uri: i2 == null ? void 0 : i2.uri, defs: r2 };
    t2.external = u2;
    for (let d of a2._idmap.entries()) {
      let [s2, m2] = d;
      Re(t2, m2), o2[s2] = Ce(t2, m2);
    }
    if (Object.keys(r2).length > 0) {
      let d = t2.target === "draft-2020-12" ? "$defs" : "definitions";
      o2.__shared = { [d]: r2 };
    }
    return { schemas: o2 };
  }
  let n = Ae({ ...i2, processors: Ri });
  return O(e2, n), Re(n, e2), Ce(n, e2);
}
class Yp {
  get metadataRegistry() {
    return this.ctx.metadataRegistry;
  }
  get target() {
    return this.ctx.target;
  }
  get unrepresentable() {
    return this.ctx.unrepresentable;
  }
  get override() {
    return this.ctx.override;
  }
  get io() {
    return this.ctx.io;
  }
  get counter() {
    return this.ctx.counter;
  }
  set counter(i2) {
    this.ctx.counter = i2;
  }
  get seen() {
    return this.ctx.seen;
  }
  constructor(i2) {
    let n = (i2 == null ? void 0 : i2.target) ?? "draft-2020-12";
    n === "draft-4" && (n = "draft-04"), n === "draft-7" && (n = "draft-07"), this.ctx = Ae({ processors: Ri, target: n, ...(i2 == null ? void 0 : i2.metadata) && { metadata: i2.metadata }, ...(i2 == null ? void 0 : i2.unrepresentable) && { unrepresentable: i2.unrepresentable }, ...(i2 == null ? void 0 : i2.override) && { override: i2.override }, ...(i2 == null ? void 0 : i2.io) && { io: i2.io } });
  }
  process(i2, n = { path: [], schemaPath: [] }) {
    return O(i2, this.ctx, n);
  }
  emit(i2, n) {
    n && (n.cycles && (this.ctx.cycles = n.cycles), n.reused && (this.ctx.reused = n.reused), n.external && (this.ctx.external = n.external)), Re(this.ctx, i2);
    let a2 = Ce(this.ctx, i2), { "~standard": t2, ...r2 } = a2;
    return r2;
  }
}
var Qp = {}, Il = {};
le(Il, { xor: () => Nd, xid: () => td, void: () => Sd, uuidv7: () => Gl, uuidv6: () => Vl, uuidv4: () => Wl, uuid: () => ql, url: () => Kl, unknown: () => we, union: () => yi, undefined: () => xd, ulid: () => ed, uint64: () => kd, uint32: () => bd, tuple: () => sr, transform: () => ki, templateLiteral: () => Wd, symbol: () => Id, superRefine: () => Er, success: () => Md, stringbool: () => Yd, stringFormat: () => md, string: () => Pt, strictObject: () => jd, set: () => Ad, refine: () => Dr, record: () => lr, readonly: () => Ur, promise: () => Vd, preprocess: () => ec, prefault: () => _r, pipe: () => Ye, partialRecord: () => Dd, optional: () => He, object: () => Od, number: () => Vn, nullish: () => Jd, nullable: () => Xe, null: () => Xn, nonoptional: () => kr, never: () => $i, nativeEnum: () => Rd, nanoid: () => Xl, nan: () => Fd, meta: () => Hd, map: () => Td, mac: () => rd, looseRecord: () => Ed, looseObject: () => Zd, literal: () => Cd, lazy: () => Zr, ksuid: () => id, keyof: () => Ud, jwt: () => cd, json: () => Qd, ipv6: () => ad, ipv4: () => nd, intersection: () => or, int64: () => _d, int32: () => $d, int: () => Dt, instanceof: () => Xd, httpUrl: () => Bl, hostname: () => fd, hex: () => pd, hash: () => vd, guid: () => Fl, function: () => Et, float64: () => hd, float32: () => gd, file: () => Ld, exactOptional: () => gr, enum: () => _i, emoji: () => Hl, email: () => Ml, e164: () => dd, discriminatedUnion: () => Pd, describe: () => Bd, date: () => zd, custom: () => Kd, cuid2: () => Ql, cuid: () => Yl, codec: () => qd, cidrv6: () => ud, cidrv4: () => od, check: () => Gd, catch: () => wr, boolean: () => Gn, bigint: () => yd, base64url: () => ld, base64: () => sd, array: () => $t, any: () => wd, _function: () => Et, _default: () => br, _ZodString: () => ei, ZodXor: () => nr, ZodXID: () => ui, ZodVoid: () => tr, ZodUnknown: () => Qn, ZodUnion: () => yt, ZodUndefined: () => Bn, ZodUUID: () => oe, ZodURL: () => pt, ZodULID: () => oi, ZodType: () => I, ZodTuple: () => ur, ZodTransform: () => pr, ZodTemplateLiteral: () => Or, ZodSymbol: () => Kn, ZodSuccess: () => Ir, ZodStringFormat: () => N, ZodString: () => ft, ZodSet: () => cr, ZodRecord: () => _t, ZodReadonly: () => zr, ZodPromise: () => Nr, ZodPrefault: () => yr, ZodPipe: () => wi, ZodOptional: () => Ii, ZodObject: () => bt, ZodNumberFormat: () => Ue, ZodNumber: () => vt, ZodNullable: () => hr, ZodNull: () => Hn, ZodNonOptional: () => xi, ZodNever: () => er, ZodNanoID: () => ni, ZodNaN: () => Sr, ZodMap: () => dr, ZodMAC: () => Wn, ZodLiteral: () => mr, ZodLazy: () => jr, ZodKSUID: () => si, ZodJWT: () => gi, ZodIntersection: () => ar, ZodIPv6: () => di, ZodIPv4: () => li, ZodGUID: () => Be, ZodFunction: () => Pr, ZodFile: () => fr, ZodExactOptional: () => vr, ZodEnum: () => Le, ZodEmoji: () => ii, ZodEmail: () => ti, ZodE164: () => vi, ZodDiscriminatedUnion: () => rr, ZodDefault: () => $r, ZodDate: () => bi, ZodCustomStringFormat: () => Me, ZodCustom: () => kt, ZodCodec: () => Si, ZodCatch: () => xr, ZodCUID2: () => ai, ZodCUID: () => ri, ZodCIDRv6: () => mi, ZodCIDRv4: () => ci, ZodBoolean: () => gt, ZodBigIntFormat: () => hi, ZodBigInt: () => ht, ZodBase64URL: () => pi, ZodBase64: () => fi, ZodArray: () => ir, ZodAny: () => Yn });
var xl = {};
le(xl, { uppercase: () => qt, trim: () => Ht, toUpperCase: () => Yt, toLowerCase: () => Xt, startsWith: () => Vt, slugify: () => Qt, size: () => lt, regex: () => Mt, property: () => An, positive: () => Pn, overwrite: () => ce, normalize: () => Bt, nonpositive: () => En, nonnegative: () => Tn, negative: () => Dn, multipleOf: () => Te, minSize: () => ve, minLength: () => xe, mime: () => Kt, maxSize: () => Je, maxLength: () => dt, lte: () => ee, lt: () => fe, lowercase: () => Ft, length: () => ct, includes: () => Wt, gte: () => V, gt: () => pe, endsWith: () => Gt });
var Ln = {};
le(Ln, { time: () => zl, duration: () => Ul, datetime: () => wl, date: () => Sl, ZodISOTime: () => Fn, ZodISODuration: () => qn, ZodISODateTime: () => Jn, ZodISODate: () => Mn });
var Jn = f("ZodISODateTime", (e2, i2) => {
  qo.init(e2, i2), N.init(e2, i2);
});
function wl(e2) {
  return is(Jn, e2);
}
var Mn = f("ZodISODate", (e2, i2) => {
  Wo.init(e2, i2), N.init(e2, i2);
});
function Sl(e2) {
  return ns(Mn, e2);
}
var Fn = f("ZodISOTime", (e2, i2) => {
  Vo.init(e2, i2), N.init(e2, i2);
});
function zl(e2) {
  return rs(Fn, e2);
}
var qn = f("ZodISODuration", (e2, i2) => {
  Go.init(e2, i2), N.init(e2, i2);
});
function Ul(e2) {
  return as(qn, e2);
}
var Ol = (e2, i2) => {
  Mi.init(e2, i2), e2.name = "ZodError", Object.defineProperties(e2, { format: { value: (n) => qi(e2, n) }, flatten: { value: (n) => Fi(e2, n) }, addIssue: { value: (n) => {
    e2.issues.push(n), e2.message = JSON.stringify(e2.issues, Ut, 2);
  } }, addIssues: { value: (n) => {
    e2.issues.push(...n), e2.message = JSON.stringify(e2.issues, Ut, 2);
  } }, isEmpty: { get() {
    return e2.issues.length === 0;
  } } });
}, ev = f("ZodError", Ol), B = f("ZodError", Ol, { Parent: Error }), jl = tt(B), Zl = it(B), Nl = nt(B), Pl = rt(B), Dl = Wi(B), El = Vi(B), Tl = Gi(B), Al = Ki(B), Rl = Bi(B), Cl = Hi(B), Ll = Xi(B), Jl = Yi(B), I = f("ZodType", (e2, i2) => (k.init(e2, i2), Object.assign(e2["~standard"], { jsonSchema: { input: Ke(e2, "input"), output: Ke(e2, "output") } }), e2.toJSONSchema = Rs(e2, {}), e2.def = i2, e2.type = i2.type, Object.defineProperty(e2, "_def", { value: i2 }), e2.check = (...n) => e2.clone(S.mergeDefs(i2, { checks: [...i2.checks ?? [], ...n.map((a2) => typeof a2 == "function" ? { _zod: { check: a2, def: { check: "custom" }, onattach: [] } } : a2)] }), { parent: true }), e2.with = e2.check, e2.clone = (n, a2) => ie(e2, n, a2), e2.brand = () => e2, e2.register = (n, a2) => (n.add(e2, a2), e2), e2.parse = (n, a2) => jl(e2, n, a2, { callee: e2.parse }), e2.safeParse = (n, a2) => Nl(e2, n, a2), e2.parseAsync = async (n, a2) => Zl(e2, n, a2, { callee: e2.parseAsync }), e2.safeParseAsync = async (n, a2) => Pl(e2, n, a2), e2.spa = e2.safeParseAsync, e2.encode = (n, a2) => Dl(e2, n, a2), e2.decode = (n, a2) => El(e2, n, a2), e2.encodeAsync = async (n, a2) => Tl(e2, n, a2), e2.decodeAsync = async (n, a2) => Al(e2, n, a2), e2.safeEncode = (n, a2) => Rl(e2, n, a2), e2.safeDecode = (n, a2) => Cl(e2, n, a2), e2.safeEncodeAsync = async (n, a2) => Ll(e2, n, a2), e2.safeDecodeAsync = async (n, a2) => Jl(e2, n, a2), e2.refine = (n, a2) => e2.check(Dr(n, a2)), e2.superRefine = (n) => e2.check(Er(n)), e2.overwrite = (n) => e2.check(ce(n)), e2.optional = () => He(e2), e2.exactOptional = () => gr(e2), e2.nullable = () => Xe(e2), e2.nullish = () => He(Xe(e2)), e2.nonoptional = (n) => kr(e2, n), e2.array = () => $t(e2), e2.or = (n) => yi([e2, n]), e2.and = (n) => or(e2, n), e2.transform = (n) => Ye(e2, ki(n)), e2.default = (n) => br(e2, n), e2.prefault = (n) => _r(e2, n), e2.catch = (n) => wr(e2, n), e2.pipe = (n) => Ye(e2, n), e2.readonly = () => Ur(e2), e2.describe = (n) => {
  let a2 = e2.clone();
  return Q.add(a2, { description: n }), a2;
}, Object.defineProperty(e2, "description", { get() {
  var n;
  return (n = Q.get(e2)) == null ? void 0 : n.description;
}, configurable: true }), e2.meta = (...n) => {
  if (n.length === 0) return Q.get(e2);
  let a2 = e2.clone();
  return Q.add(a2, n[0]), a2;
}, e2.isOptional = () => e2.safeParse(void 0).success, e2.isNullable = () => e2.safeParse(null).success, e2.apply = (n) => n(e2), e2)), ei = f("_ZodString", (e2, i2) => {
  st.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (a2, t2, r2) => Cs(e2, a2, t2);
  let n = e2._zod.bag;
  e2.format = n.format ?? null, e2.minLength = n.minimum ?? null, e2.maxLength = n.maximum ?? null, e2.regex = (...a2) => e2.check(Mt(...a2)), e2.includes = (...a2) => e2.check(Wt(...a2)), e2.startsWith = (...a2) => e2.check(Vt(...a2)), e2.endsWith = (...a2) => e2.check(Gt(...a2)), e2.min = (...a2) => e2.check(xe(...a2)), e2.max = (...a2) => e2.check(dt(...a2)), e2.length = (...a2) => e2.check(ct(...a2)), e2.nonempty = (...a2) => e2.check(xe(1, ...a2)), e2.lowercase = (a2) => e2.check(Ft(a2)), e2.uppercase = (a2) => e2.check(qt(a2)), e2.trim = () => e2.check(Ht()), e2.normalize = (...a2) => e2.check(Bt(...a2)), e2.toLowerCase = () => e2.check(Xt()), e2.toUpperCase = () => e2.check(Yt()), e2.slugify = () => e2.check(Qt());
}), ft = f("ZodString", (e2, i2) => {
  st.init(e2, i2), ei.init(e2, i2), e2.email = (n) => e2.check(fn(ti, n)), e2.url = (n) => e2.check(Jt(pt, n)), e2.jwt = (n) => e2.check(Nn(gi, n)), e2.emoji = (n) => e2.check($n(ii, n)), e2.guid = (n) => e2.check(Nt(Be, n)), e2.uuid = (n) => e2.check(pn(oe, n)), e2.uuidv4 = (n) => e2.check(vn(oe, n)), e2.uuidv6 = (n) => e2.check(gn(oe, n)), e2.uuidv7 = (n) => e2.check(hn(oe, n)), e2.nanoid = (n) => e2.check(bn(ni, n)), e2.guid = (n) => e2.check(Nt(Be, n)), e2.cuid = (n) => e2.check(yn(ri, n)), e2.cuid2 = (n) => e2.check(_n(ai, n)), e2.ulid = (n) => e2.check(kn(oi, n)), e2.base64 = (n) => e2.check(On(fi, n)), e2.base64url = (n) => e2.check(jn(pi, n)), e2.xid = (n) => e2.check(In(ui, n)), e2.ksuid = (n) => e2.check(xn(si, n)), e2.ipv4 = (n) => e2.check(wn(li, n)), e2.ipv6 = (n) => e2.check(Sn(di, n)), e2.cidrv4 = (n) => e2.check(zn(ci, n)), e2.cidrv6 = (n) => e2.check(Un(mi, n)), e2.e164 = (n) => e2.check(Zn(vi, n)), e2.datetime = (n) => e2.check(wl(n)), e2.date = (n) => e2.check(Sl(n)), e2.time = (n) => e2.check(zl(n)), e2.duration = (n) => e2.check(Ul(n));
});
function Pt(e2) {
  return Yu(ft, e2);
}
var N = f("ZodStringFormat", (e2, i2) => {
  Z.init(e2, i2), ei.init(e2, i2);
}), ti = f("ZodEmail", (e2, i2) => {
  Eo.init(e2, i2), N.init(e2, i2);
});
function Ml(e2) {
  return fn(ti, e2);
}
var Be = f("ZodGUID", (e2, i2) => {
  Po.init(e2, i2), N.init(e2, i2);
});
function Fl(e2) {
  return Nt(Be, e2);
}
var oe = f("ZodUUID", (e2, i2) => {
  Do.init(e2, i2), N.init(e2, i2);
});
function ql(e2) {
  return pn(oe, e2);
}
function Wl(e2) {
  return vn(oe, e2);
}
function Vl(e2) {
  return gn(oe, e2);
}
function Gl(e2) {
  return hn(oe, e2);
}
var pt = f("ZodURL", (e2, i2) => {
  To.init(e2, i2), N.init(e2, i2);
});
function Kl(e2) {
  return Jt(pt, e2);
}
function Bl(e2) {
  return Jt(pt, { protocol: /^https?$/, hostname: ze.domain, ...S.normalizeParams(e2) });
}
var ii = f("ZodEmoji", (e2, i2) => {
  Ao.init(e2, i2), N.init(e2, i2);
});
function Hl(e2) {
  return $n(ii, e2);
}
var ni = f("ZodNanoID", (e2, i2) => {
  Ro.init(e2, i2), N.init(e2, i2);
});
function Xl(e2) {
  return bn(ni, e2);
}
var ri = f("ZodCUID", (e2, i2) => {
  Co.init(e2, i2), N.init(e2, i2);
});
function Yl(e2) {
  return yn(ri, e2);
}
var ai = f("ZodCUID2", (e2, i2) => {
  Lo.init(e2, i2), N.init(e2, i2);
});
function Ql(e2) {
  return _n(ai, e2);
}
var oi = f("ZodULID", (e2, i2) => {
  Jo.init(e2, i2), N.init(e2, i2);
});
function ed(e2) {
  return kn(oi, e2);
}
var ui = f("ZodXID", (e2, i2) => {
  Mo.init(e2, i2), N.init(e2, i2);
});
function td(e2) {
  return In(ui, e2);
}
var si = f("ZodKSUID", (e2, i2) => {
  Fo.init(e2, i2), N.init(e2, i2);
});
function id(e2) {
  return xn(si, e2);
}
var li = f("ZodIPv4", (e2, i2) => {
  Ko.init(e2, i2), N.init(e2, i2);
});
function nd(e2) {
  return wn(li, e2);
}
var Wn = f("ZodMAC", (e2, i2) => {
  Ho.init(e2, i2), N.init(e2, i2);
});
function rd(e2) {
  return es(Wn, e2);
}
var di = f("ZodIPv6", (e2, i2) => {
  Bo.init(e2, i2), N.init(e2, i2);
});
function ad(e2) {
  return Sn(di, e2);
}
var ci = f("ZodCIDRv4", (e2, i2) => {
  Xo.init(e2, i2), N.init(e2, i2);
});
function od(e2) {
  return zn(ci, e2);
}
var mi = f("ZodCIDRv6", (e2, i2) => {
  Yo.init(e2, i2), N.init(e2, i2);
});
function ud(e2) {
  return Un(mi, e2);
}
var fi = f("ZodBase64", (e2, i2) => {
  Qo.init(e2, i2), N.init(e2, i2);
});
function sd(e2) {
  return On(fi, e2);
}
var pi = f("ZodBase64URL", (e2, i2) => {
  tu.init(e2, i2), N.init(e2, i2);
});
function ld(e2) {
  return jn(pi, e2);
}
var vi = f("ZodE164", (e2, i2) => {
  iu.init(e2, i2), N.init(e2, i2);
});
function dd(e2) {
  return Zn(vi, e2);
}
var gi = f("ZodJWT", (e2, i2) => {
  ru.init(e2, i2), N.init(e2, i2);
});
function cd(e2) {
  return Nn(gi, e2);
}
var Me = f("ZodCustomStringFormat", (e2, i2) => {
  au.init(e2, i2), N.init(e2, i2);
});
function md(e2, i2, n = {}) {
  return mt(Me, e2, i2, n);
}
function fd(e2) {
  return mt(Me, "hostname", ze.hostname, e2);
}
function pd(e2) {
  return mt(Me, "hex", ze.hex, e2);
}
function vd(e2, i2) {
  let n = (i2 == null ? void 0 : i2.enc) ?? "hex", a2 = `${e2}_${n}`, t2 = ze[a2];
  if (!t2) throw Error(`Unrecognized hash format: ${a2}`);
  return mt(Me, a2, t2, i2);
}
var vt = f("ZodNumber", (e2, i2) => {
  an.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (a2, t2, r2) => Ls(e2, a2, t2), e2.gt = (a2, t2) => e2.check(pe(a2, t2)), e2.gte = (a2, t2) => e2.check(V(a2, t2)), e2.min = (a2, t2) => e2.check(V(a2, t2)), e2.lt = (a2, t2) => e2.check(fe(a2, t2)), e2.lte = (a2, t2) => e2.check(ee(a2, t2)), e2.max = (a2, t2) => e2.check(ee(a2, t2)), e2.int = (a2) => e2.check(Dt(a2)), e2.safe = (a2) => e2.check(Dt(a2)), e2.positive = (a2) => e2.check(pe(0, a2)), e2.nonnegative = (a2) => e2.check(V(0, a2)), e2.negative = (a2) => e2.check(fe(0, a2)), e2.nonpositive = (a2) => e2.check(ee(0, a2)), e2.multipleOf = (a2, t2) => e2.check(Te(a2, t2)), e2.step = (a2, t2) => e2.check(Te(a2, t2)), e2.finite = () => e2;
  let n = e2._zod.bag;
  e2.minValue = Math.max(n.minimum ?? Number.NEGATIVE_INFINITY, n.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null, e2.maxValue = Math.min(n.maximum ?? Number.POSITIVE_INFINITY, n.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null, e2.isInt = (n.format ?? "").includes("int") || Number.isSafeInteger(n.multipleOf ?? 0.5), e2.isFinite = true, e2.format = n.format ?? null;
});
function Vn(e2) {
  return os(vt, e2);
}
var Ue = f("ZodNumberFormat", (e2, i2) => {
  ou.init(e2, i2), vt.init(e2, i2);
});
function Dt(e2) {
  return ss(Ue, e2);
}
function gd(e2) {
  return ls(Ue, e2);
}
function hd(e2) {
  return ds(Ue, e2);
}
function $d(e2) {
  return cs(Ue, e2);
}
function bd(e2) {
  return ms(Ue, e2);
}
var gt = f("ZodBoolean", (e2, i2) => {
  on.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Js(e2, n, a2);
});
function Gn(e2) {
  return fs(gt, e2);
}
var ht = f("ZodBigInt", (e2, i2) => {
  un.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (a2, t2, r2) => Ms(e2, a2), e2.gte = (a2, t2) => e2.check(V(a2, t2)), e2.min = (a2, t2) => e2.check(V(a2, t2)), e2.gt = (a2, t2) => e2.check(pe(a2, t2)), e2.gte = (a2, t2) => e2.check(V(a2, t2)), e2.min = (a2, t2) => e2.check(V(a2, t2)), e2.lt = (a2, t2) => e2.check(fe(a2, t2)), e2.lte = (a2, t2) => e2.check(ee(a2, t2)), e2.max = (a2, t2) => e2.check(ee(a2, t2)), e2.positive = (a2) => e2.check(pe(BigInt(0), a2)), e2.negative = (a2) => e2.check(fe(BigInt(0), a2)), e2.nonpositive = (a2) => e2.check(ee(BigInt(0), a2)), e2.nonnegative = (a2) => e2.check(V(BigInt(0), a2)), e2.multipleOf = (a2, t2) => e2.check(Te(a2, t2));
  let n = e2._zod.bag;
  e2.minValue = n.minimum ?? null, e2.maxValue = n.maximum ?? null, e2.format = n.format ?? null;
});
function yd(e2) {
  return vs(ht, e2);
}
var hi = f("ZodBigIntFormat", (e2, i2) => {
  uu.init(e2, i2), ht.init(e2, i2);
});
function _d(e2) {
  return hs(hi, e2);
}
function kd(e2) {
  return $s(hi, e2);
}
var Kn = f("ZodSymbol", (e2, i2) => {
  su.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Fs(e2, n);
});
function Id(e2) {
  return bs(Kn, e2);
}
var Bn = f("ZodUndefined", (e2, i2) => {
  lu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Ws(e2, n);
});
function xd(e2) {
  return ys(Bn, e2);
}
var Hn = f("ZodNull", (e2, i2) => {
  du.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => qs(e2, n, a2);
});
function Xn(e2) {
  return _s(Hn, e2);
}
var Yn = f("ZodAny", (e2, i2) => {
  cu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Ks();
});
function wd() {
  return ks(Yn);
}
var Qn = f("ZodUnknown", (e2, i2) => {
  mu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Bs();
});
function we() {
  return Is(Qn);
}
var er = f("ZodNever", (e2, i2) => {
  fu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Gs(e2, n, a2);
});
function $i(e2) {
  return xs(er, e2);
}
var tr = f("ZodVoid", (e2, i2) => {
  pu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Vs(e2, n);
});
function Sd(e2) {
  return ws(tr, e2);
}
var bi = f("ZodDate", (e2, i2) => {
  vu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (a2, t2, r2) => Hs(e2, a2), e2.min = (a2, t2) => e2.check(V(a2, t2)), e2.max = (a2, t2) => e2.check(ee(a2, t2));
  let n = e2._zod.bag;
  e2.minDate = n.minimum ? new Date(n.minimum) : null, e2.maxDate = n.maximum ? new Date(n.maximum) : null;
});
function zd(e2) {
  return Ss(bi, e2);
}
var ir = f("ZodArray", (e2, i2) => {
  gu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => sl(e2, n, a2, t2), e2.element = i2.element, e2.min = (n, a2) => e2.check(xe(n, a2)), e2.nonempty = (n) => e2.check(xe(1, n)), e2.max = (n, a2) => e2.check(dt(n, a2)), e2.length = (n, a2) => e2.check(ct(n, a2)), e2.unwrap = () => e2.element;
});
function $t(e2, i2) {
  return Os(ir, e2, i2);
}
function Ud(e2) {
  let i2 = e2._zod.def.shape;
  return _i(Object.keys(i2));
}
var bt = f("ZodObject", (e2, i2) => {
  yu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => ll(e2, n, a2, t2), S.defineLazy(e2, "shape", () => i2.shape), e2.keyof = () => _i(Object.keys(e2._zod.def.shape)), e2.catchall = (n) => e2.clone({ ...e2._zod.def, catchall: n }), e2.passthrough = () => e2.clone({ ...e2._zod.def, catchall: we() }), e2.loose = () => e2.clone({ ...e2._zod.def, catchall: we() }), e2.strict = () => e2.clone({ ...e2._zod.def, catchall: $i() }), e2.strip = () => e2.clone({ ...e2._zod.def, catchall: void 0 }), e2.extend = (n) => S.extend(e2, n), e2.safeExtend = (n) => S.safeExtend(e2, n), e2.merge = (n) => S.merge(e2, n), e2.pick = (n) => S.pick(e2, n), e2.omit = (n) => S.omit(e2, n), e2.partial = (...n) => S.partial(Ii, e2, n[0]), e2.required = (...n) => S.required(xi, e2, n[0]);
});
function Od(e2, i2) {
  let n = { type: "object", shape: e2 ?? {}, ...S.normalizeParams(i2) };
  return new bt(n);
}
function jd(e2, i2) {
  return new bt({ type: "object", shape: e2, catchall: $i(), ...S.normalizeParams(i2) });
}
function Zd(e2, i2) {
  return new bt({ type: "object", shape: e2, catchall: we(), ...S.normalizeParams(i2) });
}
var yt = f("ZodUnion", (e2, i2) => {
  Lt.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Rn(e2, n, a2, t2), e2.options = i2.options;
});
function yi(e2, i2) {
  return new yt({ type: "union", options: e2, ...S.normalizeParams(i2) });
}
var nr = f("ZodXor", (e2, i2) => {
  yt.init(e2, i2), _u.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Rn(e2, n, a2, t2), e2.options = i2.options;
});
function Nd(e2, i2) {
  return new nr({ type: "union", options: e2, inclusive: false, ...S.normalizeParams(i2) });
}
var rr = f("ZodDiscriminatedUnion", (e2, i2) => {
  yt.init(e2, i2), ku.init(e2, i2);
});
function Pd(e2, i2, n) {
  return new rr({ type: "union", options: i2, discriminator: e2, ...S.normalizeParams(n) });
}
var ar = f("ZodIntersection", (e2, i2) => {
  Iu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => dl(e2, n, a2, t2);
});
function or(e2, i2) {
  return new ar({ type: "intersection", left: e2, right: i2 });
}
var ur = f("ZodTuple", (e2, i2) => {
  sn.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => cl(e2, n, a2, t2), e2.rest = (n) => e2.clone({ ...e2._zod.def, rest: n });
});
function sr(e2, i2, n) {
  let a2 = i2 instanceof k, t2 = a2 ? n : i2;
  return new ur({ type: "tuple", items: e2, rest: a2 ? i2 : null, ...S.normalizeParams(t2) });
}
var _t = f("ZodRecord", (e2, i2) => {
  xu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => ml(e2, n, a2, t2), e2.keyType = i2.keyType, e2.valueType = i2.valueType;
});
function lr(e2, i2, n) {
  return new _t({ type: "record", keyType: e2, valueType: i2, ...S.normalizeParams(n) });
}
function Dd(e2, i2, n) {
  let a2 = ie(e2);
  return a2._zod.values = void 0, new _t({ type: "record", keyType: a2, valueType: i2, ...S.normalizeParams(n) });
}
function Ed(e2, i2, n) {
  return new _t({ type: "record", keyType: e2, valueType: i2, mode: "loose", ...S.normalizeParams(n) });
}
var dr = f("ZodMap", (e2, i2) => {
  wu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => ol(e2, n), e2.keyType = i2.keyType, e2.valueType = i2.valueType, e2.min = (...n) => e2.check(ve(...n)), e2.nonempty = (n) => e2.check(ve(1, n)), e2.max = (...n) => e2.check(Je(...n)), e2.size = (...n) => e2.check(lt(...n));
});
function Td(e2, i2, n) {
  return new dr({ type: "map", keyType: e2, valueType: i2, ...S.normalizeParams(n) });
}
var cr = f("ZodSet", (e2, i2) => {
  Su.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => ul(e2, n), e2.min = (...n) => e2.check(ve(...n)), e2.nonempty = (n) => e2.check(ve(1, n)), e2.max = (...n) => e2.check(Je(...n)), e2.size = (...n) => e2.check(lt(...n));
});
function Ad(e2, i2) {
  return new cr({ type: "set", valueType: e2, ...S.normalizeParams(i2) });
}
var Le = f("ZodEnum", (e2, i2) => {
  zu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (a2, t2, r2) => Xs(e2, a2, t2), e2.enum = i2.entries, e2.options = Object.values(i2.entries);
  let n = new Set(Object.keys(i2.entries));
  e2.extract = (a2, t2) => {
    let r2 = {};
    for (let o2 of a2) if (n.has(o2)) r2[o2] = i2.entries[o2];
    else throw Error(`Key ${o2} not found in enum`);
    return new Le({ ...i2, checks: [], ...S.normalizeParams(t2), entries: r2 });
  }, e2.exclude = (a2, t2) => {
    let r2 = { ...i2.entries };
    for (let o2 of a2) if (n.has(o2)) delete r2[o2];
    else throw Error(`Key ${o2} not found in enum`);
    return new Le({ ...i2, checks: [], ...S.normalizeParams(t2), entries: r2 });
  };
});
function _i(e2, i2) {
  let n = Array.isArray(e2) ? Object.fromEntries(e2.map((a2) => [a2, a2])) : e2;
  return new Le({ type: "enum", entries: n, ...S.normalizeParams(i2) });
}
function Rd(e2, i2) {
  return new Le({ type: "enum", entries: e2, ...S.normalizeParams(i2) });
}
var mr = f("ZodLiteral", (e2, i2) => {
  Uu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Ys(e2, n, a2), e2.values = new Set(i2.values), Object.defineProperty(e2, "value", { get() {
    if (i2.values.length > 1) throw Error("This schema contains multiple valid literal values. Use `.values` instead.");
    return i2.values[0];
  } });
});
function Cd(e2, i2) {
  return new mr({ type: "literal", values: Array.isArray(e2) ? e2 : [e2], ...S.normalizeParams(i2) });
}
var fr = f("ZodFile", (e2, i2) => {
  Ou.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => tl(e2, n, a2), e2.min = (n, a2) => e2.check(ve(n, a2)), e2.max = (n, a2) => e2.check(Je(n, a2)), e2.mime = (n, a2) => e2.check(Kt(Array.isArray(n) ? n : [n], a2));
});
function Ld(e2) {
  return js(fr, e2);
}
var pr = f("ZodTransform", (e2, i2) => {
  ju.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => al(e2, n), e2._zod.parse = (n, a2) => {
    if (a2.direction === "backward") throw new Tt(e2.constructor.name);
    n.addIssue = (r2) => {
      if (typeof r2 == "string") n.issues.push(S.issue(r2, n.value, i2));
      else {
        let o2 = r2;
        o2.fatal && (o2.continue = false), o2.code ?? (o2.code = "custom"), o2.input ?? (o2.input = n.value), o2.inst ?? (o2.inst = e2), n.issues.push(S.issue(o2));
      }
    };
    let t2 = i2.transform(n.value, n);
    return t2 instanceof Promise ? t2.then((r2) => (n.value = r2, n)) : (n.value = t2, n);
  };
});
function ki(e2) {
  return new pr({ type: "transform", transform: e2 });
}
var Ii = f("ZodOptional", (e2, i2) => {
  ln.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Cn(e2, n, a2, t2), e2.unwrap = () => e2._zod.def.innerType;
});
function He(e2) {
  return new Ii({ type: "optional", innerType: e2 });
}
var vr = f("ZodExactOptional", (e2, i2) => {
  Zu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Cn(e2, n, a2, t2), e2.unwrap = () => e2._zod.def.innerType;
});
function gr(e2) {
  return new vr({ type: "optional", innerType: e2 });
}
var hr = f("ZodNullable", (e2, i2) => {
  Nu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => fl(e2, n, a2, t2), e2.unwrap = () => e2._zod.def.innerType;
});
function Xe(e2) {
  return new hr({ type: "nullable", innerType: e2 });
}
function Jd(e2) {
  return He(Xe(e2));
}
var $r = f("ZodDefault", (e2, i2) => {
  Pu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => vl(e2, n, a2, t2), e2.unwrap = () => e2._zod.def.innerType, e2.removeDefault = e2.unwrap;
});
function br(e2, i2) {
  return new $r({ type: "default", innerType: e2, get defaultValue() {
    return typeof i2 == "function" ? i2() : S.shallowClone(i2);
  } });
}
var yr = f("ZodPrefault", (e2, i2) => {
  Du.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => gl(e2, n, a2, t2), e2.unwrap = () => e2._zod.def.innerType;
});
function _r(e2, i2) {
  return new yr({ type: "prefault", innerType: e2, get defaultValue() {
    return typeof i2 == "function" ? i2() : S.shallowClone(i2);
  } });
}
var xi = f("ZodNonOptional", (e2, i2) => {
  Eu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => pl(e2, n, a2, t2), e2.unwrap = () => e2._zod.def.innerType;
});
function kr(e2, i2) {
  return new xi({ type: "nonoptional", innerType: e2, ...S.normalizeParams(i2) });
}
var Ir = f("ZodSuccess", (e2, i2) => {
  Tu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => il(e2, n, a2), e2.unwrap = () => e2._zod.def.innerType;
});
function Md(e2) {
  return new Ir({ type: "success", innerType: e2 });
}
var xr = f("ZodCatch", (e2, i2) => {
  Au.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => hl(e2, n, a2, t2), e2.unwrap = () => e2._zod.def.innerType, e2.removeCatch = e2.unwrap;
});
function wr(e2, i2) {
  return new xr({ type: "catch", innerType: e2, catchValue: typeof i2 == "function" ? i2 : () => i2 });
}
var Sr = f("ZodNaN", (e2, i2) => {
  Ru.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => Qs(e2, n);
});
function Fd(e2) {
  return Us(Sr, e2);
}
var wi = f("ZodPipe", (e2, i2) => {
  Cu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => $l(e2, n, a2, t2), e2.in = i2.in, e2.out = i2.out;
});
function Ye(e2, i2) {
  return new wi({ type: "pipe", in: e2, out: i2 });
}
var Si = f("ZodCodec", (e2, i2) => {
  wi.init(e2, i2), dn.init(e2, i2);
});
function qd(e2, i2, n) {
  return new Si({ type: "pipe", in: e2, out: i2, transform: n.decode, reverseTransform: n.encode });
}
var zr = f("ZodReadonly", (e2, i2) => {
  Lu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => bl(e2, n, a2, t2), e2.unwrap = () => e2._zod.def.innerType;
});
function Ur(e2) {
  return new zr({ type: "readonly", innerType: e2 });
}
var Or = f("ZodTemplateLiteral", (e2, i2) => {
  Ju.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => el(e2, n, a2);
});
function Wd(e2, i2) {
  return new Or({ type: "template_literal", parts: e2, ...S.normalizeParams(i2) });
}
var jr = f("ZodLazy", (e2, i2) => {
  qu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => _l(e2, n, a2, t2), e2.unwrap = () => e2._zod.def.getter();
});
function Zr(e2) {
  return new jr({ type: "lazy", getter: e2 });
}
var Nr = f("ZodPromise", (e2, i2) => {
  Fu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => yl(e2, n, a2, t2), e2.unwrap = () => e2._zod.def.innerType;
});
function Vd(e2) {
  return new Nr({ type: "promise", innerType: e2 });
}
var Pr = f("ZodFunction", (e2, i2) => {
  Mu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => rl(e2, n);
});
function Et(e2) {
  return new Pr({ type: "function", input: Array.isArray(e2 == null ? void 0 : e2.input) ? sr(e2 == null ? void 0 : e2.input) : (e2 == null ? void 0 : e2.input) ?? $t(we()), output: (e2 == null ? void 0 : e2.output) ?? we() });
}
var kt = f("ZodCustom", (e2, i2) => {
  Wu.init(e2, i2), I.init(e2, i2), e2._zod.processJSONSchema = (n, a2, t2) => nl(e2, n);
});
function Gd(e2) {
  let i2 = new E({ check: "custom" });
  return i2._zod.check = e2, i2;
}
function Kd(e2, i2) {
  return Zs(kt, e2 ?? (() => true), i2);
}
function Dr(e2, i2 = {}) {
  return Ns(kt, e2, i2);
}
function Er(e2) {
  return Ps(e2);
}
var Bd = Es, Hd = Ts;
function Xd(e2, i2 = {}) {
  let n = new kt({ type: "custom", check: "custom", fn: (a2) => a2 instanceof e2, abort: true, ...S.normalizeParams(i2) });
  return n._zod.bag.Class = e2, n._zod.check = (a2) => {
    a2.value instanceof e2 || a2.issues.push({ code: "invalid_type", expected: e2.name, input: a2.value, inst: n, path: [...n._zod.def.path ?? []] });
  }, n;
}
var Yd = (...e2) => As({ Codec: Si, Boolean: gt, String: ft }, ...e2);
function Qd(e2) {
  let i2 = Zr(() => yi([Pt(e2), Vn(), Gn(), Xn(), $t(i2), lr(Pt(), i2)]));
  return i2;
}
function ec(e2, i2) {
  return Ye(ki(e2), i2);
}
var tv = { invalid_type: "invalid_type", too_big: "too_big", too_small: "too_small", invalid_format: "invalid_format", not_multiple_of: "not_multiple_of", unrecognized_keys: "unrecognized_keys", invalid_union: "invalid_union", invalid_key: "invalid_key", invalid_element: "invalid_element", invalid_value: "invalid_value", custom: "custom" };
function iv(e2) {
  F({ customError: e2 });
}
function nv() {
  return F().customError;
}
var Ci;
Ci || (Ci = {});
var h = { ...Il, ...xl, iso: Ln }, rv = /* @__PURE__ */ new Set(["$schema", "$ref", "$defs", "definitions", "$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor", "type", "enum", "const", "anyOf", "oneOf", "allOf", "not", "properties", "required", "additionalProperties", "patternProperties", "propertyNames", "minProperties", "maxProperties", "items", "prefixItems", "additionalItems", "minItems", "maxItems", "uniqueItems", "contains", "minContains", "maxContains", "minLength", "maxLength", "pattern", "format", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", "description", "default", "contentEncoding", "contentMediaType", "contentSchema", "unevaluatedItems", "unevaluatedProperties", "if", "then", "else", "dependentSchemas", "dependentRequired", "nullable", "readOnly"]);
function av(e2, i2) {
  let n = e2.$schema;
  return n === "https://json-schema.org/draft/2020-12/schema" ? "draft-2020-12" : n === "http://json-schema.org/draft-07/schema#" ? "draft-7" : n === "http://json-schema.org/draft-04/schema#" ? "draft-4" : i2 ?? "draft-2020-12";
}
function ov(e2, i2) {
  if (!e2.startsWith("#")) throw Error("External $ref is not supported, only local refs (#/...) are allowed");
  let n = e2.slice(1).split("/").filter(Boolean);
  if (n.length === 0) return i2.rootSchema;
  let a2 = i2.version === "draft-2020-12" ? "$defs" : "definitions";
  if (n[0] === a2) {
    let t2 = n[1];
    if (!t2 || !i2.defs[t2]) throw Error(`Reference not found: ${e2}`);
    return i2.defs[t2];
  }
  throw Error(`Reference not found: ${e2}`);
}
function tc(e2, i2) {
  if (e2.not !== void 0) {
    if (typeof e2.not == "object" && Object.keys(e2.not).length === 0) return h.never();
    throw Error("not is not supported in Zod (except { not: {} } for never)");
  }
  if (e2.unevaluatedItems !== void 0) throw Error("unevaluatedItems is not supported");
  if (e2.unevaluatedProperties !== void 0) throw Error("unevaluatedProperties is not supported");
  if (e2.if !== void 0 || e2.then !== void 0 || e2.else !== void 0) throw Error("Conditional schemas (if/then/else) are not supported");
  if (e2.dependentSchemas !== void 0 || e2.dependentRequired !== void 0) throw Error("dependentSchemas and dependentRequired are not supported");
  if (e2.$ref) {
    let t2 = e2.$ref;
    if (i2.refs.has(t2)) return i2.refs.get(t2);
    if (i2.processing.has(t2)) return h.lazy(() => {
      if (!i2.refs.has(t2)) throw Error(`Circular reference not resolved: ${t2}`);
      return i2.refs.get(t2);
    });
    i2.processing.add(t2);
    let r2 = ov(t2, i2), o2 = M(r2, i2);
    return i2.refs.set(t2, o2), i2.processing.delete(t2), o2;
  }
  if (e2.enum !== void 0) {
    let t2 = e2.enum;
    if (i2.version === "openapi-3.0" && e2.nullable === true && t2.length === 1 && t2[0] === null) return h.null();
    if (t2.length === 0) return h.never();
    if (t2.length === 1) return h.literal(t2[0]);
    if (t2.every((o2) => typeof o2 == "string")) return h.enum(t2);
    let r2 = t2.map((o2) => h.literal(o2));
    return r2.length < 2 ? r2[0] : h.union([r2[0], r2[1], ...r2.slice(2)]);
  }
  if (e2.const !== void 0) return h.literal(e2.const);
  let n = e2.type;
  if (Array.isArray(n)) {
    let t2 = n.map((r2) => {
      let o2 = { ...e2, type: r2 };
      return tc(o2, i2);
    });
    return t2.length === 0 ? h.never() : t2.length === 1 ? t2[0] : h.union(t2);
  }
  if (!n) return h.any();
  let a2;
  switch (n) {
    case "string": {
      let t2 = h.string();
      if (e2.format) {
        let r2 = e2.format;
        r2 === "email" ? t2 = t2.check(h.email()) : r2 === "uri" || r2 === "uri-reference" ? t2 = t2.check(h.url()) : r2 === "uuid" || r2 === "guid" ? t2 = t2.check(h.uuid()) : r2 === "date-time" ? t2 = t2.check(h.iso.datetime()) : r2 === "date" ? t2 = t2.check(h.iso.date()) : r2 === "time" ? t2 = t2.check(h.iso.time()) : r2 === "duration" ? t2 = t2.check(h.iso.duration()) : r2 === "ipv4" ? t2 = t2.check(h.ipv4()) : r2 === "ipv6" ? t2 = t2.check(h.ipv6()) : r2 === "mac" ? t2 = t2.check(h.mac()) : r2 === "cidr" ? t2 = t2.check(h.cidrv4()) : r2 === "cidr-v6" ? t2 = t2.check(h.cidrv6()) : r2 === "base64" ? t2 = t2.check(h.base64()) : r2 === "base64url" ? t2 = t2.check(h.base64url()) : r2 === "e164" ? t2 = t2.check(h.e164()) : r2 === "jwt" ? t2 = t2.check(h.jwt()) : r2 === "emoji" ? t2 = t2.check(h.emoji()) : r2 === "nanoid" ? t2 = t2.check(h.nanoid()) : r2 === "cuid" ? t2 = t2.check(h.cuid()) : r2 === "cuid2" ? t2 = t2.check(h.cuid2()) : r2 === "ulid" ? t2 = t2.check(h.ulid()) : r2 === "xid" ? t2 = t2.check(h.xid()) : r2 === "ksuid" && (t2 = t2.check(h.ksuid()));
      }
      typeof e2.minLength == "number" && (t2 = t2.min(e2.minLength)), typeof e2.maxLength == "number" && (t2 = t2.max(e2.maxLength)), e2.pattern && (t2 = t2.regex(new RegExp(e2.pattern))), a2 = t2;
      break;
    }
    case "number":
    case "integer": {
      let t2 = n === "integer" ? h.number().int() : h.number();
      typeof e2.minimum == "number" && (t2 = t2.min(e2.minimum)), typeof e2.maximum == "number" && (t2 = t2.max(e2.maximum)), typeof e2.exclusiveMinimum == "number" ? t2 = t2.gt(e2.exclusiveMinimum) : e2.exclusiveMinimum === true && typeof e2.minimum == "number" && (t2 = t2.gt(e2.minimum)), typeof e2.exclusiveMaximum == "number" ? t2 = t2.lt(e2.exclusiveMaximum) : e2.exclusiveMaximum === true && typeof e2.maximum == "number" && (t2 = t2.lt(e2.maximum)), typeof e2.multipleOf == "number" && (t2 = t2.multipleOf(e2.multipleOf)), a2 = t2;
      break;
    }
    case "boolean": {
      a2 = h.boolean();
      break;
    }
    case "null": {
      a2 = h.null();
      break;
    }
    case "object": {
      let t2 = {}, r2 = e2.properties || {}, o2 = new Set(e2.required || []);
      for (let [d, s2] of Object.entries(r2)) {
        let m2 = M(s2, i2);
        t2[d] = o2.has(d) ? m2 : m2.optional();
      }
      if (e2.propertyNames) {
        let d = M(e2.propertyNames, i2), s2 = e2.additionalProperties && typeof e2.additionalProperties == "object" ? M(e2.additionalProperties, i2) : h.any();
        if (Object.keys(t2).length === 0) {
          a2 = h.record(d, s2);
          break;
        }
        let m2 = h.object(t2).passthrough(), c = h.looseRecord(d, s2);
        a2 = h.intersection(m2, c);
        break;
      }
      if (e2.patternProperties) {
        let d = e2.patternProperties, s2 = Object.keys(d), m2 = [];
        for (let p2 of s2) {
          let $2 = M(d[p2], i2), y = h.string().regex(new RegExp(p2));
          m2.push(h.looseRecord(y, $2));
        }
        let c = [];
        if (Object.keys(t2).length > 0 && c.push(h.object(t2).passthrough()), c.push(...m2), c.length === 0) a2 = h.object({}).passthrough();
        else if (c.length === 1) a2 = c[0];
        else {
          let p2 = h.intersection(c[0], c[1]);
          for (let $2 = 2; $2 < c.length; $2++) p2 = h.intersection(p2, c[$2]);
          a2 = p2;
        }
        break;
      }
      let u2 = h.object(t2);
      e2.additionalProperties === false ? a2 = u2.strict() : typeof e2.additionalProperties == "object" ? a2 = u2.catchall(M(e2.additionalProperties, i2)) : a2 = u2.passthrough();
      break;
    }
    case "array": {
      let { prefixItems: t2, items: r2 } = e2;
      if (t2 && Array.isArray(t2)) {
        let o2 = t2.map((d) => M(d, i2)), u2 = r2 && typeof r2 == "object" && !Array.isArray(r2) ? M(r2, i2) : void 0;
        u2 ? a2 = h.tuple(o2).rest(u2) : a2 = h.tuple(o2), typeof e2.minItems == "number" && (a2 = a2.check(h.minLength(e2.minItems))), typeof e2.maxItems == "number" && (a2 = a2.check(h.maxLength(e2.maxItems)));
      } else if (Array.isArray(r2)) {
        let o2 = r2.map((d) => M(d, i2)), u2 = e2.additionalItems && typeof e2.additionalItems == "object" ? M(e2.additionalItems, i2) : void 0;
        u2 ? a2 = h.tuple(o2).rest(u2) : a2 = h.tuple(o2), typeof e2.minItems == "number" && (a2 = a2.check(h.minLength(e2.minItems))), typeof e2.maxItems == "number" && (a2 = a2.check(h.maxLength(e2.maxItems)));
      } else if (r2 !== void 0) {
        let o2 = M(r2, i2), u2 = h.array(o2);
        typeof e2.minItems == "number" && (u2 = u2.min(e2.minItems)), typeof e2.maxItems == "number" && (u2 = u2.max(e2.maxItems)), a2 = u2;
      } else a2 = h.array(h.any());
      break;
    }
    default:
      throw Error(`Unsupported type: ${n}`);
  }
  return e2.description && (a2 = a2.describe(e2.description)), e2.default !== void 0 && (a2 = a2.default(e2.default)), a2;
}
function M(e2, i2) {
  if (typeof e2 == "boolean") return e2 ? h.any() : h.never();
  let n = tc(e2, i2), a2 = e2.type || e2.enum !== void 0 || e2.const !== void 0;
  if (e2.anyOf && Array.isArray(e2.anyOf)) {
    let u2 = e2.anyOf.map((s2) => M(s2, i2)), d = h.union(u2);
    n = a2 ? h.intersection(n, d) : d;
  }
  if (e2.oneOf && Array.isArray(e2.oneOf)) {
    let u2 = e2.oneOf.map((s2) => M(s2, i2)), d = h.xor(u2);
    n = a2 ? h.intersection(n, d) : d;
  }
  if (e2.allOf && Array.isArray(e2.allOf)) if (e2.allOf.length === 0) n = a2 ? n : h.any();
  else {
    let u2 = a2 ? n : M(e2.allOf[0], i2), d = a2 ? 0 : 1;
    for (let s2 = d; s2 < e2.allOf.length; s2++) u2 = h.intersection(u2, M(e2.allOf[s2], i2));
    n = u2;
  }
  e2.nullable === true && i2.version === "openapi-3.0" && (n = h.nullable(n)), e2.readOnly === true && (n = h.readonly(n));
  let t2 = {}, r2 = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
  for (let u2 of r2) u2 in e2 && (t2[u2] = e2[u2]);
  let o2 = ["contentEncoding", "contentMediaType", "contentSchema"];
  for (let u2 of o2) u2 in e2 && (t2[u2] = e2[u2]);
  for (let u2 of Object.keys(e2)) rv.has(u2) || (t2[u2] = e2[u2]);
  return Object.keys(t2).length > 0 && i2.registry.add(n, t2), n;
}
function uv(e2, i2) {
  if (typeof e2 == "boolean") return e2 ? h.any() : h.never();
  let n = av(e2, i2 == null ? void 0 : i2.defaultTarget), a2 = e2.$defs || e2.definitions || {}, t2 = { version: n, defs: a2, refs: /* @__PURE__ */ new Map(), processing: /* @__PURE__ */ new Set(), rootSchema: e2, registry: (i2 == null ? void 0 : i2.registry) ?? Q };
  return M(e2, t2);
}
var ic = {};
le(ic, { string: () => sv, number: () => lv, date: () => mv, boolean: () => dv, bigint: () => cv });
function sv(e2) {
  return Qu(ft, e2);
}
function lv(e2) {
  return us(vt, e2);
}
function dv(e2) {
  return ps(gt, e2);
}
function cv(e2) {
  return gs(ht, e2);
}
function mv(e2) {
  return zs(bi, e2);
}
F(Vu());
var fv = l.union([l.literal("light"), l.literal("dark")]).describe("Color theme preference for the host environment."), Qe = l.union([l.literal("inline"), l.literal("fullscreen"), l.literal("pip")]).describe("Display mode for UI presentation."), pv = l.union([l.literal("--color-background-primary"), l.literal("--color-background-secondary"), l.literal("--color-background-tertiary"), l.literal("--color-background-inverse"), l.literal("--color-background-ghost"), l.literal("--color-background-info"), l.literal("--color-background-danger"), l.literal("--color-background-success"), l.literal("--color-background-warning"), l.literal("--color-background-disabled"), l.literal("--color-text-primary"), l.literal("--color-text-secondary"), l.literal("--color-text-tertiary"), l.literal("--color-text-inverse"), l.literal("--color-text-ghost"), l.literal("--color-text-info"), l.literal("--color-text-danger"), l.literal("--color-text-success"), l.literal("--color-text-warning"), l.literal("--color-text-disabled"), l.literal("--color-border-primary"), l.literal("--color-border-secondary"), l.literal("--color-border-tertiary"), l.literal("--color-border-inverse"), l.literal("--color-border-ghost"), l.literal("--color-border-info"), l.literal("--color-border-danger"), l.literal("--color-border-success"), l.literal("--color-border-warning"), l.literal("--color-border-disabled"), l.literal("--color-ring-primary"), l.literal("--color-ring-secondary"), l.literal("--color-ring-inverse"), l.literal("--color-ring-info"), l.literal("--color-ring-danger"), l.literal("--color-ring-success"), l.literal("--color-ring-warning"), l.literal("--font-sans"), l.literal("--font-mono"), l.literal("--font-weight-normal"), l.literal("--font-weight-medium"), l.literal("--font-weight-semibold"), l.literal("--font-weight-bold"), l.literal("--font-text-xs-size"), l.literal("--font-text-sm-size"), l.literal("--font-text-md-size"), l.literal("--font-text-lg-size"), l.literal("--font-heading-xs-size"), l.literal("--font-heading-sm-size"), l.literal("--font-heading-md-size"), l.literal("--font-heading-lg-size"), l.literal("--font-heading-xl-size"), l.literal("--font-heading-2xl-size"), l.literal("--font-heading-3xl-size"), l.literal("--font-text-xs-line-height"), l.literal("--font-text-sm-line-height"), l.literal("--font-text-md-line-height"), l.literal("--font-text-lg-line-height"), l.literal("--font-heading-xs-line-height"), l.literal("--font-heading-sm-line-height"), l.literal("--font-heading-md-line-height"), l.literal("--font-heading-lg-line-height"), l.literal("--font-heading-xl-line-height"), l.literal("--font-heading-2xl-line-height"), l.literal("--font-heading-3xl-line-height"), l.literal("--border-radius-xs"), l.literal("--border-radius-sm"), l.literal("--border-radius-md"), l.literal("--border-radius-lg"), l.literal("--border-radius-xl"), l.literal("--border-radius-full"), l.literal("--border-width-regular"), l.literal("--shadow-hairline"), l.literal("--shadow-sm"), l.literal("--shadow-md"), l.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."), vv = l.record(pv.describe(`Style variables for theming MCP apps.

Individual style keys are optional - hosts may provide any subset of these values.
Values are strings containing CSS values (colors, sizes, font stacks, etc.).

Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`), l.union([l.string(), l.undefined()]).describe(`Style variables for theming MCP apps.

Individual style keys are optional - hosts may provide any subset of these values.
Values are strings containing CSS values (colors, sizes, font stacks, etc.).

Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps.

Individual style keys are optional - hosts may provide any subset of these values.
Values are strings containing CSS values (colors, sizes, font stacks, etc.).

Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`), gv = l.object({ method: l.literal("ui/open-link"), params: l.object({ url: l.string().describe("URL to open in the host's browser") }) });
l.object({ isError: l.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).") }).passthrough();
l.object({ isError: l.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).") }).passthrough();
l.object({ isError: l.boolean().optional().describe("True if the host rejected or failed to deliver the message.") }).passthrough();
var hv = l.object({ method: l.literal("ui/notifications/sandbox-proxy-ready"), params: l.object({}) }), Tr = l.object({ connectDomains: l.array(l.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).

- Maps to CSP \`connect-src\` directive
- Empty or omitted → no network connections (secure default)`), resourceDomains: l.array(l.string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"), frameDomains: l.array(l.string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"), baseUriDomains: l.array(l.string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)") }), Ar = l.object({ camera: l.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."), microphone: l.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."), geolocation: l.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."), clipboardWrite: l.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.") }), $v = l.object({ method: l.literal("ui/notifications/size-changed"), params: l.object({ width: l.number().optional().describe("New width in pixels."), height: l.number().optional().describe("New height in pixels.") }) });
l.object({ method: l.literal("ui/notifications/tool-input"), params: l.object({ arguments: l.record(l.string(), l.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.") }) });
l.object({ method: l.literal("ui/notifications/tool-input-partial"), params: l.object({ arguments: l.record(l.string(), l.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).") }) });
l.object({ method: l.literal("ui/notifications/tool-cancelled"), params: l.object({ reason: l.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").') }) });
var bv = l.object({ fonts: l.string().optional() }), yv = l.object({ variables: vv.optional().describe("CSS variables for theming the app."), css: bv.optional().describe("CSS blocks that apps can inject.") });
l.object({ method: l.literal("ui/resource-teardown"), params: l.object({}) });
var _v = l.record(l.string(), l.unknown()), ua = l.object({ text: l.object({}).optional().describe("Host supports text content blocks."), image: l.object({}).optional().describe("Host supports image content blocks."), audio: l.object({}).optional().describe("Host supports audio content blocks."), resource: l.object({}).optional().describe("Host supports resource content blocks."), resourceLink: l.object({}).optional().describe("Host supports resource link content blocks."), structuredContent: l.object({}).optional().describe("Host supports structured content.") }), kv = l.object({ experimental: l.object({}).optional().describe("Experimental features (structure TBD)."), openLinks: l.object({}).optional().describe("Host supports opening external URLs."), downloadFile: l.object({}).optional().describe("Host supports file downloads via ui/download-file."), serverTools: l.object({ listChanged: l.boolean().optional().describe("Host supports tools/list_changed notifications.") }).optional().describe("Host can proxy tool calls to the MCP server."), serverResources: l.object({ listChanged: l.boolean().optional().describe("Host supports resources/list_changed notifications.") }).optional().describe("Host can proxy resource reads to the MCP server."), logging: l.object({}).optional().describe("Host accepts log messages."), sandbox: l.object({ permissions: Ar.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."), csp: Tr.optional().describe("CSP domains approved by the host.") }).optional().describe("Sandbox configuration applied by the host."), updateModelContext: ua.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."), message: ua.optional().describe("Host supports receiving content messages (ui/message) from the view.") }), Iv = l.object({ experimental: l.object({}).optional().describe("Experimental features (structure TBD)."), tools: l.object({ listChanged: l.boolean().optional().describe("App supports tools/list_changed notifications.") }).optional().describe("App exposes MCP-style tools that the host can call."), availableDisplayModes: l.array(Qe).optional().describe("Display modes the app supports.") }), xv = l.object({ method: l.literal("ui/notifications/initialized"), params: l.object({}).optional() });
l.object({ csp: Tr.optional().describe("Content Security Policy configuration for UI resources."), permissions: Ar.optional().describe("Sandbox permissions requested by the UI resource."), domain: l.string().optional().describe(`Dedicated origin for view sandbox.

Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.

**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include:
- Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`)
- URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`)

If omitted, host uses default sandbox origin (typically per-conversation).`), prefersBorder: l.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border.

Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary.

- \`true\`: request visible border + background
- \`false\`: request no visible border + background
- omitted: host decides border`) });
var sa = l.object({ method: l.literal("ui/request-display-mode"), params: l.object({ mode: Qe.describe("The display mode being requested.") }) });
l.object({ mode: Qe.describe("The display mode that was actually set. May differ from requested if not supported.") }).passthrough();
var wv = l.union([l.literal("model"), l.literal("app")]).describe("Tool visibility scope - who can access the tool.");
l.object({ resourceUri: l.string().optional(), visibility: l.array(wv).optional().describe(`Who can access this tool. Default: ["model", "app"]
- "model": Tool visible to and callable by the agent
- "app": Tool callable by the app from this server only`) });
l.object({ mimeTypes: l.array(l.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.') });
var Sv = l.object({ method: l.literal("ui/download-file"), params: l.object({ contents: l.array(l.union([EmbeddedResourceSchema, ResourceLinkSchema])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.") }) }), zv = l.object({ method: l.literal("ui/message"), params: l.object({ role: l.literal("user").describe('Message role, currently only "user" is supported.'), content: l.array(ContentBlockSchema).describe("Message content blocks (text, image, etc.).") }) });
l.object({ method: l.literal("ui/notifications/sandbox-resource-ready"), params: l.object({ html: l.string().describe("HTML content to load into the inner iframe."), sandbox: l.string().optional().describe("Optional override for the inner iframe's sandbox attribute."), csp: Tr.optional().describe("CSP configuration from resource metadata."), permissions: Ar.optional().describe("Sandbox permissions from resource metadata.") }) });
l.object({ method: l.literal("ui/notifications/tool-result"), params: CallToolResultSchema.describe("Standard MCP tool execution result.") });
var nc = l.object({ toolInfo: l.object({ id: RequestIdSchema.optional().describe("JSON-RPC id of the tools/call request."), tool: ToolSchema.describe("Tool definition including name, inputSchema, etc.") }).optional().describe("Metadata of the tool call that instantiated this App."), theme: fv.optional().describe("Current color theme preference."), styles: yv.optional().describe("Style configuration for theming the app."), displayMode: Qe.optional().describe("How the UI is currently displayed."), availableDisplayModes: l.array(Qe).optional().describe("Display modes the host supports."), containerDimensions: l.union([l.object({ height: l.number().describe("Fixed container height in pixels.") }), l.object({ maxHeight: l.union([l.number(), l.undefined()]).optional().describe("Maximum container height in pixels.") })]).and(l.union([l.object({ width: l.number().describe("Fixed container width in pixels.") }), l.object({ maxWidth: l.union([l.number(), l.undefined()]).optional().describe("Maximum container width in pixels.") })])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`), locale: l.string().optional().describe("User's language and region preference in BCP 47 format."), timeZone: l.string().optional().describe("User's timezone in IANA format."), userAgent: l.string().optional().describe("Host application identifier."), platform: l.union([l.literal("web"), l.literal("desktop"), l.literal("mobile")]).optional().describe("Platform type for responsive design decisions."), deviceCapabilities: l.object({ touch: l.boolean().optional().describe("Whether the device supports touch input."), hover: l.boolean().optional().describe("Whether the device supports hover interactions.") }).optional().describe("Device input capabilities."), safeAreaInsets: l.object({ top: l.number().describe("Top safe area inset in pixels."), right: l.number().describe("Right safe area inset in pixels."), bottom: l.number().describe("Bottom safe area inset in pixels."), left: l.number().describe("Left safe area inset in pixels.") }).optional().describe("Mobile safe area boundaries in pixels.") }).passthrough();
l.object({ method: l.literal("ui/notifications/host-context-changed"), params: nc.describe("Partial context update containing only changed fields.") });
var Uv = l.object({ method: l.literal("ui/update-model-context"), params: l.object({ content: l.array(ContentBlockSchema).optional().describe("Context content blocks (text, image, etc.)."), structuredContent: l.record(l.string(), l.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.") }) }), Ov = l.object({ method: l.literal("ui/initialize"), params: l.object({ appInfo: ImplementationSchema.describe("App identification (name and version)."), appCapabilities: Iv.describe("Features and capabilities this app provides."), protocolVersion: l.string().describe("Protocol version this app supports.") }) });
l.object({ protocolVersion: l.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'), hostInfo: ImplementationSchema.describe("Host application identification and version."), hostCapabilities: kv.describe("Features and capabilities provided by the host."), hostContext: nc.describe("Rich context about the host environment.") }).passthrough();
class jv {
  constructor(i2 = window.parent, n) {
    L(this, "eventTarget");
    L(this, "eventSource");
    L(this, "messageListener");
    L(this, "onclose");
    L(this, "onerror");
    L(this, "onmessage");
    L(this, "sessionId");
    L(this, "setProtocolVersion");
    this.eventTarget = i2, this.eventSource = n, this.messageListener = (a2) => {
      var r2, o2, u2;
      if (n && a2.source !== this.eventSource) {
        console.debug("Ignoring message from unknown source", a2);
        return;
      }
      let t2 = JSONRPCMessageSchema.safeParse(a2.data);
      t2.success ? (console.debug("Parsed message", t2.data), (r2 = this.onmessage) == null || r2.call(this, t2.data)) : ((o2 = a2.data) == null ? void 0 : o2.jsonrpc) !== "2.0" ? console.debug("Ignoring non-JSON-RPC message", t2.error.message, a2) : (console.error("Failed to parse message", t2.error.message, a2), (u2 = this.onerror) == null || u2.call(this, Error("Invalid JSON-RPC message received: " + t2.error.message)));
    };
  }
  async start() {
    window.addEventListener("message", this.messageListener);
  }
  async send(i2, n) {
    console.debug("Sending message", i2), this.eventTarget.postMessage(i2, "*");
  }
  async close() {
    var i2;
    window.removeEventListener("message", this.messageListener), (i2 = this.onclose) == null || i2.call(this);
  }
}
var Zv = "ui/resourceUri", Rr = "text/html;profile=mcp-app";
function Nv(e2) {
  var n, a2, t2;
  let i2 = (a2 = (n = e2._meta) == null ? void 0 : n.ui) == null ? void 0 : a2.resourceUri;
  if (i2 === void 0 && (i2 = (t2 = e2._meta) == null ? void 0 : t2[Zv]), typeof i2 == "string" && i2.startsWith("ui://")) return i2;
  if (i2 !== void 0) throw Error(`Invalid UI resource URI: ${JSON.stringify(i2)}`);
}
var Pv = [pa];
class Dv extends Protocol {
  constructor(n, a2, t2, r2) {
    super(r2);
    L(this, "_client");
    L(this, "_hostInfo");
    L(this, "_capabilities");
    L(this, "_appCapabilities");
    L(this, "_hostContext", {});
    L(this, "_appInfo");
    L(this, "onping");
    L(this, "sendResourceTeardown", this.teardownResource);
    this._client = n, this._hostInfo = a2, this._capabilities = t2, this._hostContext = (r2 == null ? void 0 : r2.hostContext) || {}, this.setRequestHandler(Ov, (o2) => this._oninitialize(o2)), this.setRequestHandler(PingRequestSchema, (o2, u2) => {
      var d;
      return (d = this.onping) == null || d.call(this, o2.params, u2), {};
    }), this.setRequestHandler(sa, (o2) => ({ mode: this._hostContext.displayMode ?? "inline" }));
  }
  getAppCapabilities() {
    return this._appCapabilities;
  }
  getAppVersion() {
    return this._appInfo;
  }
  set onsizechange(n) {
    this.setNotificationHandler($v, (a2) => n(a2.params));
  }
  set onsandboxready(n) {
    this.setNotificationHandler(hv, (a2) => n(a2.params));
  }
  set oninitialized(n) {
    this.setNotificationHandler(xv, (a2) => n(a2.params));
  }
  set onmessage(n) {
    this.setRequestHandler(zv, async (a2, t2) => n(a2.params, t2));
  }
  set onopenlink(n) {
    this.setRequestHandler(gv, async (a2, t2) => n(a2.params, t2));
  }
  set ondownloadfile(n) {
    this.setRequestHandler(Sv, async (a2, t2) => n(a2.params, t2));
  }
  set onrequestdisplaymode(n) {
    this.setRequestHandler(sa, async (a2, t2) => n(a2.params, t2));
  }
  set onloggingmessage(n) {
    this.setNotificationHandler(LoggingMessageNotificationSchema, async (a2) => {
      n(a2.params);
    });
  }
  set onupdatemodelcontext(n) {
    this.setRequestHandler(Uv, async (a2, t2) => n(a2.params, t2));
  }
  set oncalltool(n) {
    this.setRequestHandler(CallToolRequestSchema, async (a2, t2) => n(a2.params, t2));
  }
  sendToolListChanged(n = {}) {
    return this.notification({ method: "notifications/tools/list_changed", params: n });
  }
  set onlistresources(n) {
    this.setRequestHandler(ListResourcesRequestSchema, async (a2, t2) => n(a2.params, t2));
  }
  set onlistresourcetemplates(n) {
    this.setRequestHandler(ListResourceTemplatesRequestSchema, async (a2, t2) => n(a2.params, t2));
  }
  set onreadresource(n) {
    this.setRequestHandler(ReadResourceRequestSchema, async (a2, t2) => n(a2.params, t2));
  }
  sendResourceListChanged(n = {}) {
    return this.notification({ method: "notifications/resources/list_changed", params: n });
  }
  set onlistprompts(n) {
    this.setRequestHandler(ListPromptsRequestSchema, async (a2, t2) => n(a2.params, t2));
  }
  sendPromptListChanged(n = {}) {
    return this.notification({ method: "notifications/prompts/list_changed", params: n });
  }
  assertCapabilityForMethod(n) {
  }
  assertRequestHandlerCapability(n) {
  }
  assertNotificationCapability(n) {
  }
  assertTaskCapability(n) {
    throw Error("Tasks are not supported in MCP Apps");
  }
  assertTaskHandlerCapability(n) {
    throw Error("Task handlers are not supported in MCP Apps");
  }
  getCapabilities() {
    return this._capabilities;
  }
  async _oninitialize(n) {
    let a2 = n.params.protocolVersion;
    return this._appCapabilities = n.params.appCapabilities, this._appInfo = n.params.appInfo, { protocolVersion: Pv.includes(a2) ? a2 : pa, hostCapabilities: this.getCapabilities(), hostInfo: this._hostInfo, hostContext: this._hostContext };
  }
  setHostContext(n) {
    let a2 = {}, t2 = false;
    for (let r2 of Object.keys(n)) {
      let o2 = this._hostContext[r2], u2 = n[r2];
      Ev(o2, u2) || (a2[r2] = u2, t2 = true);
    }
    t2 && (this._hostContext = n, this.sendHostContextChange(a2));
  }
  sendHostContextChange(n) {
    return this.notification({ method: "ui/notifications/host-context-changed", params: n });
  }
  sendToolInput(n) {
    return this.notification({ method: "ui/notifications/tool-input", params: n });
  }
  sendToolInputPartial(n) {
    return this.notification({ method: "ui/notifications/tool-input-partial", params: n });
  }
  sendToolResult(n) {
    return this.notification({ method: "ui/notifications/tool-result", params: n });
  }
  sendToolCancelled(n) {
    return this.notification({ method: "ui/notifications/tool-cancelled", params: n });
  }
  sendSandboxResourceReady(n) {
    return this.notification({ method: "ui/notifications/sandbox-resource-ready", params: n });
  }
  teardownResource(n, a2) {
    return this.request({ method: "ui/resource-teardown", params: n }, _v, a2);
  }
  async connect(n) {
    if (this.transport) throw Error("AppBridge is already connected. Call close() before connecting again.");
    if (this._client) {
      let a2 = this._client.getServerCapabilities();
      if (!a2) throw Error("Client server capabilities not available");
      a2.tools && (this.oncalltool = async (t2, r2) => this._client.request({ method: "tools/call", params: t2 }, CallToolResultSchema, { signal: r2.signal }), a2.tools.listChanged && this._client.setNotificationHandler(ToolListChangedNotificationSchema, (t2) => this.sendToolListChanged(t2.params))), a2.resources && (this.onlistresources = async (t2, r2) => this._client.request({ method: "resources/list", params: t2 }, ListResourcesResultSchema, { signal: r2.signal }), this.onlistresourcetemplates = async (t2, r2) => this._client.request({ method: "resources/templates/list", params: t2 }, ListResourceTemplatesResultSchema, { signal: r2.signal }), this.onreadresource = async (t2, r2) => this._client.request({ method: "resources/read", params: t2 }, ReadResourceResultSchema, { signal: r2.signal }), a2.resources.listChanged && this._client.setNotificationHandler(ResourceListChangedNotificationSchema, (t2) => this.sendResourceListChanged(t2.params))), a2.prompts && (this.onlistprompts = async (t2, r2) => this._client.request({ method: "prompts/list", params: t2 }, ListPromptsResultSchema, { signal: r2.signal }), a2.prompts.listChanged && this._client.setNotificationHandler(PromptListChangedNotificationSchema, (t2) => this.sendPromptListChanged(t2.params)));
    }
    return super.connect(n);
  }
}
function Ev(e2, i2) {
  return JSON.stringify(e2) === JSON.stringify(i2);
}
const Rv = 1e4;
async function Cv(e2) {
  const i2 = document.createElement("iframe");
  i2.style.width = "100%", i2.style.height = "600px", i2.style.border = "none", i2.style.backgroundColor = "transparent", i2.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms");
  const n = new Promise((a2, t2) => {
    let r2 = false;
    const o2 = () => {
      window.removeEventListener("message", d), i2.removeEventListener("error", s2);
    }, u2 = setTimeout(() => {
      r2 || (r2 = true, o2(), t2(new Error("Timed out waiting for sandbox proxy iframe to be ready")));
    }, Rv), d = (m2) => {
      m2.source === i2.contentWindow && m2.data && m2.data.method === Dc && (r2 || (r2 = true, clearTimeout(u2), o2(), a2()));
    }, s2 = () => {
      r2 || (r2 = true, clearTimeout(u2), o2(), t2(new Error("Failed to load sandbox proxy iframe")));
    };
    window.addEventListener("message", d), i2.addEventListener("error", s2);
  });
  return i2.src = e2.href, { iframe: i2, onReady: n };
}
async function Lv(e2, i2) {
  let n, a2;
  do {
    const r2 = await e2.listTools({ cursor: a2 });
    n = r2.tools.find((o2) => o2.name === i2), a2 = r2.nextCursor;
  } while (!n && a2);
  if (!n)
    throw new Error(`tool ${i2} not found`);
  if (!n._meta)
    return null;
  const t2 = Nv(n);
  if (!t2)
    return null;
  if (!t2.startsWith("ui://"))
    throw new Error(`tool ${i2} has unsupported output template URI: ${t2}`);
  return { uri: t2 };
}
async function Jv(e2, i2) {
  const n = await e2.readResource({ uri: i2.uri });
  if (!n)
    throw new Error("UI resource not found: " + i2.uri);
  if (n.contents.length !== 1)
    throw new Error("Unsupported UI resource content length: " + n.contents.length);
  const a2 = n.contents[0];
  let t2;
  const r2 = (o2) => o2 === Rr;
  if ("text" in a2 && typeof a2.text == "string" && r2(a2.mimeType))
    t2 = a2.text;
  else if ("blob" in a2 && typeof a2.blob == "string" && r2(a2.mimeType))
    t2 = atob(a2.blob);
  else
    throw new Error("Unsupported UI resource content format: " + JSON.stringify(a2));
  return t2;
}
function Mv(e2, i2) {
  const n = new URL(e2.href);
  return i2 && Object.keys(i2).length > 0 && n.searchParams.set("csp", JSON.stringify(i2)), n;
}
const Fv = (e2) => {
  const { html: i2, sandbox: n, appBridge: a2, onSizeChanged: t2, onInitialized: r2, toolInput: o2, toolResult: u2, onError: d } = e2, [s2, m2] = reactExports.useState(false), [c, p2] = reactExports.useState(false), [$2, y] = reactExports.useState(null), x2 = reactExports.useRef(null), z2 = reactExports.useRef(null), P2 = reactExports.useRef(null), W2 = reactExports.useRef(null), ae = reactExports.useRef(t2), A = reactExports.useRef(r2), D2 = reactExports.useRef(d);
  return reactExports.useEffect(() => {
    ae.current = t2, A.current = r2, D2.current = d;
  }), reactExports.useEffect(() => {
    const R = Mv(n.url, n.csp), U2 = R.href;
    if (P2.current === U2 && W2.current === a2 && z2.current)
      return;
    m2(false), p2(false), y(null);
    let H2 = true;
    return (async () => {
      var Fe, qe;
      try {
        z2.current && ((Fe = x2.current) != null && Fe.contains(z2.current)) && (x2.current.removeChild(z2.current), z2.current = null, P2.current = null, W2.current = null);
        const { iframe: G2, onReady: me2 } = await Cv(R);
        if (!H2 || (z2.current = G2, P2.current = U2, W2.current = a2, x2.current && x2.current.appendChild(G2), await me2, !H2) || (a2.onsizechange = async (X2) => {
          var je;
          (je = ae.current) == null || je.call(ae, X2), z2.current && (X2.width !== void 0 && (z2.current.style.width = `${X2.width}px`), X2.height !== void 0 && (z2.current.style.height = `${X2.height}px`));
        }, a2.oninitialized = () => {
          var X2;
          H2 && (console.log("[AppFrame] App initialized"), m2(true), (X2 = A.current) == null || X2.call(A, {
            appVersion: a2.getAppVersion(),
            appCapabilities: a2.getAppCapabilities()
          }));
        }, await a2.connect(
          new jv(G2.contentWindow, G2.contentWindow)
        ), !H2)) return;
        p2(true);
      } catch (G2) {
        if (console.error("[AppFrame] Error:", G2), !H2) return;
        const me2 = G2 instanceof Error ? G2 : new Error(String(G2));
        y(me2), (qe = D2.current) == null || qe.call(D2, me2);
      }
    })(), () => {
      H2 = false;
    };
  }, [n.url, n.csp, a2]), reactExports.useEffect(() => {
    if (!c || !i2 || W2.current !== a2) return;
    (async () => {
      var U2;
      try {
        console.log("[AppFrame] Sending HTML to sandbox"), await a2.sendSandboxResourceReady({
          html: i2,
          csp: n.csp
        });
      } catch (H2) {
        const Oe = H2 instanceof Error ? H2 : new Error(String(H2));
        y(Oe), (U2 = D2.current) == null || U2.call(D2, Oe);
      }
    })();
  }, [c, i2, a2, n.csp]), reactExports.useEffect(() => {
    c && s2 && o2 && W2.current === a2 && (console.log("[AppFrame] Sending tool input:", o2), a2.sendToolInput({ arguments: o2 }));
  }, [a2, c, s2, o2]), reactExports.useEffect(() => {
    c && s2 && u2 && W2.current === a2 && (console.log("[AppFrame] Sending tool result:", u2), a2.sendToolResult(u2));
  }, [a2, c, s2, u2]), /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      ref: x2,
      style: {
        width: "100%",
        height: "100%",
        display: "flex",
        flexDirection: "column"
      },
      children: $2 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { color: "red", padding: "1rem" }, children: [
        "Error: ",
        $2.message
      ] })
    }
  );
}, qv = reactExports.forwardRef((e2, i2) => {
  const {
    client: n,
    toolName: a2,
    sandbox: t2,
    toolResourceUri: r2,
    html: o2,
    toolInput: u2,
    toolResult: d,
    toolInputPartial: s2,
    toolCancelled: m2,
    hostContext: c,
    onMessage: p2,
    onOpenLink: $2,
    onLoggingMessage: y,
    onSizeChanged: x2,
    onError: z2,
    onCallTool: P2,
    onListResources: W2,
    onListResourceTemplates: ae,
    onReadResource: A,
    onListPrompts: D2,
    onFallbackRequest: R
  } = e2, [U2, H2] = reactExports.useState(null), [Oe, Fe] = reactExports.useState(o2 ?? null), [qe, G2] = reactExports.useState(null), me2 = reactExports.useRef(p2), X2 = reactExports.useRef($2), je = reactExports.useRef(y), Cr = reactExports.useRef(x2), he2 = reactExports.useRef(z2), zi = reactExports.useRef(P2), Ui = reactExports.useRef(W2), Oi = reactExports.useRef(ae), Ze = reactExports.useRef(A), ji = reactExports.useRef(D2), Zi = reactExports.useRef(R);
  reactExports.useEffect(() => {
    me2.current = p2, X2.current = $2, je.current = y, Cr.current = x2, he2.current = z2, zi.current = P2, Ui.current = W2, Oi.current = ae, Ze.current = A, ji.current = D2, Zi.current = R;
  }), reactExports.useImperativeHandle(
    i2,
    () => ({
      sendToolListChanged: () => U2 == null ? void 0 : U2.sendToolListChanged(),
      sendResourceListChanged: () => U2 == null ? void 0 : U2.sendResourceListChanged(),
      sendPromptListChanged: () => U2 == null ? void 0 : U2.sendPromptListChanged(),
      teardownResource: () => U2 == null ? void 0 : U2.teardownResource({})
    }),
    [U2]
  ), reactExports.useEffect(() => {
    let We = true;
    return (() => {
      var $e;
      try {
        const Y2 = n == null ? void 0 : n.getServerCapabilities(), J2 = new Dv(
          n ?? null,
          {
            name: "MCP-UI Host",
            version: "1.0.0"
          },
          {
            openLinks: {},
            serverTools: Y2 == null ? void 0 : Y2.tools,
            serverResources: Y2 == null ? void 0 : Y2.resources
          }
        );
        if (J2.onmessage = async (T2, j) => {
          if (me2.current)
            return me2.current(T2, j);
          throw new McpError(ErrorCode.MethodNotFound, "Method not found");
        }, J2.onopenlink = async (T2, j) => {
          if (X2.current)
            return X2.current(T2, j);
          throw new McpError(ErrorCode.MethodNotFound, "Method not found");
        }, J2.onloggingmessage = (T2) => {
          je.current && je.current(T2);
        }, zi.current && (J2.oncalltool = (T2, j) => zi.current(T2, j)), Ui.current && (J2.onlistresources = (T2, j) => Ui.current(T2, j)), Oi.current && (J2.onlistresourcetemplates = (T2, j) => Oi.current(T2, j)), Ze.current && (J2.onreadresource = (T2, j) => Ze.current(T2, j)), ji.current && (J2.onlistprompts = (T2, j) => ji.current(T2, j)), J2.fallbackRequestHandler = async (T2, j) => {
          if (Zi.current)
            return Zi.current(T2, j);
          throw new McpError(
            ErrorCode.MethodNotFound,
            `No handler for method: ${T2.method}`
          );
        }, !We) return;
        H2(J2);
      } catch (Y2) {
        if (console.error("[AppRenderer] Error creating bridge:", Y2), !We) return;
        const J2 = Y2 instanceof Error ? Y2 : new Error(String(Y2));
        G2(J2), ($e = he2.current) == null || $e.call(he2, J2);
      }
    })(), () => {
      We = false;
    };
  }, [n]), reactExports.useEffect(() => {
    if (o2) {
      Fe(o2);
      return;
    }
    const We = !!n, Lr = !!r2 && !!Ze.current;
    if (!We && !Lr) {
      G2(
        new Error(
          "Either 'html' prop, 'client', or ('toolResourceUri' + 'onReadResource') must be provided to fetch UI resource"
        )
      );
      return;
    }
    let $e = true;
    return (async () => {
      var J2, T2;
      try {
        let j;
        if (r2)
          j = r2, console.log(`[AppRenderer] Using provided resource URI: ${j}`);
        else if (n) {
          console.log(`[AppRenderer] Fetching resource URI for tool: ${a2}`);
          const ye2 = await Lv(n, a2);
          if (!ye2)
            throw new Error(
              `Tool ${a2} has no UI resource (no ui/resourceUri in tool._meta)`
            );
          j = ye2.uri, console.log(`[AppRenderer] Got resource URI: ${j}`);
        } else
          throw new Error("Cannot determine resource URI without client or toolResourceUri");
        if (!$e) return;
        console.log(`[AppRenderer] Reading resource HTML from: ${j}`);
        let be2;
        if (n)
          be2 = await Jv(n, { uri: j });
        else if (Ze.current) {
          const ye2 = await Ze.current({ uri: j }, {});
          if (!ye2.contents || ye2.contents.length !== 1)
            throw new Error("Unsupported UI resource content length: " + ((J2 = ye2.contents) == null ? void 0 : J2.length));
          const ue2 = ye2.contents[0], Jr = (ac) => ac === Rr;
          if ("text" in ue2 && typeof ue2.text == "string" && Jr(ue2.mimeType))
            be2 = ue2.text;
          else if ("blob" in ue2 && typeof ue2.blob == "string" && Jr(ue2.mimeType))
            be2 = atob(ue2.blob);
          else
            throw new Error("Unsupported UI resource content format: " + JSON.stringify(ue2));
        } else
          throw new Error("No way to read resource HTML");
        if (!$e) return;
        Fe(be2);
      } catch (j) {
        if (!$e) return;
        const be2 = j instanceof Error ? j : new Error(String(j));
        G2(be2), (T2 = he2.current) == null || T2.call(he2, be2);
      }
    })(), () => {
      $e = false;
    };
  }, [n, a2, r2, o2]), reactExports.useEffect(() => {
    U2 && c && U2.setHostContext(c);
  }, [U2, c]), reactExports.useEffect(() => {
    U2 && s2 && U2.sendToolInputPartial(s2);
  }, [U2, s2]), reactExports.useEffect(() => {
    U2 && m2 && U2.sendToolCancelled({});
  }, [U2, m2]);
  const rc = Cr.current;
  return qe ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { color: "red", padding: "1rem" }, children: [
    "Error: ",
    qe.message
  ] }) : !U2 || !Oe ? null : /* @__PURE__ */ jsxRuntimeExports.jsx(
    Fv,
    {
      html: Oe,
      sandbox: t2,
      appBridge: U2,
      toolInput: u2,
      toolResult: d,
      onSizeChanged: rc,
      onError: z2
    }
  );
});
qv.displayName = "AppRenderer";
const AppRenderer = ({
  sandboxPath,
  tool,
  mcpClient,
  toolInput,
  toolResult,
  onNotification
}) => {
  const [error, setError] = reactExports.useState(null);
  const { toast: toast2 } = useToast();
  const normalizedToolResult = reactExports.useMemo(() => {
    if (!toolResult) {
      return void 0;
    }
    if ("content" in toolResult) {
      const parsedResult = CallToolResultSchema.safeParse(toolResult);
      return parsedResult.success ? parsedResult.data : void 0;
    }
    if ("toolResult" in toolResult) {
      const parsedResult = CallToolResultSchema.safeParse(
        toolResult.toolResult
      );
      return parsedResult.success ? parsedResult.data : void 0;
    }
    return void 0;
  }, [toolResult]);
  const hostContext = reactExports.useMemo(
    () => ({
      theme: document.documentElement.classList.contains("dark") ? "dark" : "light"
    }),
    []
  );
  const handleOpenLink = async ({ url: url2 }) => {
    let isError = true;
    if (url2.startsWith("https://") || url2.startsWith("http://")) {
      window.open(url2, "_blank");
      isError = false;
    }
    return { isError };
  };
  const handleMessage = async (params, _extra) => {
    const message = params.content.filter(
      (block) => Boolean(block.type === "text")
    ).map((block) => block.text).join("\n");
    if (message) {
      toast2({
        description: message
      });
    }
    return {};
  };
  const handleLoggingMessage = (params) => {
    if (onNotification) {
      onNotification({
        method: "notifications/message",
        params
      });
    }
  };
  if (!mcpClient) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(Alert, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CircleAlert, { className: "h-4 w-4" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { children: "Waiting for MCP client..." })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col h-full", children: [
    error && /* @__PURE__ */ jsxRuntimeExports.jsxs(Alert, { variant: "destructive", className: "mb-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CircleAlert, { className: "h-4 w-4" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { children: error })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: "flex-1 border rounded overflow-hidden",
        style: { minHeight: "400px" },
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          qv,
          {
            client: mcpClient,
            onOpenLink: handleOpenLink,
            onMessage: handleMessage,
            onLoggingMessage: handleLoggingMessage,
            toolName: tool.name,
            hostContext,
            toolInput,
            toolResult: normalizedToolResult,
            sandbox: {
              url: new URL(sandboxPath, window.location.origin)
            },
            onError: (err) => setError(err.message)
          }
        )
      }
    )
  ] });
};
const hasUIMetadata = (tool) => {
  return !!FZ(tool);
};
const cloneToolParams$1 = (source) => {
  try {
    return structuredClone(source);
  } catch {
    return { ...source };
  }
};
const AppsTab = ({
  sandboxPath,
  tools,
  listTools,
  callTool,
  prefilledToolCall,
  onPrefilledToolCallConsumed,
  error,
  mcpClient,
  onNotification
}) => {
  const [appTools, setAppTools] = reactExports.useState([]);
  const [selectedTool, setSelectedTool] = reactExports.useState(null);
  const [params, setParams] = reactExports.useState({});
  const [isAppOpen, setIsAppOpen] = reactExports.useState(false);
  const [isOpeningApp, setIsOpeningApp] = reactExports.useState(false);
  const [isMaximized, setIsMaximized] = reactExports.useState(false);
  const [hasValidationErrors, setHasValidationErrors] = reactExports.useState(false);
  const [submittedParams, setSubmittedParams] = reactExports.useState(void 0);
  const [submittedToolResult, setSubmittedToolResult] = reactExports.useState(null);
  const formRefs = reactExports.useRef({});
  const openAppRunIdRef = reactExports.useRef(0);
  const prefillingParamsRef = reactExports.useRef(null);
  const consumedPrefilledCallIdRef = reactExports.useRef(null);
  const buildInitialParams = reactExports.useCallback((tool) => {
    const initialParams = Object.entries(tool.inputSchema.properties ?? []).map(
      ([key, value]) => {
        const resolvedValue = resolveRef(
          value,
          tool.inputSchema
        );
        return [
          key,
          generateDefaultValue(
            resolvedValue,
            key,
            tool.inputSchema
          )
        ];
      }
    );
    return Object.fromEntries(initialParams);
  }, []);
  const checkValidationErrors = reactExports.useCallback(() => {
    const errors2 = Object.values(formRefs.current).some(
      (ref2) => ref2 && !ref2.validateJson().isValid
    );
    setHasValidationErrors(errors2);
    return errors2;
  }, []);
  reactExports.useEffect(() => {
    const filtered = tools.filter(hasUIMetadata);
    console.log("[AppsTab] Filtered app tools:", {
      totalTools: tools.length,
      appTools: filtered.length,
      appToolNames: filtered.map((t2) => t2.name)
    });
    setAppTools(filtered);
    if (selectedTool && !filtered.find((t2) => t2.name === selectedTool.name)) {
      setSelectedTool(null);
      setIsAppOpen(false);
      setSubmittedParams(void 0);
      setSubmittedToolResult(null);
    }
  }, [tools, selectedTool]);
  reactExports.useEffect(() => {
    if (selectedTool) {
      const prefillingParams = prefillingParamsRef.current;
      if (prefillingParams) {
        setParams(prefillingParams);
        prefillingParamsRef.current = null;
      } else {
        setParams(buildInitialParams(selectedTool));
      }
      setHasValidationErrors(false);
      formRefs.current = {};
    } else {
      setParams({});
      setIsAppOpen(false);
      setSubmittedParams(void 0);
      setSubmittedToolResult(null);
    }
  }, [buildInitialParams, selectedTool]);
  reactExports.useEffect(() => {
    if (!prefilledToolCall) {
      return;
    }
    if (consumedPrefilledCallIdRef.current === prefilledToolCall.id) {
      return;
    }
    const matchingTool = appTools.find(
      (tool) => tool.name === prefilledToolCall.toolName
    );
    if (!matchingTool) {
      return;
    }
    const hydratedParams = cloneToolParams$1(prefilledToolCall.params);
    openAppRunIdRef.current += 1;
    setIsOpeningApp(false);
    prefillingParamsRef.current = hydratedParams;
    setSelectedTool(matchingTool);
    setSubmittedParams(hydratedParams);
    setSubmittedToolResult(prefilledToolCall.result);
    setIsAppOpen(true);
    setIsMaximized(false);
    consumedPrefilledCallIdRef.current = prefilledToolCall.id;
    onPrefilledToolCallConsumed?.(prefilledToolCall.id);
  }, [appTools, onPrefilledToolCallConsumed, prefilledToolCall]);
  const handleRefresh = reactExports.useCallback(() => {
    listTools();
  }, [listTools]);
  const executeToolAndOpenApp = reactExports.useCallback(
    async (tool, toolParams) => {
      const runId = ++openAppRunIdRef.current;
      const runParams = cloneToolParams$1(toolParams);
      prefillingParamsRef.current = null;
      setIsOpeningApp(true);
      setSubmittedParams(runParams);
      setSubmittedToolResult(null);
      try {
        const result = await callTool(tool.name, runParams);
        if (runId !== openAppRunIdRef.current) {
          return;
        }
        setSubmittedParams(runParams);
        setSubmittedToolResult(result);
        setIsAppOpen(true);
      } catch {
        if (runId !== openAppRunIdRef.current) {
          return;
        }
        setSubmittedToolResult(null);
        setIsAppOpen(false);
      } finally {
        if (runId === openAppRunIdRef.current) {
          setIsOpeningApp(false);
        }
      }
    },
    [callTool]
  );
  const handleCloseApp = reactExports.useCallback(() => {
    openAppRunIdRef.current += 1;
    setIsOpeningApp(false);
    setIsAppOpen(false);
    setSubmittedToolResult(null);
  }, []);
  const handleOpenApp = reactExports.useCallback(async () => {
    if (!selectedTool || checkValidationErrors()) {
      return;
    }
    await executeToolAndOpenApp(selectedTool, params);
  }, [checkValidationErrors, executeToolAndOpenApp, params, selectedTool]);
  const handleSelectTool = reactExports.useCallback(
    (tool) => {
      openAppRunIdRef.current += 1;
      setIsOpeningApp(false);
      prefillingParamsRef.current = null;
      setSelectedTool(tool);
      setSubmittedParams(void 0);
      setSubmittedToolResult(null);
      const hasFields = tool.inputSchema.properties && Object.keys(tool.inputSchema.properties).length > 0;
      if (hasFields) {
        setIsAppOpen(false);
        return;
      }
      const initialParams = buildInitialParams(tool);
      void executeToolAndOpenApp(tool, initialParams);
    },
    [buildInitialParams, executeToolAndOpenApp]
  );
  const handleDeselectTool = reactExports.useCallback(() => {
    openAppRunIdRef.current += 1;
    setIsOpeningApp(false);
    prefillingParamsRef.current = null;
    setSelectedTool(null);
    setIsAppOpen(false);
    setIsMaximized(false);
    setSubmittedParams(void 0);
    setSubmittedToolResult(null);
  }, []);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(TabsContent, { value: "apps", className: "space-y-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      className: isMaximized ? "grid grid-cols-1 gap-4" : "grid grid-cols-1 md:grid-cols-2 gap-4",
      children: [
        !isMaximized && /* @__PURE__ */ jsxRuntimeExports.jsx(
          ListPane,
          {
            items: appTools,
            listItems: handleRefresh,
            setSelectedItem: handleSelectTool,
            renderItem: (tool) => {
              return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start w-full gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-shrink-0 mt-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx(IconDisplay, { icons: tool.icons, size: "sm" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col flex-1 min-w-0", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "truncate font-semibold", children: tool.name }),
                  tool.description && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-500 text-left line-clamp-2", children: tool.description })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "w-4 h-4 flex-shrink-0 text-gray-400 mt-1" })
              ] });
            },
            title: "MCP Apps",
            buttonText: "Refresh Apps"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-card border border-border rounded-lg shadow", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4 border-b border-gray-200 dark:border-border", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
              selectedTool && /* @__PURE__ */ jsxRuntimeExports.jsx(
                IconDisplay,
                {
                  icons: selectedTool.icons,
                  size: "md"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "font-semibold", children: selectedTool ? selectedTool.name : "Select an app" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
              selectedTool && isAppOpen && /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  onClick: () => setIsMaximized(!isMaximized),
                  variant: "ghost",
                  size: "sm",
                  "aria-label": isMaximized ? "Minimize" : "Maximize",
                  children: isMaximized ? /* @__PURE__ */ jsxRuntimeExports.jsx(Minimize2, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Maximize2, { className: "w-4 h-4" })
                }
              ),
              selectedTool && /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  onClick: handleDeselectTool,
                  variant: "ghost",
                  size: "sm",
                  "aria-label": "Close app",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(X$1, { className: "w-4 h-4" })
                }
              )
            ] })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-4", children: [
            error && /* @__PURE__ */ jsxRuntimeExports.jsxs(Alert, { variant: "destructive", className: "mb-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(CircleAlert, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { children: error })
            ] }),
            selectedTool ? (() => {
              const hasFields = selectedTool.inputSchema.properties && Object.keys(selectedTool.inputSchema.properties).length > 0;
              return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4", children: !isAppOpen ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
                selectedTool.description && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 whitespace-pre-wrap", children: selectedTool.description }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4 border rounded-lg p-4 bg-muted/30", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-medium text-sm", children: "App Input" }),
                  Object.entries(
                    selectedTool.inputSchema.properties ?? []
                  ).map(([key, value]) => {
                    const resolvedValue = resolveRef(
                      value,
                      selectedTool.inputSchema
                    );
                    const prop = normalizeUnionType(resolvedValue);
                    const inputSchema = selectedTool.inputSchema;
                    const required2 = isPropertyRequired(
                      key,
                      inputSchema
                    );
                    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs(
                          Label$1,
                          {
                            htmlFor: key,
                            className: "block text-sm font-medium text-gray-700 dark:text-gray-300",
                            children: [
                              key,
                              required2 && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500 ml-1", children: "*" })
                            ]
                          }
                        ),
                        prop.nullable ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center space-x-2", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            Checkbox,
                            {
                              id: `${key}-null`,
                              checked: params[key] === null,
                              onCheckedChange: (checked) => setParams({
                                ...params,
                                [key]: checked ? null : prop.type === "array" ? void 0 : prop.default !== null ? prop.default : prop.type === "boolean" ? false : prop.type === "string" ? "" : void 0
                              })
                            }
                          ),
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "label",
                            {
                              htmlFor: `${key}-null`,
                              className: "text-sm font-medium text-gray-700 dark:text-gray-300",
                              children: "null"
                            }
                          )
                        ] }) : null
                      ] }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "div",
                        {
                          className: `${prop.nullable && params[key] === null ? "pointer-events-none opacity-50" : ""}`,
                          children: prop.type === "boolean" ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center space-x-2", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx(
                              Checkbox,
                              {
                                id: key,
                                checked: !!params[key],
                                onCheckedChange: (checked) => setParams({
                                  ...params,
                                  [key]: checked
                                })
                              }
                            ),
                            /* @__PURE__ */ jsxRuntimeExports.jsx(
                              "label",
                              {
                                htmlFor: key,
                                className: "text-sm font-medium text-gray-700 dark:text-gray-300",
                                children: prop.description || "Toggle this option"
                              }
                            )
                          ] }) : prop.type === "string" && prop.enum ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
                            Select,
                            {
                              value: params[key] === void 0 ? "" : String(params[key]),
                              onValueChange: (value2) => {
                                setParams({
                                  ...params,
                                  [key]: value2 === "" ? void 0 : value2
                                });
                              },
                              children: [
                                /* @__PURE__ */ jsxRuntimeExports.jsx(SelectTrigger, { id: key, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                                  SelectValue,
                                  {
                                    placeholder: prop.description || "Select an option"
                                  }
                                ) }),
                                /* @__PURE__ */ jsxRuntimeExports.jsx(SelectContent, { children: prop.enum.map((option) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                                  SelectItem,
                                  {
                                    value: option,
                                    children: option
                                  },
                                  option
                                )) })
                              ]
                            }
                          ) : prop.type === "string" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                            Textarea,
                            {
                              id: key,
                              placeholder: prop.description,
                              value: params[key] === void 0 ? "" : String(params[key]),
                              onChange: (e2) => {
                                setParams({
                                  ...params,
                                  [key]: e2.target.value === "" ? void 0 : e2.target.value
                                });
                              }
                            }
                          ) : prop.type === "object" || prop.type === "array" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                            DynamicJsonForm,
                            {
                              ref: (ref2) => formRefs.current[key] = ref2,
                              schema: {
                                type: prop.type,
                                properties: prop.properties,
                                description: prop.description,
                                items: prop.items
                              },
                              value: params[key] ?? generateDefaultValue(prop),
                              onChange: (newValue) => {
                                setParams({
                                  ...params,
                                  [key]: newValue
                                });
                                setTimeout(checkValidationErrors, 100);
                              }
                            }
                          ) : prop.type === "number" || prop.type === "integer" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                            Input,
                            {
                              type: "number",
                              id: key,
                              placeholder: prop.description,
                              value: params[key] === void 0 ? "" : String(params[key]),
                              onChange: (e2) => {
                                const value2 = e2.target.value;
                                if (value2 === "") {
                                  setParams({
                                    ...params,
                                    [key]: void 0
                                  });
                                } else {
                                  const num = Number(value2);
                                  setParams({
                                    ...params,
                                    [key]: isNaN(num) ? value2 : num
                                  });
                                }
                              }
                            }
                          ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                            DynamicJsonForm,
                            {
                              ref: (ref2) => formRefs.current[key] = ref2,
                              schema: {
                                type: prop.type,
                                properties: prop.properties,
                                description: prop.description,
                                items: prop.items
                              },
                              value: params[key],
                              onChange: (newValue) => {
                                setParams({
                                  ...params,
                                  [key]: newValue
                                });
                                setTimeout(checkValidationErrors, 100);
                              }
                            }
                          )
                        }
                      )
                    ] }, key);
                  }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    Button,
                    {
                      onClick: () => void handleOpenApp(),
                      className: "w-full",
                      disabled: hasValidationErrors || isOpeningApp,
                      children: [
                        isOpeningApp ? /* @__PURE__ */ jsxRuntimeExports.jsx(LoaderCircle, { className: "w-4 h-4 mr-2 animate-spin" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Play, { className: "w-4 h-4 mr-2" }),
                        isOpeningApp ? "Opening App..." : "Open App"
                      ]
                    }
                  )
                ] })
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
                hasFields && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    onClick: handleCloseApp,
                    variant: "outline",
                    size: "sm",
                    children: "Back to Input"
                  }
                ) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-[600px]", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  AppRenderer,
                  {
                    sandboxPath,
                    tool: selectedTool,
                    mcpClient,
                    toolInput: submittedParams,
                    toolResult: submittedToolResult,
                    onNotification
                  }
                ) })
              ] }) });
            })() : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-muted-foreground space-y-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(CircleAlert, { className: "w-12 h-12 opacity-20" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Select an app from the list to get started" }),
              appTools.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-center max-w-[200px]", children: [
                "No MCP Apps available. Apps are tools that include a",
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "bg-muted px-1 rounded", children: "_meta.ui.resourceUri" })
              ] })
            ] })
          ] })
        ] })
      ]
    }
  ) });
};
const ElicitationRequest = ({
  request,
  onResolve
}) => {
  const [formData, setFormData] = reactExports.useState({});
  const [validationError, setValidationError] = reactExports.useState(null);
  const [showUrlConfirm, setShowUrlConfirm] = reactExports.useState(false);
  const requestData = request.request;
  const isUrlMode = requestData.mode === "url";
  reactExports.useEffect(() => {
    if (isUrlMode) return;
    const defaultValue = generateDefaultValue(
      requestData.requestedSchema
    );
    setFormData(defaultValue);
    setValidationError(null);
  }, [isUrlMode, requestData]);
  if (isUrlMode) {
    let parsedUrl = null;
    let urlError = null;
    try {
      parsedUrl = new URL(requestData.url);
      if (parsedUrl.protocol !== "https:") {
        urlError = `Refusing to open this URL: only https: URLs are permitted for URL elicitation (received scheme "${parsedUrl.protocol}").`;
        parsedUrl = null;
      }
    } catch {
      urlError = `The server provided a malformed URL: ${requestData.url}`;
    }
    const handleConfirmOpen = () => {
      if (!parsedUrl) return;
      window.open(parsedUrl.href, "_blank", "noopener,noreferrer");
      setShowUrlConfirm(false);
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        "data-testid": "elicitation-request",
        className: "flex flex-col gap-4 p-4 border rounded-lg",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-gray-50 dark:bg-gray-800 dark:text-gray-100 p-2 rounded", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-semibold", children: "URL Request" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm", children: requestData.message })
          ] }) }),
          urlError && /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              "data-testid": "url-error",
              className: "p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md text-sm text-red-600 dark:text-red-400",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { children: "Invalid URL:" }),
                " ",
                urlError
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex space-x-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                type: "button",
                disabled: !!urlError,
                onClick: () => setShowUrlConfirm(true),
                children: "Open URL"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                type: "button",
                onClick: () => onResolve(request.id, { action: "accept" }),
                children: "Accept"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                type: "button",
                variant: "outline",
                onClick: () => onResolve(request.id, { action: "decline" }),
                children: "Decline"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                type: "button",
                variant: "outline",
                onClick: () => onResolve(request.id, { action: "cancel" }),
                children: "Cancel"
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Dialog, { open: showUrlConfirm, onOpenChange: setShowUrlConfirm, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogContent, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogHeader, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(DialogTitle, { children: "Open External URL" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(DialogDescription, { children: "The server is requesting you visit the following URL:" })
            ] }),
            parsedUrl && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm", children: [
              "Destination host:",
              " ",
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  "data-testid": "url-confirm-host",
                  className: "font-mono font-semibold break-all",
                  children: parsedUrl.host
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "p",
              {
                "data-testid": "url-confirm-text",
                className: "text-sm font-mono bg-gray-100 dark:bg-gray-800 p-3 rounded break-all select-all",
                children: requestData.url
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogFooter, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  variant: "outline",
                  onClick: () => setShowUrlConfirm(false),
                  children: "Cancel"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { onClick: handleConfirmOpen, children: "Open" })
            ] })
          ] }) })
        ]
      }
    );
  }
  const formRequest = requestData;
  const validateEmailFormat = (email2) => {
    const emailRegex2 = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex2.test(email2);
  };
  const validateFormData = (data2, schema) => {
    if (schema.type === "object" && schema.properties && typeof data2 === "object" && data2 !== null) {
      const dataObj = data2;
      if (Array.isArray(schema.required)) {
        for (const field of schema.required) {
          const value = dataObj[field];
          if (value === void 0 || value === null || value === "") {
            setValidationError(`Required field missing: ${field}`);
            return false;
          }
        }
      }
      for (const [fieldName, fieldValue] of Object.entries(dataObj)) {
        const fieldSchema = schema.properties[fieldName];
        if (fieldSchema && fieldSchema.format === "email" && typeof fieldValue === "string") {
          if (!validateEmailFormat(fieldValue)) {
            setValidationError(`Invalid email format: ${fieldName}`);
            return false;
          }
        }
      }
    }
    return true;
  };
  const handleAccept = () => {
    try {
      if (!validateFormData(formData, formRequest.requestedSchema)) {
        return;
      }
      const ajv2 = new Ajv$1();
      const validate2 = ajv2.compile(formRequest.requestedSchema);
      const isValid2 = validate2(formData);
      if (!isValid2) {
        const errorMessage = ajv2.errorsText(validate2.errors);
        setValidationError(errorMessage);
        return;
      }
      onResolve(request.id, {
        action: "accept",
        content: formData
      });
    } catch (error) {
      setValidationError(
        error instanceof Error ? error.message : "Validation failed"
      );
    }
  };
  const handleDecline = () => {
    onResolve(request.id, { action: "decline" });
  };
  const handleCancel = () => {
    onResolve(request.id, { action: "cancel" });
  };
  const schemaTitle = formRequest.requestedSchema.title || "Information Request";
  const schemaDescription = formRequest.requestedSchema.description;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      "data-testid": "elicitation-request",
      className: "flex gap-4 p-4 border rounded-lg space-y-4",
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-1 bg-gray-50 dark:bg-gray-800 dark:text-gray-100 p-2 rounded", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-semibold", children: schemaTitle }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm", children: formRequest.message }),
          schemaDescription && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-muted-foreground", children: schemaDescription }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h5", { className: "text-xs font-medium mb-1", children: "Request Schema:" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              JsonView,
              {
                data: JSON.stringify(formRequest.requestedSchema, null, 2)
              }
            )
          ] })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-medium", children: "Response Form" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              DynamicJsonForm,
              {
                schema: formRequest.requestedSchema,
                value: formData,
                onChange: (newValue) => {
                  setFormData(newValue);
                  setValidationError(null);
                }
              }
            ),
            validationError && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-red-600 dark:text-red-400", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { children: "Validation Error:" }),
              " ",
              validationError
            ] }) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex space-x-2 mt-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { type: "button", onClick: handleAccept, children: "Submit" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { type: "button", variant: "outline", onClick: handleDecline, children: "Decline" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { type: "button", variant: "outline", onClick: handleCancel, children: "Cancel" })
          ] })
        ] })
      ]
    }
  );
};
const ElicitationTab = ({ pendingRequests, onResolve }) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(TabsContent, { value: "elicitations", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "h-96", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Alert, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { children: "When the server requests information from the user, requests will appear here for response." }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-4 space-y-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold", children: "Recent Requests" }),
      pendingRequests.map((request) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        ElicitationRequest,
        {
          request,
          onResolve
        },
        request.id
      )),
      pendingRequests.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-500", children: "No pending requests" })
    ] })
  ] }) });
};
const MetadataTab = ({
  metadata: metadata2,
  onMetadataChange
}) => {
  const [entries, setEntries] = reactExports.useState(() => {
    return Object.entries(metadata2).map(([key, value]) => ({ key, value }));
  });
  const addEntry = () => {
    setEntries([...entries, { key: "", value: "" }]);
  };
  const removeEntry = (index2) => {
    const newEntries = entries.filter((_2, i2) => i2 !== index2);
    setEntries(newEntries);
    updateMetadata(newEntries);
  };
  const updateEntry = (index2, field, value) => {
    const newEntries = [...entries];
    newEntries[index2][field] = value;
    setEntries(newEntries);
    updateMetadata(newEntries);
  };
  const updateMetadata = (newEntries) => {
    const metadataObject = {};
    newEntries.forEach(({ key, value }) => {
      const trimmedKey = key.trim();
      if (trimmedKey && value.trim() && hasValidMetaPrefix(trimmedKey) && !isReservedMetaKey(trimmedKey) && hasValidMetaName(trimmedKey)) {
        metadataObject[trimmedKey] = value.trim();
      }
    });
    onMetadataChange(metadataObject);
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(TabsContent, { value: "metadata", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold", children: "Metadata" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: "Key-value pairs that will be included in all MCP requests" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: addEntry, size: "sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4 mr-2" }),
        "Add Entry"
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: entries.map((entry, index2) => {
      const trimmedKey = entry.key.trim();
      const hasInvalidPrefix = trimmedKey !== "" && !hasValidMetaPrefix(trimmedKey);
      const isReservedKey = trimmedKey !== "" && isReservedMetaKey(trimmedKey);
      const hasInvalidName = trimmedKey !== "" && !hasValidMetaName(trimmedKey);
      const validationMessage = hasInvalidPrefix ? META_PREFIX_RULES_MESSAGE : isReservedKey ? RESERVED_NAMESPACE_MESSAGE : hasInvalidName ? META_NAME_RULES_MESSAGE : null;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center space-x-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Label$1, { htmlFor: `key-${index2}`, className: "sr-only", children: "Key" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                id: `key-${index2}`,
                placeholder: "Key",
                value: entry.key,
                onChange: (e2) => updateEntry(index2, "key", e2.target.value),
                "aria-invalid": Boolean(validationMessage),
                className: cn$1(
                  validationMessage && "border-red-500 focus-visible:ring-red-500 focus-visible:ring-1"
                )
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Label$1, { htmlFor: `value-${index2}`, className: "sr-only", children: "Value" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                id: `value-${index2}`,
                placeholder: "Value",
                value: entry.value,
                onChange: (e2) => updateEntry(index2, "value", e2.target.value),
                disabled: Boolean(validationMessage)
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: () => removeEntry(index2),
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" })
            }
          )
        ] }),
        validationMessage && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-red-600 dark:text-red-400", children: validationMessage })
      ] }, index2);
    }) }),
    entries.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-center py-8", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-500 dark:text-gray-400 mb-4", children: 'No metadata entries. Click "Add Entry" to add key-value pairs.' }) })
  ] }) });
};
const CONFIG_LOCAL_STORAGE_KEY = "inspectorConfig_v1";
const hasAppResourceUri = (tool) => {
  return Boolean(FZ(tool));
};
const cloneToolParams = (source) => {
  try {
    return structuredClone(source);
  } catch {
    return { ...source };
  }
};
const filterReservedMetadata = (metadata2) => {
  return Object.entries(metadata2).reduce(
    (acc, [key, value]) => {
      if (!isReservedMetaKey(key) && hasValidMetaPrefix(key) && hasValidMetaName(key)) {
        acc[key] = value;
      }
      return acc;
    },
    {}
  );
};
const App = () => {
  const [resources, setResources] = reactExports.useState([]);
  const [resourceTemplates, setResourceTemplates] = reactExports.useState([]);
  const [resourceContent, setResourceContent] = reactExports.useState("");
  const [resourceContentMap, setResourceContentMap] = reactExports.useState({});
  const [fetchingResources, setFetchingResources] = reactExports.useState(
    /* @__PURE__ */ new Set()
  );
  const [prompts, setPrompts] = reactExports.useState([]);
  const [promptContent, setPromptContent] = reactExports.useState("");
  const [tools, setTools] = reactExports.useState([]);
  const [tasks, setTasks] = reactExports.useState([]);
  const [toolResult, setToolResult] = reactExports.useState(null);
  const [prefilledAppsToolCall, setPrefilledAppsToolCall] = reactExports.useState(null);
  const [errors2, setErrors] = reactExports.useState({
    resources: null,
    prompts: null,
    tools: null,
    tasks: null
  });
  const [command, setCommand] = reactExports.useState(getInitialCommand);
  const [args, setArgs] = reactExports.useState(getInitialArgs);
  const [sseUrl, setSseUrl] = reactExports.useState(getInitialSseUrl);
  const [transportType, setTransportType] = reactExports.useState(getInitialTransportType);
  const [connectionType, setConnectionType] = reactExports.useState(
    () => {
      return localStorage.getItem("lastConnectionType") || "proxy";
    }
  );
  const [logLevel, setLogLevel] = reactExports.useState("debug");
  const [notifications, setNotifications] = reactExports.useState([]);
  const [roots, setRoots] = reactExports.useState([]);
  const [env, setEnv] = reactExports.useState({});
  const [config2, setConfig] = reactExports.useState(
    () => initializeInspectorConfig(CONFIG_LOCAL_STORAGE_KEY)
  );
  const [bearerToken, setBearerToken] = reactExports.useState(() => {
    return localStorage.getItem("lastBearerToken") || "";
  });
  const [headerName, setHeaderName] = reactExports.useState(() => {
    return localStorage.getItem("lastHeaderName") || "";
  });
  const [oauthClientId, setOauthClientId] = reactExports.useState(() => {
    return localStorage.getItem("lastOauthClientId") || "";
  });
  const [oauthScope, setOauthScope] = reactExports.useState(() => {
    return localStorage.getItem("lastOauthScope") || "";
  });
  const [oauthClientSecret, setOauthClientSecret] = reactExports.useState(() => {
    return localStorage.getItem("lastOauthClientSecret") || "";
  });
  const [customHeaders, setCustomHeaders] = reactExports.useState(() => {
    const savedHeaders = localStorage.getItem("lastCustomHeaders");
    if (savedHeaders) {
      try {
        return JSON.parse(savedHeaders);
      } catch (error) {
        console.warn(
          `Failed to parse custom headers: "${savedHeaders}", will try legacy migration`,
          error
        );
      }
    }
    const legacyToken = localStorage.getItem("lastBearerToken") || "";
    const legacyHeaderName = localStorage.getItem("lastHeaderName") || "";
    if (legacyToken) {
      return migrateFromLegacyAuth(legacyToken, legacyHeaderName);
    }
    return [
      {
        name: "Authorization",
        value: "Bearer ",
        enabled: false
      }
    ];
  });
  const [pendingSampleRequests, setPendingSampleRequests] = reactExports.useState([]);
  const [pendingElicitationRequests, setPendingElicitationRequests] = reactExports.useState([]);
  const [isAuthDebuggerVisible, setIsAuthDebuggerVisible] = reactExports.useState(false);
  const [authState, setAuthState] = reactExports.useState(EMPTY_DEBUGGER_STATE);
  const [metadata2, setMetadata] = reactExports.useState(() => {
    const savedMetadata = localStorage.getItem("lastMetadata");
    if (savedMetadata) {
      try {
        const parsed = JSON.parse(savedMetadata);
        if (parsed && typeof parsed === "object") {
          return filterReservedMetadata(parsed);
        }
      } catch (error) {
        console.warn("Failed to parse saved metadata:", error);
      }
    }
    return {};
  });
  const updateAuthState = (updates) => {
    setAuthState((prev) => ({ ...prev, ...updates }));
  };
  const handleMetadataChange = (newMetadata) => {
    const sanitizedMetadata = filterReservedMetadata(newMetadata);
    setMetadata(sanitizedMetadata);
    localStorage.setItem("lastMetadata", JSON.stringify(sanitizedMetadata));
  };
  const nextRequestId = reactExports.useRef(0);
  const rootsRef = reactExports.useRef([]);
  const [selectedResource, setSelectedResource] = reactExports.useState(
    null
  );
  const [resourceSubscriptions, setResourceSubscriptions] = reactExports.useState(/* @__PURE__ */ new Set());
  const [selectedPrompt, setSelectedPrompt] = reactExports.useState(null);
  const [selectedTool, setSelectedTool] = reactExports.useState(null);
  const [selectedTask, setSelectedTask] = reactExports.useState(null);
  const [isPollingTask, setIsPollingTask] = reactExports.useState(false);
  const [nextResourceCursor, setNextResourceCursor] = reactExports.useState();
  const [nextResourceTemplateCursor, setNextResourceTemplateCursor] = reactExports.useState();
  const [nextPromptCursor, setNextPromptCursor] = reactExports.useState();
  const [nextToolCursor, setNextToolCursor] = reactExports.useState();
  const [nextTaskCursor, setNextTaskCursor] = reactExports.useState();
  const progressTokenRef = reactExports.useRef(0);
  const prefilledAppsToolCallIdRef = reactExports.useRef(0);
  const [activeTab, setActiveTab] = reactExports.useState(() => {
    const hash = window.location.hash.slice(1);
    const initialTab = hash || "resources";
    return initialTab;
  });
  const currentTabRef = reactExports.useRef(activeTab);
  const lastToolCallOriginTabRef = reactExports.useRef(activeTab);
  reactExports.useEffect(() => {
    currentTabRef.current = activeTab;
  }, [activeTab]);
  const navigateToOriginatingTab = (originatingTab) => {
    if (!originatingTab) return;
    const validTabs = [
      ...serverCapabilities?.resources ? ["resources"] : [],
      ...serverCapabilities?.prompts ? ["prompts"] : [],
      ...serverCapabilities?.tools ? ["tools"] : [],
      ...serverCapabilities?.tasks ? ["tasks"] : [],
      "apps",
      "ping",
      "sampling",
      "elicitations",
      "roots",
      "auth",
      "metadata"
    ];
    if (!validTabs.includes(originatingTab)) return;
    setActiveTab(originatingTab);
    window.location.hash = originatingTab;
    setTimeout(() => {
      setActiveTab(originatingTab);
      window.location.hash = originatingTab;
    }, 100);
  };
  const { height: historyPaneHeight, handleDragStart } = useDraggablePane(300);
  const {
    width: sidebarWidth,
    isDragging: isSidebarDragging,
    handleDragStart: handleSidebarDragStart
  } = useDraggableSidebar(320);
  const selectedTaskRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    selectedTaskRef.current = selectedTask;
  }, [selectedTask]);
  const {
    connectionStatus,
    serverCapabilities,
    serverImplementation,
    mcpClient,
    requestHistory,
    clearRequestHistory,
    makeRequest,
    cancelTask: cancelMcpTask,
    listTasks: listMcpTasks,
    sendNotification,
    handleCompletion,
    completionsSupported,
    connect: connectMcpServer,
    disconnect: disconnectMcpServer
  } = useConnection({
    transportType,
    command,
    args,
    sseUrl,
    env,
    customHeaders,
    oauthClientId,
    oauthClientSecret,
    oauthScope,
    config: config2,
    connectionType,
    onNotification: (notification) => {
      setNotifications((prev) => [...prev, notification]);
      if (notification.method === "notifications/tasks/list_changed") {
        void listTasks();
      }
      if (notification.method === "notifications/tasks/status") {
        const task = notification.params;
        setTasks((prev) => {
          const exists = prev.some((t2) => t2.taskId === task.taskId);
          if (exists) {
            return prev.map((t2) => t2.taskId === task.taskId ? task : t2);
          } else {
            return [task, ...prev];
          }
        });
        if (selectedTaskRef.current?.taskId === task.taskId) {
          setSelectedTask(task);
        }
      }
    },
    onPendingRequest: (request, resolve2, reject) => {
      const currentTab = lastToolCallOriginTabRef.current;
      setPendingSampleRequests((prev) => [
        ...prev,
        {
          id: nextRequestId.current++,
          request,
          originatingTab: currentTab,
          resolve: resolve2,
          reject
        }
      ]);
      setActiveTab("sampling");
      window.location.hash = "sampling";
    },
    onElicitationRequest: (request, resolve2) => {
      const currentTab = lastToolCallOriginTabRef.current;
      const requestId = nextRequestId.current++;
      const requestData = request.params.mode === "url" ? {
        id: requestId,
        mode: "url",
        message: request.params.message,
        url: request.params.url,
        elicitationId: request.params.elicitationId
      } : {
        id: requestId,
        message: request.params.message,
        requestedSchema: request.params.requestedSchema
      };
      setPendingElicitationRequests((prev) => [
        ...prev,
        {
          id: requestId,
          request: requestData,
          originatingTab: currentTab,
          resolve: resolve2,
          decline: (error) => {
            console.error("Elicitation request rejected:", error);
          }
        }
      ]);
      setActiveTab("elicitations");
      window.location.hash = "elicitations";
    },
    getRoots: () => rootsRef.current,
    defaultLoggingLevel: logLevel,
    metadata: metadata2
  });
  reactExports.useEffect(() => {
    if (serverCapabilities) {
      const hash = window.location.hash.slice(1);
      const validTabs = [
        ...serverCapabilities?.resources ? ["resources"] : [],
        ...serverCapabilities?.prompts ? ["prompts"] : [],
        ...serverCapabilities?.tools ? ["tools"] : [],
        ...serverCapabilities?.tasks ? ["tasks"] : [],
        "apps",
        "ping",
        "sampling",
        "elicitations",
        "roots",
        "auth",
        "metadata"
      ];
      const isValidTab = validTabs.includes(hash);
      if (!isValidTab) {
        const defaultTab = serverCapabilities?.resources ? "resources" : serverCapabilities?.prompts ? "prompts" : serverCapabilities?.tools ? "tools" : serverCapabilities?.tasks ? "tasks" : "ping";
        setActiveTab(defaultTab);
        window.location.hash = defaultTab;
      }
    }
  }, [serverCapabilities]);
  reactExports.useEffect(() => {
    if (mcpClient && activeTab === "tasks") {
      void listTasks();
    }
  }, [mcpClient, activeTab]);
  reactExports.useEffect(() => {
    if (mcpClient && activeTab === "apps" && serverCapabilities?.tools) {
      void listTools();
    }
  }, [mcpClient, activeTab, serverCapabilities?.tools]);
  reactExports.useEffect(() => {
    localStorage.setItem("lastCommand", command);
  }, [command]);
  reactExports.useEffect(() => {
    localStorage.setItem("lastArgs", args);
  }, [args]);
  reactExports.useEffect(() => {
    localStorage.setItem("lastSseUrl", sseUrl);
  }, [sseUrl]);
  reactExports.useEffect(() => {
    localStorage.setItem("lastTransportType", transportType);
  }, [transportType]);
  reactExports.useEffect(() => {
    localStorage.setItem("lastConnectionType", connectionType);
  }, [connectionType]);
  reactExports.useEffect(() => {
    if (bearerToken) {
      localStorage.setItem("lastBearerToken", bearerToken);
    } else {
      localStorage.removeItem("lastBearerToken");
    }
  }, [bearerToken]);
  reactExports.useEffect(() => {
    if (headerName) {
      localStorage.setItem("lastHeaderName", headerName);
    } else {
      localStorage.removeItem("lastHeaderName");
    }
  }, [headerName]);
  reactExports.useEffect(() => {
    localStorage.setItem("lastCustomHeaders", JSON.stringify(customHeaders));
  }, [customHeaders]);
  reactExports.useEffect(() => {
    if (customHeaders.length === 0 && (bearerToken || headerName)) {
      const migratedHeaders = migrateFromLegacyAuth(bearerToken, headerName);
      if (migratedHeaders.length > 0) {
        setCustomHeaders(migratedHeaders);
        setBearerToken("");
        setHeaderName("");
      }
    }
  }, [bearerToken, headerName, customHeaders, setCustomHeaders]);
  reactExports.useEffect(() => {
    localStorage.setItem("lastOauthClientId", oauthClientId);
  }, [oauthClientId]);
  reactExports.useEffect(() => {
    localStorage.setItem("lastOauthScope", oauthScope);
  }, [oauthScope]);
  reactExports.useEffect(() => {
    localStorage.setItem("lastOauthClientSecret", oauthClientSecret);
  }, [oauthClientSecret]);
  reactExports.useEffect(() => {
    saveInspectorConfig(CONFIG_LOCAL_STORAGE_KEY, config2);
  }, [config2]);
  const onOAuthConnect = reactExports.useCallback(
    (serverUrl) => {
      setSseUrl(serverUrl);
      setIsAuthDebuggerVisible(false);
      void connectMcpServer();
    },
    [connectMcpServer]
  );
  const onOAuthDebugConnect = reactExports.useCallback(
    async ({
      authorizationCode,
      errorMsg,
      restoredState
    }) => {
      setIsAuthDebuggerVisible(true);
      if (errorMsg) {
        updateAuthState({
          latestError: new Error(errorMsg)
        });
        return;
      }
      if (restoredState && authorizationCode) {
        let currentState = {
          ...restoredState,
          authorizationCode,
          oauthStep: "token_request",
          isInitiatingAuth: true,
          statusMessage: null,
          latestError: null
        };
        try {
          const fetchFn = connectionType === "proxy" && config2 ? createProxyFetch(config2) : void 0;
          const stateMachine = new OAuthStateMachine(
            sseUrl,
            (updates) => {
              currentState = { ...currentState, ...updates };
            },
            fetchFn
          );
          while (currentState.oauthStep !== "complete" && currentState.oauthStep !== "authorization_code") {
            await stateMachine.executeStep(currentState);
          }
          if (currentState.oauthStep === "complete") {
            updateAuthState({
              ...currentState,
              statusMessage: {
                type: "success",
                message: "Authentication completed successfully"
              },
              isInitiatingAuth: false
            });
          }
        } catch (error) {
          console.error("OAuth continuation error:", error);
          updateAuthState({
            latestError: error instanceof Error ? error : new Error(String(error)),
            statusMessage: {
              type: "error",
              message: `Failed to complete OAuth flow: ${error instanceof Error ? error.message : String(error)}`
            },
            isInitiatingAuth: false
          });
        }
      } else if (authorizationCode) {
        updateAuthState({
          authorizationCode,
          oauthStep: "token_request"
        });
      }
    },
    [sseUrl, connectionType, config2]
  );
  reactExports.useEffect(() => {
    const loadOAuthTokens = async () => {
      try {
        if (sseUrl) {
          const key = getServerSpecificKey(SESSION_KEYS.TOKENS, sseUrl);
          const tokens = sessionStorage.getItem(key);
          if (tokens) {
            const parsedTokens = await OAuthTokensSchema.parseAsync(
              JSON.parse(tokens)
            );
            updateAuthState({
              oauthTokens: parsedTokens,
              oauthStep: "complete"
            });
          }
        }
      } catch (error) {
        console.error("Error loading OAuth tokens:", error);
      }
    };
    loadOAuthTokens();
  }, [sseUrl]);
  reactExports.useEffect(() => {
    const headers = {};
    const { token: proxyAuthToken, header: proxyAuthTokenHeader } = getMCPProxyAuthToken(config2);
    if (proxyAuthToken) {
      headers[proxyAuthTokenHeader] = `Bearer ${proxyAuthToken}`;
    }
    fetch(`${getMCPProxyAddress(config2)}/config`, { headers }).then((response) => response.json()).then((data2) => {
      setEnv(data2.defaultEnvironment);
      if (data2.defaultCommand) {
        setCommand(data2.defaultCommand);
      }
      if (data2.defaultArgs) {
        setArgs(data2.defaultArgs);
      }
      if (data2.defaultTransport) {
        setTransportType(
          data2.defaultTransport
        );
      }
      if (data2.defaultServerUrl) {
        setSseUrl(data2.defaultServerUrl);
      }
    }).catch(
      (error) => console.error("Error fetching default environment:", error)
    );
  }, [config2]);
  reactExports.useEffect(() => {
    rootsRef.current = roots;
  }, [roots]);
  reactExports.useEffect(() => {
    if (mcpClient && !window.location.hash) {
      const defaultTab = serverCapabilities?.resources ? "resources" : serverCapabilities?.prompts ? "prompts" : serverCapabilities?.tools ? "tools" : serverCapabilities?.tasks ? "tasks" : "ping";
      window.location.hash = defaultTab;
    } else if (!mcpClient && window.location.hash) {
      window.history.replaceState(
        null,
        "",
        window.location.pathname + window.location.search
      );
    }
  }, [mcpClient, serverCapabilities]);
  reactExports.useEffect(() => {
    const handleHashChange = () => {
      const hash = window.location.hash.slice(1);
      if (hash && hash !== activeTab) {
        setActiveTab(hash);
      }
    };
    window.addEventListener("hashchange", handleHashChange);
    return () => window.removeEventListener("hashchange", handleHashChange);
  }, [activeTab]);
  const handleApproveSampling = (id2, result) => {
    setPendingSampleRequests((prev) => {
      const request = prev.find((r2) => r2.id === id2);
      request?.resolve(result);
      navigateToOriginatingTab(request?.originatingTab);
      return prev.filter((r2) => r2.id !== id2);
    });
  };
  const handleRejectSampling = (id2) => {
    setPendingSampleRequests((prev) => {
      const request = prev.find((r2) => r2.id === id2);
      request?.reject(new Error("Sampling request rejected"));
      navigateToOriginatingTab(request?.originatingTab);
      return prev.filter((r2) => r2.id !== id2);
    });
  };
  const handleResolveElicitation = (id2, response) => {
    setPendingElicitationRequests((prev) => {
      const request = prev.find((r2) => r2.id === id2);
      if (request) {
        request.resolve(response);
        if (request.originatingTab) {
          const originatingTab = request.originatingTab;
          const validTabs = [
            ...serverCapabilities?.resources ? ["resources"] : [],
            ...serverCapabilities?.prompts ? ["prompts"] : [],
            ...serverCapabilities?.tools ? ["tools"] : [],
            ...serverCapabilities?.tasks ? ["tasks"] : [],
            "apps",
            "ping",
            "sampling",
            "elicitations",
            "roots",
            "auth",
            "metadata"
          ];
          if (validTabs.includes(originatingTab)) {
            setActiveTab(originatingTab);
            window.location.hash = originatingTab;
            setTimeout(() => {
              setActiveTab(originatingTab);
              window.location.hash = originatingTab;
            }, 100);
          }
        }
      }
      return prev.filter((r2) => r2.id !== id2);
    });
  };
  const clearError = (tabKey) => {
    setErrors((prev) => ({ ...prev, [tabKey]: null }));
  };
  const sendMCPRequest = async (request, schema, tabKey) => {
    try {
      const response = await makeRequest(request, schema);
      if (tabKey !== void 0) {
        clearError(tabKey);
      }
      return response;
    } catch (e2) {
      const errorString = e2.message ?? String(e2);
      if (tabKey !== void 0) {
        setErrors((prev) => ({
          ...prev,
          [tabKey]: errorString
        }));
      }
      throw e2;
    }
  };
  const listResources = async () => {
    const response = await sendMCPRequest(
      {
        method: "resources/list",
        params: nextResourceCursor ? { cursor: nextResourceCursor } : {}
      },
      ListResourcesResultSchema,
      "resources"
    );
    setResources(resources.concat(response.resources ?? []));
    setNextResourceCursor(response.nextCursor);
  };
  const listResourceTemplates = async () => {
    const response = await sendMCPRequest(
      {
        method: "resources/templates/list",
        params: nextResourceTemplateCursor ? { cursor: nextResourceTemplateCursor } : {}
      },
      ListResourceTemplatesResultSchema,
      "resources"
    );
    setResourceTemplates(
      resourceTemplates.concat(response.resourceTemplates ?? [])
    );
    setNextResourceTemplateCursor(response.nextCursor);
  };
  const getPrompt = async (name2, args2 = {}) => {
    lastToolCallOriginTabRef.current = currentTabRef.current;
    const response = await sendMCPRequest(
      {
        method: "prompts/get",
        params: { name: name2, arguments: args2 }
      },
      GetPromptResultSchema,
      "prompts"
    );
    setPromptContent(JSON.stringify(response, null, 2));
  };
  const readResource = async (uri2) => {
    if (fetchingResources.has(uri2) || resourceContentMap[uri2]) {
      return;
    }
    console.log("[App] Reading resource:", uri2);
    setFetchingResources((prev) => new Set(prev).add(uri2));
    lastToolCallOriginTabRef.current = currentTabRef.current;
    try {
      const response = await sendMCPRequest(
        {
          method: "resources/read",
          params: { uri: uri2 }
        },
        ReadResourceResultSchema,
        "resources"
      );
      console.log("[App] Resource read response:", {
        uri: uri2,
        responseLength: JSON.stringify(response).length,
        hasContents: !!response.contents
      });
      const content = JSON.stringify(response, null, 2);
      setResourceContent(content);
      setResourceContentMap((prev) => ({
        ...prev,
        [uri2]: content
      }));
    } catch (error) {
      console.error(`[App] Failed to read resource ${uri2}:`, error);
      const errorString = error.message ?? String(error);
      setResourceContentMap((prev) => ({
        ...prev,
        [uri2]: JSON.stringify({ error: errorString })
      }));
    } finally {
      setFetchingResources((prev) => {
        const next = new Set(prev);
        next.delete(uri2);
        return next;
      });
    }
  };
  const subscribeToResource = async (uri2) => {
    if (!resourceSubscriptions.has(uri2)) {
      await sendMCPRequest(
        {
          method: "resources/subscribe",
          params: { uri: uri2 }
        },
        objectType({}),
        "resources"
      );
      const clone2 = new Set(resourceSubscriptions);
      clone2.add(uri2);
      setResourceSubscriptions(clone2);
    }
  };
  const unsubscribeFromResource = async (uri2) => {
    if (resourceSubscriptions.has(uri2)) {
      await sendMCPRequest(
        {
          method: "resources/unsubscribe",
          params: { uri: uri2 }
        },
        objectType({}),
        "resources"
      );
      const clone2 = new Set(resourceSubscriptions);
      clone2.delete(uri2);
      setResourceSubscriptions(clone2);
    }
  };
  const listPrompts = async () => {
    const response = await sendMCPRequest(
      {
        method: "prompts/list",
        params: nextPromptCursor ? { cursor: nextPromptCursor } : {}
      },
      ListPromptsResultSchema,
      "prompts"
    );
    setPrompts(response.prompts);
    setNextPromptCursor(response.nextCursor);
  };
  const listTools = async () => {
    const response = await sendMCPRequest(
      {
        method: "tools/list",
        params: nextToolCursor ? { cursor: nextToolCursor } : {}
      },
      ListToolsResultSchema,
      "tools"
    );
    setTools(response.tools);
    setNextToolCursor(response.nextCursor);
    cacheToolOutputSchemas(response.tools);
  };
  const callTool = async (name2, params, toolMetadata, runAsTask) => {
    lastToolCallOriginTabRef.current = currentTabRef.current;
    try {
      const tool = tools.find((t2) => t2.name === name2);
      const cleanedParams = tool?.inputSchema ? cleanParams(params, tool.inputSchema) : params;
      const mergedMetadata = {
        ...metadata2,
        // General metadata
        progressToken: progressTokenRef.current++,
        ...toolMetadata
        // Tool-specific metadata
      };
      const request = {
        method: "tools/call",
        params: {
          name: name2,
          arguments: cleanedParams,
          _meta: mergedMetadata
        }
      };
      if (runAsTask) {
        request.params = {
          ...request.params,
          task: {
            ttl: getMCPTaskTtl(config2)
          }
        };
      }
      const response = await sendMCPRequest(
        request,
        CompatibilityCallToolResultSchema,
        "tools"
      );
      const isTaskResult = (res) => !!res && typeof res === "object" && "task" in res && !!res.task && typeof res.task === "object" && "taskId" in res.task;
      if (runAsTask && isTaskResult(response)) {
        const taskId = response.task.taskId;
        const pollInterval = response.task.pollInterval;
        setIsPollingTask(true);
        const initialResponseMeta = response && typeof response === "object" && "_meta" in response ? response._meta ?? {} : void 0;
        let latestToolResult = {
          content: [
            {
              type: "text",
              text: `Task created: ${taskId}. Polling for status...`
            }
          ],
          _meta: {
            ...initialResponseMeta || {},
            "io.modelcontextprotocol/related-task": { taskId }
          }
        };
        setToolResult(latestToolResult);
        let taskCompleted = false;
        while (!taskCompleted) {
          try {
            await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
            const taskStatus = await sendMCPRequest(
              {
                method: "tasks/get",
                params: { taskId }
              },
              GetTaskResultSchema
            );
            if (taskStatus.status === "completed" || taskStatus.status === "failed" || taskStatus.status === "cancelled") {
              taskCompleted = true;
              console.log(
                `Polling complete for task ${taskId}: ${taskStatus.status}`
              );
              if (taskStatus.status === "completed") {
                console.log(`Fetching result for task ${taskId}`);
                const result = await sendMCPRequest(
                  {
                    method: "tasks/result",
                    params: { taskId }
                  },
                  CompatibilityCallToolResultSchema
                );
                console.log(`Result received for task ${taskId}:`, result);
                latestToolResult = result;
                setToolResult(latestToolResult);
                void listTasks();
              } else {
                latestToolResult = {
                  content: [
                    {
                      type: "text",
                      text: `Task ${taskStatus.status}: ${taskStatus.statusMessage || "No additional information"}`
                    }
                  ],
                  isError: true
                };
                setToolResult(latestToolResult);
                void listTasks();
              }
            } else {
              const pollingResponseMeta = response && typeof response === "object" && "_meta" in response ? response._meta ?? {} : void 0;
              latestToolResult = {
                content: [
                  {
                    type: "text",
                    text: `Task status: ${taskStatus.status}${taskStatus.statusMessage ? ` - ${taskStatus.statusMessage}` : ""}. Polling...`
                  }
                ],
                _meta: {
                  ...pollingResponseMeta || {},
                  "io.modelcontextprotocol/related-task": { taskId }
                }
              };
              setToolResult(latestToolResult);
              void listTasks();
            }
          } catch (pollingError) {
            console.error("Error polling task status:", pollingError);
            latestToolResult = {
              content: [
                {
                  type: "text",
                  text: `Error polling task status: ${pollingError instanceof Error ? pollingError.message : String(pollingError)}`
                }
              ],
              isError: true
            };
            setToolResult(latestToolResult);
            taskCompleted = true;
          }
        }
        setIsPollingTask(false);
        setErrors((prev) => ({ ...prev, tools: null }));
        return latestToolResult;
      } else {
        const directResult = response;
        setToolResult(directResult);
        setErrors((prev) => ({ ...prev, tools: null }));
        return directResult;
      }
    } catch (e2) {
      const toolResult2 = {
        content: [
          {
            type: "text",
            text: e2.message ?? String(e2)
          }
        ],
        isError: true
      };
      setToolResult(toolResult2);
      setErrors((prev) => ({ ...prev, tools: null }));
      return toolResult2;
    }
  };
  const listTasks = reactExports.useCallback(async () => {
    try {
      const response = await listMcpTasks(nextTaskCursor);
      setTasks(response.tasks);
      setNextTaskCursor(response.nextCursor);
      setErrors((prev) => ({ ...prev, tasks: null }));
    } catch (e2) {
      setErrors((prev) => ({
        ...prev,
        tasks: e2.message ?? String(e2)
      }));
    }
  }, [listMcpTasks, nextTaskCursor]);
  const cancelTask = async (taskId) => {
    try {
      const response = await cancelMcpTask(taskId);
      setTasks((prev) => prev.map((t2) => t2.taskId === taskId ? response : t2));
      if (selectedTask?.taskId === taskId) {
        setSelectedTask(response);
      }
      clearError("tasks");
    } catch (e2) {
      setErrors((prev) => ({
        ...prev,
        tasks: e2.message ?? String(e2)
      }));
    }
  };
  const handleRootsChange = async () => {
    await sendNotification({ method: "notifications/roots/list_changed" });
  };
  const handleClearNotifications = () => {
    setNotifications([]);
  };
  const sendLogLevelRequest = async (level) => {
    await sendMCPRequest(
      {
        method: "logging/setLevel",
        params: { level }
      },
      objectType({})
    );
    setLogLevel(level);
  };
  const AuthDebuggerWrapper = () => /* @__PURE__ */ jsxRuntimeExports.jsx(TabsContent, { value: "auth", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
    AuthDebugger,
    {
      serverUrl: sseUrl,
      onBack: () => setIsAuthDebuggerVisible(false),
      authState,
      updateAuthState,
      config: config2,
      connectionType
    }
  ) });
  if (window.location.pathname === "/oauth/callback") {
    const OAuthCallback = React.lazy(
      () => __vitePreload(() => import("./OAuthCallback-Cd9z3Q8P.js"), true ? [] : void 0)
    );
    return /* @__PURE__ */ jsxRuntimeExports.jsx(reactExports.Suspense, { fallback: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: "Loading..." }), children: /* @__PURE__ */ jsxRuntimeExports.jsx(OAuthCallback, { onConnect: onOAuthConnect }) });
  }
  if (window.location.pathname === "/oauth/callback/debug") {
    const OAuthDebugCallback = React.lazy(
      () => __vitePreload(() => import("./OAuthDebugCallback-h_lUPqCA.js"), true ? [] : void 0)
    );
    return /* @__PURE__ */ jsxRuntimeExports.jsx(reactExports.Suspense, { fallback: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: "Loading..." }), children: /* @__PURE__ */ jsxRuntimeExports.jsx(OAuthDebugCallback, { onConnect: onOAuthDebugConnect }) });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex h-screen bg-background", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        style: {
          width: sidebarWidth,
          minWidth: 200,
          maxWidth: 600,
          transition: isSidebarDragging ? "none" : "width 0.15s"
        },
        className: "bg-card border-r border-border flex flex-col h-full relative",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Sidebar,
            {
              connectionStatus,
              transportType,
              setTransportType,
              command,
              setCommand,
              args,
              setArgs,
              sseUrl,
              setSseUrl,
              env,
              setEnv,
              config: config2,
              setConfig,
              customHeaders,
              setCustomHeaders,
              oauthClientId,
              setOauthClientId,
              oauthClientSecret,
              setOauthClientSecret,
              oauthScope,
              setOauthScope,
              onConnect: connectMcpServer,
              onDisconnect: disconnectMcpServer,
              logLevel,
              sendLogLevelRequest,
              loggingSupported: !!serverCapabilities?.logging || false,
              connectionType,
              setConnectionType,
              serverImplementation
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              onMouseDown: handleSidebarDragStart,
              style: {
                cursor: "col-resize",
                position: "absolute",
                top: 0,
                right: 0,
                width: 6,
                height: "100%",
                zIndex: 10,
                background: isSidebarDragging ? "rgba(0,0,0,0.08)" : "transparent"
              },
              "aria-label": "Resize sidebar",
              "data-testid": "sidebar-drag-handle"
            }
          )
        ]
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 flex flex-col overflow-hidden", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-1 overflow-auto", children: mcpClient ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Tabs,
        {
          value: activeTab,
          className: "w-full p-4",
          onValueChange: (value) => {
            setActiveTab(value);
            window.location.hash = value;
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(TabsList, { className: "mb-4 py-0", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                TabsTrigger,
                {
                  value: "resources",
                  disabled: !serverCapabilities?.resources,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Files, { className: "w-4 h-4 mr-2" }),
                    "Resources"
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                TabsTrigger,
                {
                  value: "prompts",
                  disabled: !serverCapabilities?.prompts,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(MessageSquare, { className: "w-4 h-4 mr-2" }),
                    "Prompts"
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                TabsTrigger,
                {
                  value: "tools",
                  disabled: !serverCapabilities?.tools,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Hammer, { className: "w-4 h-4 mr-2" }),
                    "Tools"
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                TabsTrigger,
                {
                  value: "tasks",
                  disabled: !serverCapabilities?.tasks,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(ListTodo, { className: "w-4 h-4 mr-2" }),
                    "Tasks"
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(TabsTrigger, { value: "apps", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(AppWindow, { className: "w-4 h-4 mr-2" }),
                "Apps"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(TabsTrigger, { value: "ping", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Bell, { className: "w-4 h-4 mr-2" }),
                "Ping"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(TabsTrigger, { value: "sampling", className: "relative", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Hash, { className: "w-4 h-4 mr-2" }),
                "Sampling",
                pendingSampleRequests.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full h-4 w-4 flex items-center justify-center", children: pendingSampleRequests.length })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(TabsTrigger, { value: "elicitations", className: "relative", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(MessageSquare, { className: "w-4 h-4 mr-2" }),
                "Elicitations",
                pendingElicitationRequests.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full h-4 w-4 flex items-center justify-center", children: pendingElicitationRequests.length })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(TabsTrigger, { value: "roots", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(FolderTree, { className: "w-4 h-4 mr-2" }),
                "Roots"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(TabsTrigger, { value: "auth", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Key, { className: "w-4 h-4 mr-2" }),
                "Auth"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(TabsTrigger, { value: "metadata", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Settings, { className: "w-4 h-4 mr-2" }),
                "Metadata"
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full", children: !serverCapabilities?.resources && !serverCapabilities?.prompts && !serverCapabilities?.tools ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-lg text-gray-500 dark:text-gray-400", children: "The connected server does not support any MCP capabilities" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                PingTab,
                {
                  onPingClick: () => {
                    void sendMCPRequest(
                      {
                        method: "ping"
                      },
                      EmptyResultSchema
                    );
                  }
                }
              )
            ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                ResourcesTab,
                {
                  resources,
                  resourceTemplates,
                  listResources: () => {
                    clearError("resources");
                    listResources();
                  },
                  clearResources: () => {
                    setResources([]);
                    setNextResourceCursor(void 0);
                  },
                  listResourceTemplates: () => {
                    clearError("resources");
                    listResourceTemplates();
                  },
                  clearResourceTemplates: () => {
                    setResourceTemplates([]);
                    setNextResourceTemplateCursor(void 0);
                  },
                  readResource: (uri2) => {
                    clearError("resources");
                    readResource(uri2);
                  },
                  selectedResource,
                  setSelectedResource: (resource) => {
                    clearError("resources");
                    setSelectedResource(resource);
                  },
                  resourceSubscriptionsSupported: serverCapabilities?.resources?.subscribe || false,
                  resourceSubscriptions,
                  subscribeToResource: (uri2) => {
                    clearError("resources");
                    subscribeToResource(uri2);
                  },
                  unsubscribeFromResource: (uri2) => {
                    clearError("resources");
                    unsubscribeFromResource(uri2);
                  },
                  handleCompletion,
                  completionsSupported,
                  resourceContent,
                  nextCursor: nextResourceCursor,
                  nextTemplateCursor: nextResourceTemplateCursor,
                  error: errors2.resources
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                PromptsTab,
                {
                  prompts,
                  listPrompts: () => {
                    clearError("prompts");
                    listPrompts();
                  },
                  clearPrompts: () => {
                    setPrompts([]);
                    setNextPromptCursor(void 0);
                  },
                  getPrompt: (name2, args2) => {
                    clearError("prompts");
                    getPrompt(name2, args2);
                  },
                  selectedPrompt,
                  setSelectedPrompt: (prompt) => {
                    clearError("prompts");
                    setSelectedPrompt(prompt);
                    setPromptContent("");
                  },
                  handleCompletion,
                  completionsSupported,
                  promptContent,
                  nextCursor: nextPromptCursor,
                  error: errors2.prompts
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                ToolsTab,
                {
                  serverSupportsTaskRequests: !!serverCapabilities?.tasks?.requests?.tools?.call,
                  tools,
                  listTools: () => {
                    clearError("tools");
                    listTools();
                  },
                  clearTools: () => {
                    setTools([]);
                    setNextToolCursor(void 0);
                    cacheToolOutputSchemas([]);
                  },
                  callTool: async (name2, params, metadata22, runAsTask) => {
                    clearError("tools");
                    setToolResult(null);
                    const result = await callTool(
                      name2,
                      params,
                      metadata22,
                      runAsTask
                    );
                    const calledTool = tools.find(
                      (tool) => tool.name === name2
                    );
                    if (calledTool && hasAppResourceUri(calledTool)) {
                      setPrefilledAppsToolCall({
                        id: ++prefilledAppsToolCallIdRef.current,
                        toolName: name2,
                        params: cloneToolParams(params),
                        result
                      });
                    } else {
                      setPrefilledAppsToolCall(null);
                    }
                    return result;
                  },
                  selectedTool,
                  setSelectedTool: (tool) => {
                    clearError("tools");
                    setSelectedTool(tool);
                    setToolResult(null);
                  },
                  toolResult,
                  isPollingTask,
                  nextCursor: nextToolCursor,
                  error: errors2.tools,
                  resourceContent: resourceContentMap,
                  onReadResource: (uri2) => {
                    clearError("resources");
                    readResource(uri2);
                  }
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                TasksTab,
                {
                  tasks,
                  listTasks: () => {
                    clearError("tasks");
                    listTasks();
                  },
                  clearTasks: () => {
                    setTasks([]);
                    setNextTaskCursor(void 0);
                  },
                  cancelTask,
                  selectedTask,
                  setSelectedTask: (task) => {
                    clearError("tasks");
                    setSelectedTask(task);
                  },
                  error: errors2.tasks,
                  nextCursor: nextTaskCursor
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                AppsTab,
                {
                  sandboxPath: `${getMCPProxyAddress(config2)}/sandbox`,
                  tools,
                  listTools: () => {
                    clearError("tools");
                    listTools();
                  },
                  callTool: async (name2, params, metadata22, runAsTask) => {
                    clearError("tools");
                    setToolResult(null);
                    return callTool(name2, params, metadata22, runAsTask);
                  },
                  prefilledToolCall: prefilledAppsToolCall,
                  onPrefilledToolCallConsumed: (callId) => {
                    setPrefilledAppsToolCall(
                      (prev) => prev?.id === callId ? null : prev
                    );
                  },
                  error: errors2.tools,
                  mcpClient,
                  onNotification: (notification) => {
                    setNotifications((prev) => [...prev, notification]);
                  }
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(ConsoleTab, {}),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                PingTab,
                {
                  onPingClick: () => {
                    void sendMCPRequest(
                      {
                        method: "ping"
                      },
                      EmptyResultSchema
                    );
                  }
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                SamplingTab,
                {
                  pendingRequests: pendingSampleRequests,
                  onApprove: handleApproveSampling,
                  onReject: handleRejectSampling
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                ElicitationTab,
                {
                  pendingRequests: pendingElicitationRequests,
                  onResolve: handleResolveElicitation
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                RootsTab,
                {
                  roots,
                  setRoots,
                  onRootsChange: handleRootsChange
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(AuthDebuggerWrapper, {}),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                MetadataTab,
                {
                  metadata: metadata2,
                  onMetadataChange: handleMetadataChange
                }
              )
            ] }) })
          ]
        }
      ) : isAuthDebuggerVisible ? /* @__PURE__ */ jsxRuntimeExports.jsx(
        Tabs,
        {
          defaultValue: "auth",
          className: "w-full p-4",
          onValueChange: (value) => window.location.hash = value,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(AuthDebuggerWrapper, {})
        }
      ) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center justify-center h-full gap-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-lg text-gray-500 dark:text-gray-400", children: "Connect to an MCP server to start inspecting" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-muted-foreground", children: "Need to configure authentication?" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: () => setIsAuthDebuggerVisible(true),
              children: "Open Auth Settings"
            }
          )
        ] })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: "relative border-t border-border",
          style: {
            height: `${historyPaneHeight}px`
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: "absolute w-full h-4 -top-2 cursor-row-resize flex items-center justify-center hover:bg-accent/50 dark:hover:bg-input/40",
                onMouseDown: handleDragStart,
                children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-1 rounded-full bg-border" })
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-full overflow-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              HistoryAndNotifications,
              {
                requestHistory,
                serverNotifications: notifications,
                onClearHistory: clearRequestHistory,
                onClearNotifications: handleClearNotifications
              }
            ) })
          ]
        }
      )
    ] })
  ] });
};
clientExports.createRoot(document.getElementById("root")).render(
  /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.StrictMode, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(TooltipProvider, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(App, {}) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Toaster, {})
  ] })
);
export {
  InspectorOAuthClientProvider as I,
  SESSION_KEYS as S,
  auth as a,
  generateOAuthErrorDescription as g,
  jsxRuntimeExports as j,
  parseOAuthCallbackParams as p,
  reactExports as r,
  useToast as u
};
