var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// ../../node_modules/.pnpm/preact@10.11.3/node_modules/preact/dist/preact.module.js
var preact_module_exports = {};
__export(preact_module_exports, {
  Component: () => d,
  Fragment: () => p,
  cloneElement: () => q,
  createContext: () => B,
  createElement: () => h,
  createRef: () => y,
  h: () => h,
  hydrate: () => S,
  isValidElement: () => i,
  options: () => l,
  render: () => P,
  toChildArray: () => x
});
function s(n3, l4) {
  for (var u4 in l4)
    n3[u4] = l4[u4];
  return n3;
}
function a(n3) {
  var l4 = n3.parentNode;
  l4 && l4.removeChild(n3);
}
function h(l4, u4, i4) {
  var t4, o4, r4, f4 = {};
  for (r4 in u4)
    "key" == r4 ? t4 = u4[r4] : "ref" == r4 ? o4 = u4[r4] : f4[r4] = u4[r4];
  if (arguments.length > 2 && (f4.children = arguments.length > 3 ? n.call(arguments, 2) : i4), "function" == typeof l4 && null != l4.defaultProps)
    for (r4 in l4.defaultProps)
      void 0 === f4[r4] && (f4[r4] = l4.defaultProps[r4]);
  return v(l4, f4, t4, o4, null);
}
function v(n3, i4, t4, o4, r4) {
  var f4 = { type: n3, props: i4, key: t4, ref: o4, __k: null, __: null, __b: 0, __e: null, __d: void 0, __c: null, __h: null, constructor: void 0, __v: null == r4 ? ++u : r4 };
  return null == r4 && null != l.vnode && l.vnode(f4), f4;
}
function y() {
  return { current: null };
}
function p(n3) {
  return n3.children;
}
function d(n3, l4) {
  this.props = n3, this.context = l4;
}
function _(n3, l4) {
  if (null == l4)
    return n3.__ ? _(n3.__, n3.__.__k.indexOf(n3) + 1) : null;
  for (var u4; l4 < n3.__k.length; l4++)
    if (null != (u4 = n3.__k[l4]) && null != u4.__e)
      return u4.__e;
  return "function" == typeof n3.type ? _(n3) : null;
}
function k(n3) {
  var l4, u4;
  if (null != (n3 = n3.__) && null != n3.__c) {
    for (n3.__e = n3.__c.base = null, l4 = 0; l4 < n3.__k.length; l4++)
      if (null != (u4 = n3.__k[l4]) && null != u4.__e) {
        n3.__e = n3.__c.base = u4.__e;
        break;
      }
    return k(n3);
  }
}
function b(n3) {
  (!n3.__d && (n3.__d = true) && t.push(n3) && !g.__r++ || o !== l.debounceRendering) && ((o = l.debounceRendering) || setTimeout)(g);
}
function g() {
  for (var n3; g.__r = t.length; )
    n3 = t.sort(function(n4, l4) {
      return n4.__v.__b - l4.__v.__b;
    }), t = [], n3.some(function(n4) {
      var l4, u4, i4, t4, o4, r4;
      n4.__d && (o4 = (t4 = (l4 = n4).__v).__e, (r4 = l4.__P) && (u4 = [], (i4 = s({}, t4)).__v = t4.__v + 1, j(r4, t4, i4, l4.__n, void 0 !== r4.ownerSVGElement, null != t4.__h ? [o4] : null, u4, null == o4 ? _(t4) : o4, t4.__h), z(u4, t4), t4.__e != o4 && k(t4)));
    });
}
function w(n3, l4, u4, i4, t4, o4, r4, c4, s4, a4) {
  var h4, y4, d4, k4, b4, g4, w4, x3 = i4 && i4.__k || e, C3 = x3.length;
  for (u4.__k = [], h4 = 0; h4 < l4.length; h4++)
    if (null != (k4 = u4.__k[h4] = null == (k4 = l4[h4]) || "boolean" == typeof k4 ? null : "string" == typeof k4 || "number" == typeof k4 || "bigint" == typeof k4 ? v(null, k4, null, null, k4) : Array.isArray(k4) ? v(p, { children: k4 }, null, null, null) : k4.__b > 0 ? v(k4.type, k4.props, k4.key, k4.ref ? k4.ref : null, k4.__v) : k4)) {
      if (k4.__ = u4, k4.__b = u4.__b + 1, null === (d4 = x3[h4]) || d4 && k4.key == d4.key && k4.type === d4.type)
        x3[h4] = void 0;
      else
        for (y4 = 0; y4 < C3; y4++) {
          if ((d4 = x3[y4]) && k4.key == d4.key && k4.type === d4.type) {
            x3[y4] = void 0;
            break;
          }
          d4 = null;
        }
      j(n3, k4, d4 = d4 || f, t4, o4, r4, c4, s4, a4), b4 = k4.__e, (y4 = k4.ref) && d4.ref != y4 && (w4 || (w4 = []), d4.ref && w4.push(d4.ref, null, k4), w4.push(y4, k4.__c || b4, k4)), null != b4 ? (null == g4 && (g4 = b4), "function" == typeof k4.type && k4.__k === d4.__k ? k4.__d = s4 = m(k4, s4, n3) : s4 = A(n3, k4, d4, x3, b4, s4), "function" == typeof u4.type && (u4.__d = s4)) : s4 && d4.__e == s4 && s4.parentNode != n3 && (s4 = _(d4));
    }
  for (u4.__e = g4, h4 = C3; h4--; )
    null != x3[h4] && N(x3[h4], x3[h4]);
  if (w4)
    for (h4 = 0; h4 < w4.length; h4++)
      M(w4[h4], w4[++h4], w4[++h4]);
}
function m(n3, l4, u4) {
  for (var i4, t4 = n3.__k, o4 = 0; t4 && o4 < t4.length; o4++)
    (i4 = t4[o4]) && (i4.__ = n3, l4 = "function" == typeof i4.type ? m(i4, l4, u4) : A(u4, i4, i4, t4, i4.__e, l4));
  return l4;
}
function x(n3, l4) {
  return l4 = l4 || [], null == n3 || "boolean" == typeof n3 || (Array.isArray(n3) ? n3.some(function(n4) {
    x(n4, l4);
  }) : l4.push(n3)), l4;
}
function A(n3, l4, u4, i4, t4, o4) {
  var r4, f4, e4;
  if (void 0 !== l4.__d)
    r4 = l4.__d, l4.__d = void 0;
  else if (null == u4 || t4 != o4 || null == t4.parentNode)
    n:
      if (null == o4 || o4.parentNode !== n3)
        n3.appendChild(t4), r4 = null;
      else {
        for (f4 = o4, e4 = 0; (f4 = f4.nextSibling) && e4 < i4.length; e4 += 1)
          if (f4 == t4)
            break n;
        n3.insertBefore(t4, o4), r4 = o4;
      }
  return void 0 !== r4 ? r4 : t4.nextSibling;
}
function C(n3, l4, u4, i4, t4) {
  var o4;
  for (o4 in u4)
    "children" === o4 || "key" === o4 || o4 in l4 || H(n3, o4, null, u4[o4], i4);
  for (o4 in l4)
    t4 && "function" != typeof l4[o4] || "children" === o4 || "key" === o4 || "value" === o4 || "checked" === o4 || u4[o4] === l4[o4] || H(n3, o4, l4[o4], u4[o4], i4);
}
function $(n3, l4, u4) {
  "-" === l4[0] ? n3.setProperty(l4, u4) : n3[l4] = null == u4 ? "" : "number" != typeof u4 || c.test(l4) ? u4 : u4 + "px";
}
function H(n3, l4, u4, i4, t4) {
  var o4;
  n:
    if ("style" === l4)
      if ("string" == typeof u4)
        n3.style.cssText = u4;
      else {
        if ("string" == typeof i4 && (n3.style.cssText = i4 = ""), i4)
          for (l4 in i4)
            u4 && l4 in u4 || $(n3.style, l4, "");
        if (u4)
          for (l4 in u4)
            i4 && u4[l4] === i4[l4] || $(n3.style, l4, u4[l4]);
      }
    else if ("o" === l4[0] && "n" === l4[1])
      o4 = l4 !== (l4 = l4.replace(/Capture$/, "")), l4 = l4.toLowerCase() in n3 ? l4.toLowerCase().slice(2) : l4.slice(2), n3.l || (n3.l = {}), n3.l[l4 + o4] = u4, u4 ? i4 || n3.addEventListener(l4, o4 ? T : I, o4) : n3.removeEventListener(l4, o4 ? T : I, o4);
    else if ("dangerouslySetInnerHTML" !== l4) {
      if (t4)
        l4 = l4.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s");
      else if ("href" !== l4 && "list" !== l4 && "form" !== l4 && "tabIndex" !== l4 && "download" !== l4 && l4 in n3)
        try {
          n3[l4] = null == u4 ? "" : u4;
          break n;
        } catch (n4) {
        }
      "function" == typeof u4 || (null == u4 || false === u4 && -1 == l4.indexOf("-") ? n3.removeAttribute(l4) : n3.setAttribute(l4, u4));
    }
}
function I(n3) {
  this.l[n3.type + false](l.event ? l.event(n3) : n3);
}
function T(n3) {
  this.l[n3.type + true](l.event ? l.event(n3) : n3);
}
function j(n3, u4, i4, t4, o4, r4, f4, e4, c4) {
  var a4, h4, v4, y4, _4, k4, b4, g4, m4, x3, A4, C3, $3, H3, I4, T4 = u4.type;
  if (void 0 !== u4.constructor)
    return null;
  null != i4.__h && (c4 = i4.__h, e4 = u4.__e = i4.__e, u4.__h = null, r4 = [e4]), (a4 = l.__b) && a4(u4);
  try {
    n:
      if ("function" == typeof T4) {
        if (g4 = u4.props, m4 = (a4 = T4.contextType) && t4[a4.__c], x3 = a4 ? m4 ? m4.props.value : a4.__ : t4, i4.__c ? b4 = (h4 = u4.__c = i4.__c).__ = h4.__E : ("prototype" in T4 && T4.prototype.render ? u4.__c = h4 = new T4(g4, x3) : (u4.__c = h4 = new d(g4, x3), h4.constructor = T4, h4.render = O), m4 && m4.sub(h4), h4.props = g4, h4.state || (h4.state = {}), h4.context = x3, h4.__n = t4, v4 = h4.__d = true, h4.__h = [], h4._sb = []), null == h4.__s && (h4.__s = h4.state), null != T4.getDerivedStateFromProps && (h4.__s == h4.state && (h4.__s = s({}, h4.__s)), s(h4.__s, T4.getDerivedStateFromProps(g4, h4.__s))), y4 = h4.props, _4 = h4.state, v4)
          null == T4.getDerivedStateFromProps && null != h4.componentWillMount && h4.componentWillMount(), null != h4.componentDidMount && h4.__h.push(h4.componentDidMount);
        else {
          if (null == T4.getDerivedStateFromProps && g4 !== y4 && null != h4.componentWillReceiveProps && h4.componentWillReceiveProps(g4, x3), !h4.__e && null != h4.shouldComponentUpdate && false === h4.shouldComponentUpdate(g4, h4.__s, x3) || u4.__v === i4.__v) {
            for (h4.props = g4, h4.state = h4.__s, u4.__v !== i4.__v && (h4.__d = false), h4.__v = u4, u4.__e = i4.__e, u4.__k = i4.__k, u4.__k.forEach(function(n4) {
              n4 && (n4.__ = u4);
            }), A4 = 0; A4 < h4._sb.length; A4++)
              h4.__h.push(h4._sb[A4]);
            h4._sb = [], h4.__h.length && f4.push(h4);
            break n;
          }
          null != h4.componentWillUpdate && h4.componentWillUpdate(g4, h4.__s, x3), null != h4.componentDidUpdate && h4.__h.push(function() {
            h4.componentDidUpdate(y4, _4, k4);
          });
        }
        if (h4.context = x3, h4.props = g4, h4.__v = u4, h4.__P = n3, C3 = l.__r, $3 = 0, "prototype" in T4 && T4.prototype.render) {
          for (h4.state = h4.__s, h4.__d = false, C3 && C3(u4), a4 = h4.render(h4.props, h4.state, h4.context), H3 = 0; H3 < h4._sb.length; H3++)
            h4.__h.push(h4._sb[H3]);
          h4._sb = [];
        } else
          do {
            h4.__d = false, C3 && C3(u4), a4 = h4.render(h4.props, h4.state, h4.context), h4.state = h4.__s;
          } while (h4.__d && ++$3 < 25);
        h4.state = h4.__s, null != h4.getChildContext && (t4 = s(s({}, t4), h4.getChildContext())), v4 || null == h4.getSnapshotBeforeUpdate || (k4 = h4.getSnapshotBeforeUpdate(y4, _4)), I4 = null != a4 && a4.type === p && null == a4.key ? a4.props.children : a4, w(n3, Array.isArray(I4) ? I4 : [I4], u4, i4, t4, o4, r4, f4, e4, c4), h4.base = u4.__e, u4.__h = null, h4.__h.length && f4.push(h4), b4 && (h4.__E = h4.__ = null), h4.__e = false;
      } else
        null == r4 && u4.__v === i4.__v ? (u4.__k = i4.__k, u4.__e = i4.__e) : u4.__e = L(i4.__e, u4, i4, t4, o4, r4, f4, c4);
    (a4 = l.diffed) && a4(u4);
  } catch (n4) {
    u4.__v = null, (c4 || null != r4) && (u4.__e = e4, u4.__h = !!c4, r4[r4.indexOf(e4)] = null), l.__e(n4, u4, i4);
  }
}
function z(n3, u4) {
  l.__c && l.__c(u4, n3), n3.some(function(u5) {
    try {
      n3 = u5.__h, u5.__h = [], n3.some(function(n4) {
        n4.call(u5);
      });
    } catch (n4) {
      l.__e(n4, u5.__v);
    }
  });
}
function L(l4, u4, i4, t4, o4, r4, e4, c4) {
  var s4, h4, v4, y4 = i4.props, p5 = u4.props, d4 = u4.type, k4 = 0;
  if ("svg" === d4 && (o4 = true), null != r4) {
    for (; k4 < r4.length; k4++)
      if ((s4 = r4[k4]) && "setAttribute" in s4 == !!d4 && (d4 ? s4.localName === d4 : 3 === s4.nodeType)) {
        l4 = s4, r4[k4] = null;
        break;
      }
  }
  if (null == l4) {
    if (null === d4)
      return document.createTextNode(p5);
    l4 = o4 ? document.createElementNS("http://www.w3.org/2000/svg", d4) : document.createElement(d4, p5.is && p5), r4 = null, c4 = false;
  }
  if (null === d4)
    y4 === p5 || c4 && l4.data === p5 || (l4.data = p5);
  else {
    if (r4 = r4 && n.call(l4.childNodes), h4 = (y4 = i4.props || f).dangerouslySetInnerHTML, v4 = p5.dangerouslySetInnerHTML, !c4) {
      if (null != r4)
        for (y4 = {}, k4 = 0; k4 < l4.attributes.length; k4++)
          y4[l4.attributes[k4].name] = l4.attributes[k4].value;
      (v4 || h4) && (v4 && (h4 && v4.__html == h4.__html || v4.__html === l4.innerHTML) || (l4.innerHTML = v4 && v4.__html || ""));
    }
    if (C(l4, p5, y4, o4, c4), v4)
      u4.__k = [];
    else if (k4 = u4.props.children, w(l4, Array.isArray(k4) ? k4 : [k4], u4, i4, t4, o4 && "foreignObject" !== d4, r4, e4, r4 ? r4[0] : i4.__k && _(i4, 0), c4), null != r4)
      for (k4 = r4.length; k4--; )
        null != r4[k4] && a(r4[k4]);
    c4 || ("value" in p5 && void 0 !== (k4 = p5.value) && (k4 !== l4.value || "progress" === d4 && !k4 || "option" === d4 && k4 !== y4.value) && H(l4, "value", k4, y4.value, false), "checked" in p5 && void 0 !== (k4 = p5.checked) && k4 !== l4.checked && H(l4, "checked", k4, y4.checked, false));
  }
  return l4;
}
function M(n3, u4, i4) {
  try {
    "function" == typeof n3 ? n3(u4) : n3.current = u4;
  } catch (n4) {
    l.__e(n4, i4);
  }
}
function N(n3, u4, i4) {
  var t4, o4;
  if (l.unmount && l.unmount(n3), (t4 = n3.ref) && (t4.current && t4.current !== n3.__e || M(t4, null, u4)), null != (t4 = n3.__c)) {
    if (t4.componentWillUnmount)
      try {
        t4.componentWillUnmount();
      } catch (n4) {
        l.__e(n4, u4);
      }
    t4.base = t4.__P = null, n3.__c = void 0;
  }
  if (t4 = n3.__k)
    for (o4 = 0; o4 < t4.length; o4++)
      t4[o4] && N(t4[o4], u4, i4 || "function" != typeof n3.type);
  i4 || null == n3.__e || a(n3.__e), n3.__ = n3.__e = n3.__d = void 0;
}
function O(n3, l4, u4) {
  return this.constructor(n3, u4);
}
function P(u4, i4, t4) {
  var o4, r4, e4;
  l.__ && l.__(u4, i4), r4 = (o4 = "function" == typeof t4) ? null : t4 && t4.__k || i4.__k, e4 = [], j(i4, u4 = (!o4 && t4 || i4).__k = h(p, null, [u4]), r4 || f, f, void 0 !== i4.ownerSVGElement, !o4 && t4 ? [t4] : r4 ? null : i4.firstChild ? n.call(i4.childNodes) : null, e4, !o4 && t4 ? t4 : r4 ? r4.__e : i4.firstChild, o4), z(e4, u4);
}
function S(n3, l4) {
  P(n3, l4, S);
}
function q(l4, u4, i4) {
  var t4, o4, r4, f4 = s({}, l4.props);
  for (r4 in u4)
    "key" == r4 ? t4 = u4[r4] : "ref" == r4 ? o4 = u4[r4] : f4[r4] = u4[r4];
  return arguments.length > 2 && (f4.children = arguments.length > 3 ? n.call(arguments, 2) : i4), v(l4.type, f4, t4 || l4.key, o4 || l4.ref, null);
}
function B(n3, l4) {
  var u4 = { __c: l4 = "__cC" + r++, __: n3, Consumer: function(n4, l5) {
    return n4.children(l5);
  }, Provider: function(n4) {
    var u5, i4;
    return this.getChildContext || (u5 = [], (i4 = {})[l4] = this, this.getChildContext = function() {
      return i4;
    }, this.shouldComponentUpdate = function(n5) {
      this.props.value !== n5.value && u5.some(b);
    }, this.sub = function(n5) {
      u5.push(n5);
      var l5 = n5.componentWillUnmount;
      n5.componentWillUnmount = function() {
        u5.splice(u5.indexOf(n5), 1), l5 && l5.call(n5);
      };
    }), n4.children;
  } };
  return u4.Provider.__ = u4.Consumer.contextType = u4;
}
var n, l, u, i, t, o, r, f, e, c;
var init_preact_module = __esm({
  "../../node_modules/.pnpm/preact@10.11.3/node_modules/preact/dist/preact.module.js"() {
    f = {};
    e = [];
    c = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;
    n = e.slice, l = { __e: function(n3, l4, u4, i4) {
      for (var t4, o4, r4; l4 = l4.__; )
        if ((t4 = l4.__c) && !t4.__)
          try {
            if ((o4 = t4.constructor) && null != o4.getDerivedStateFromError && (t4.setState(o4.getDerivedStateFromError(n3)), r4 = t4.__d), null != t4.componentDidCatch && (t4.componentDidCatch(n3, i4 || {}), r4 = t4.__d), r4)
              return t4.__E = t4;
          } catch (l5) {
            n3 = l5;
          }
      throw n3;
    } }, u = 0, i = function(n3) {
      return null != n3 && void 0 === n3.constructor;
    }, d.prototype.setState = function(n3, l4) {
      var u4;
      u4 = null != this.__s && this.__s !== this.state ? this.__s : this.__s = s({}, this.state), "function" == typeof n3 && (n3 = n3(s({}, u4), this.props)), n3 && s(u4, n3), null != n3 && this.__v && (l4 && this._sb.push(l4), b(this));
    }, d.prototype.forceUpdate = function(n3) {
      this.__v && (this.__e = true, n3 && this.__h.push(n3), b(this));
    }, d.prototype.render = p, t = [], g.__r = 0, r = 0;
  }
});

// ../../node_modules/.pnpm/big-integer@1.6.52/node_modules/big-integer/BigInteger.js
var require_BigInteger = __commonJS({
  "../../node_modules/.pnpm/big-integer@1.6.52/node_modules/big-integer/BigInteger.js"(exports, module) {
    var bigInt = function(undefined2) {
      "use strict";
      var BASE = 1e7, LOG_BASE = 7, MAX_INT = 9007199254740992, MAX_INT_ARR = smallToArray(MAX_INT), DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
      var supportsNativeBigInt = typeof BigInt === "function";
      function Integer(v4, radix, alphabet, caseSensitive) {
        if (typeof v4 === "undefined")
          return Integer[0];
        if (typeof radix !== "undefined")
          return +radix === 10 && !alphabet ? parseValue(v4) : parseBase(v4, radix, alphabet, caseSensitive);
        return parseValue(v4);
      }
      function BigInteger(value, sign2) {
        this.value = value;
        this.sign = sign2;
        this.isSmall = false;
      }
      BigInteger.prototype = Object.create(Integer.prototype);
      function SmallInteger(value) {
        this.value = value;
        this.sign = value < 0;
        this.isSmall = true;
      }
      SmallInteger.prototype = Object.create(Integer.prototype);
      function NativeBigInt(value) {
        this.value = value;
      }
      NativeBigInt.prototype = Object.create(Integer.prototype);
      function isPrecise(n3) {
        return -MAX_INT < n3 && n3 < MAX_INT;
      }
      function smallToArray(n3) {
        if (n3 < 1e7)
          return [n3];
        if (n3 < 1e14)
          return [n3 % 1e7, Math.floor(n3 / 1e7)];
        return [n3 % 1e7, Math.floor(n3 / 1e7) % 1e7, Math.floor(n3 / 1e14)];
      }
      function arrayToSmall(arr) {
        trim(arr);
        var length = arr.length;
        if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
          switch (length) {
            case 0:
              return 0;
            case 1:
              return arr[0];
            case 2:
              return arr[0] + arr[1] * BASE;
            default:
              return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
          }
        }
        return arr;
      }
      function trim(v4) {
        var i5 = v4.length;
        while (v4[--i5] === 0)
          ;
        v4.length = i5 + 1;
      }
      function createArray(length) {
        var x3 = new Array(length);
        var i5 = -1;
        while (++i5 < length) {
          x3[i5] = 0;
        }
        return x3;
      }
      function truncate(n3) {
        if (n3 > 0)
          return Math.floor(n3);
        return Math.ceil(n3);
      }
      function add2(a4, b4) {
        var l_a = a4.length, l_b = b4.length, r4 = new Array(l_a), carry = 0, base3 = BASE, sum, i5;
        for (i5 = 0; i5 < l_b; i5++) {
          sum = a4[i5] + b4[i5] + carry;
          carry = sum >= base3 ? 1 : 0;
          r4[i5] = sum - carry * base3;
        }
        while (i5 < l_a) {
          sum = a4[i5] + carry;
          carry = sum === base3 ? 1 : 0;
          r4[i5++] = sum - carry * base3;
        }
        if (carry > 0)
          r4.push(carry);
        return r4;
      }
      function addAny(a4, b4) {
        if (a4.length >= b4.length)
          return add2(a4, b4);
        return add2(b4, a4);
      }
      function addSmall(a4, carry) {
        var l4 = a4.length, r4 = new Array(l4), base3 = BASE, sum, i5;
        for (i5 = 0; i5 < l4; i5++) {
          sum = a4[i5] - base3 + carry;
          carry = Math.floor(sum / base3);
          r4[i5] = sum - carry * base3;
          carry += 1;
        }
        while (carry > 0) {
          r4[i5++] = carry % base3;
          carry = Math.floor(carry / base3);
        }
        return r4;
      }
      BigInteger.prototype.add = function(v4) {
        var n3 = parseValue(v4);
        if (this.sign !== n3.sign) {
          return this.subtract(n3.negate());
        }
        var a4 = this.value, b4 = n3.value;
        if (n3.isSmall) {
          return new BigInteger(addSmall(a4, Math.abs(b4)), this.sign);
        }
        return new BigInteger(addAny(a4, b4), this.sign);
      };
      BigInteger.prototype.plus = BigInteger.prototype.add;
      SmallInteger.prototype.add = function(v4) {
        var n3 = parseValue(v4);
        var a4 = this.value;
        if (a4 < 0 !== n3.sign) {
          return this.subtract(n3.negate());
        }
        var b4 = n3.value;
        if (n3.isSmall) {
          if (isPrecise(a4 + b4))
            return new SmallInteger(a4 + b4);
          b4 = smallToArray(Math.abs(b4));
        }
        return new BigInteger(addSmall(b4, Math.abs(a4)), a4 < 0);
      };
      SmallInteger.prototype.plus = SmallInteger.prototype.add;
      NativeBigInt.prototype.add = function(v4) {
        return new NativeBigInt(this.value + parseValue(v4).value);
      };
      NativeBigInt.prototype.plus = NativeBigInt.prototype.add;
      function subtract(a4, b4) {
        var a_l = a4.length, b_l = b4.length, r4 = new Array(a_l), borrow = 0, base3 = BASE, i5, difference;
        for (i5 = 0; i5 < b_l; i5++) {
          difference = a4[i5] - borrow - b4[i5];
          if (difference < 0) {
            difference += base3;
            borrow = 1;
          } else
            borrow = 0;
          r4[i5] = difference;
        }
        for (i5 = b_l; i5 < a_l; i5++) {
          difference = a4[i5] - borrow;
          if (difference < 0)
            difference += base3;
          else {
            r4[i5++] = difference;
            break;
          }
          r4[i5] = difference;
        }
        for (; i5 < a_l; i5++) {
          r4[i5] = a4[i5];
        }
        trim(r4);
        return r4;
      }
      function subtractAny(a4, b4, sign2) {
        var value;
        if (compareAbs(a4, b4) >= 0) {
          value = subtract(a4, b4);
        } else {
          value = subtract(b4, a4);
          sign2 = !sign2;
        }
        value = arrayToSmall(value);
        if (typeof value === "number") {
          if (sign2)
            value = -value;
          return new SmallInteger(value);
        }
        return new BigInteger(value, sign2);
      }
      function subtractSmall(a4, b4, sign2) {
        var l4 = a4.length, r4 = new Array(l4), carry = -b4, base3 = BASE, i5, difference;
        for (i5 = 0; i5 < l4; i5++) {
          difference = a4[i5] + carry;
          carry = Math.floor(difference / base3);
          difference %= base3;
          r4[i5] = difference < 0 ? difference + base3 : difference;
        }
        r4 = arrayToSmall(r4);
        if (typeof r4 === "number") {
          if (sign2)
            r4 = -r4;
          return new SmallInteger(r4);
        }
        return new BigInteger(r4, sign2);
      }
      BigInteger.prototype.subtract = function(v4) {
        var n3 = parseValue(v4);
        if (this.sign !== n3.sign) {
          return this.add(n3.negate());
        }
        var a4 = this.value, b4 = n3.value;
        if (n3.isSmall)
          return subtractSmall(a4, Math.abs(b4), this.sign);
        return subtractAny(a4, b4, this.sign);
      };
      BigInteger.prototype.minus = BigInteger.prototype.subtract;
      SmallInteger.prototype.subtract = function(v4) {
        var n3 = parseValue(v4);
        var a4 = this.value;
        if (a4 < 0 !== n3.sign) {
          return this.add(n3.negate());
        }
        var b4 = n3.value;
        if (n3.isSmall) {
          return new SmallInteger(a4 - b4);
        }
        return subtractSmall(b4, Math.abs(a4), a4 >= 0);
      };
      SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
      NativeBigInt.prototype.subtract = function(v4) {
        return new NativeBigInt(this.value - parseValue(v4).value);
      };
      NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;
      BigInteger.prototype.negate = function() {
        return new BigInteger(this.value, !this.sign);
      };
      SmallInteger.prototype.negate = function() {
        var sign2 = this.sign;
        var small = new SmallInteger(-this.value);
        small.sign = !sign2;
        return small;
      };
      NativeBigInt.prototype.negate = function() {
        return new NativeBigInt(-this.value);
      };
      BigInteger.prototype.abs = function() {
        return new BigInteger(this.value, false);
      };
      SmallInteger.prototype.abs = function() {
        return new SmallInteger(Math.abs(this.value));
      };
      NativeBigInt.prototype.abs = function() {
        return new NativeBigInt(this.value >= 0 ? this.value : -this.value);
      };
      function multiplyLong(a4, b4) {
        var a_l = a4.length, b_l = b4.length, l4 = a_l + b_l, r4 = createArray(l4), base3 = BASE, product, carry, i5, a_i, b_j;
        for (i5 = 0; i5 < a_l; ++i5) {
          a_i = a4[i5];
          for (var j4 = 0; j4 < b_l; ++j4) {
            b_j = b4[j4];
            product = a_i * b_j + r4[i5 + j4];
            carry = Math.floor(product / base3);
            r4[i5 + j4] = product - carry * base3;
            r4[i5 + j4 + 1] += carry;
          }
        }
        trim(r4);
        return r4;
      }
      function multiplySmall(a4, b4) {
        var l4 = a4.length, r4 = new Array(l4), base3 = BASE, carry = 0, product, i5;
        for (i5 = 0; i5 < l4; i5++) {
          product = a4[i5] * b4 + carry;
          carry = Math.floor(product / base3);
          r4[i5] = product - carry * base3;
        }
        while (carry > 0) {
          r4[i5++] = carry % base3;
          carry = Math.floor(carry / base3);
        }
        return r4;
      }
      function shiftLeft(x3, n3) {
        var r4 = [];
        while (n3-- > 0)
          r4.push(0);
        return r4.concat(x3);
      }
      function multiplyKaratsuba(x3, y4) {
        var n3 = Math.max(x3.length, y4.length);
        if (n3 <= 30)
          return multiplyLong(x3, y4);
        n3 = Math.ceil(n3 / 2);
        var b4 = x3.slice(n3), a4 = x3.slice(0, n3), d4 = y4.slice(n3), c4 = y4.slice(0, n3);
        var ac = multiplyKaratsuba(a4, c4), bd = multiplyKaratsuba(b4, d4), abcd = multiplyKaratsuba(addAny(a4, b4), addAny(c4, d4));
        var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n3)), shiftLeft(bd, 2 * n3));
        trim(product);
        return product;
      }
      function useKaratsuba(l1, l22) {
        return -0.012 * l1 - 0.012 * l22 + 15e-6 * l1 * l22 > 0;
      }
      BigInteger.prototype.multiply = function(v4) {
        var n3 = parseValue(v4), a4 = this.value, b4 = n3.value, sign2 = this.sign !== n3.sign, abs;
        if (n3.isSmall) {
          if (b4 === 0)
            return Integer[0];
          if (b4 === 1)
            return this;
          if (b4 === -1)
            return this.negate();
          abs = Math.abs(b4);
          if (abs < BASE) {
            return new BigInteger(multiplySmall(a4, abs), sign2);
          }
          b4 = smallToArray(abs);
        }
        if (useKaratsuba(a4.length, b4.length))
          return new BigInteger(multiplyKaratsuba(a4, b4), sign2);
        return new BigInteger(multiplyLong(a4, b4), sign2);
      };
      BigInteger.prototype.times = BigInteger.prototype.multiply;
      function multiplySmallAndArray(a4, b4, sign2) {
        if (a4 < BASE) {
          return new BigInteger(multiplySmall(b4, a4), sign2);
        }
        return new BigInteger(multiplyLong(b4, smallToArray(a4)), sign2);
      }
      SmallInteger.prototype._multiplyBySmall = function(a4) {
        if (isPrecise(a4.value * this.value)) {
          return new SmallInteger(a4.value * this.value);
        }
        return multiplySmallAndArray(Math.abs(a4.value), smallToArray(Math.abs(this.value)), this.sign !== a4.sign);
      };
      BigInteger.prototype._multiplyBySmall = function(a4) {
        if (a4.value === 0)
          return Integer[0];
        if (a4.value === 1)
          return this;
        if (a4.value === -1)
          return this.negate();
        return multiplySmallAndArray(Math.abs(a4.value), this.value, this.sign !== a4.sign);
      };
      SmallInteger.prototype.multiply = function(v4) {
        return parseValue(v4)._multiplyBySmall(this);
      };
      SmallInteger.prototype.times = SmallInteger.prototype.multiply;
      NativeBigInt.prototype.multiply = function(v4) {
        return new NativeBigInt(this.value * parseValue(v4).value);
      };
      NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;
      function square(a4) {
        var l4 = a4.length, r4 = createArray(l4 + l4), base3 = BASE, product, carry, i5, a_i, a_j;
        for (i5 = 0; i5 < l4; i5++) {
          a_i = a4[i5];
          carry = 0 - a_i * a_i;
          for (var j4 = i5; j4 < l4; j4++) {
            a_j = a4[j4];
            product = 2 * (a_i * a_j) + r4[i5 + j4] + carry;
            carry = Math.floor(product / base3);
            r4[i5 + j4] = product - carry * base3;
          }
          r4[i5 + l4] = carry;
        }
        trim(r4);
        return r4;
      }
      BigInteger.prototype.square = function() {
        return new BigInteger(square(this.value), false);
      };
      SmallInteger.prototype.square = function() {
        var value = this.value * this.value;
        if (isPrecise(value))
          return new SmallInteger(value);
        return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
      };
      NativeBigInt.prototype.square = function(v4) {
        return new NativeBigInt(this.value * this.value);
      };
      function divMod1(a4, b4) {
        var a_l = a4.length, b_l = b4.length, base3 = BASE, result = createArray(b4.length), divisorMostSignificantDigit = b4[b_l - 1], lambda = Math.ceil(base3 / (2 * divisorMostSignificantDigit)), remainder = multiplySmall(a4, lambda), divisor = multiplySmall(b4, lambda), quotientDigit, shift, carry, borrow, i5, l4, q4;
        if (remainder.length <= a_l)
          remainder.push(0);
        divisor.push(0);
        divisorMostSignificantDigit = divisor[b_l - 1];
        for (shift = a_l - b_l; shift >= 0; shift--) {
          quotientDigit = base3 - 1;
          if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
            quotientDigit = Math.floor((remainder[shift + b_l] * base3 + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
          }
          carry = 0;
          borrow = 0;
          l4 = divisor.length;
          for (i5 = 0; i5 < l4; i5++) {
            carry += quotientDigit * divisor[i5];
            q4 = Math.floor(carry / base3);
            borrow += remainder[shift + i5] - (carry - q4 * base3);
            carry = q4;
            if (borrow < 0) {
              remainder[shift + i5] = borrow + base3;
              borrow = -1;
            } else {
              remainder[shift + i5] = borrow;
              borrow = 0;
            }
          }
          while (borrow !== 0) {
            quotientDigit -= 1;
            carry = 0;
            for (i5 = 0; i5 < l4; i5++) {
              carry += remainder[shift + i5] - base3 + divisor[i5];
              if (carry < 0) {
                remainder[shift + i5] = carry + base3;
                carry = 0;
              } else {
                remainder[shift + i5] = carry;
                carry = 1;
              }
            }
            borrow += carry;
          }
          result[shift] = quotientDigit;
        }
        remainder = divModSmall(remainder, lambda)[0];
        return [arrayToSmall(result), arrayToSmall(remainder)];
      }
      function divMod2(a4, b4) {
        var a_l = a4.length, b_l = b4.length, result = [], part = [], base3 = BASE, guess, xlen, highx, highy, check;
        while (a_l) {
          part.unshift(a4[--a_l]);
          trim(part);
          if (compareAbs(part, b4) < 0) {
            result.push(0);
            continue;
          }
          xlen = part.length;
          highx = part[xlen - 1] * base3 + part[xlen - 2];
          highy = b4[b_l - 1] * base3 + b4[b_l - 2];
          if (xlen > b_l) {
            highx = (highx + 1) * base3;
          }
          guess = Math.ceil(highx / highy);
          do {
            check = multiplySmall(b4, guess);
            if (compareAbs(check, part) <= 0)
              break;
            guess--;
          } while (guess);
          result.push(guess);
          part = subtract(part, check);
        }
        result.reverse();
        return [arrayToSmall(result), arrayToSmall(part)];
      }
      function divModSmall(value, lambda) {
        var length = value.length, quotient = createArray(length), base3 = BASE, i5, q4, remainder, divisor;
        remainder = 0;
        for (i5 = length - 1; i5 >= 0; --i5) {
          divisor = remainder * base3 + value[i5];
          q4 = truncate(divisor / lambda);
          remainder = divisor - q4 * lambda;
          quotient[i5] = q4 | 0;
        }
        return [quotient, remainder | 0];
      }
      function divModAny(self2, v4) {
        var value, n3 = parseValue(v4);
        if (supportsNativeBigInt) {
          return [new NativeBigInt(self2.value / n3.value), new NativeBigInt(self2.value % n3.value)];
        }
        var a4 = self2.value, b4 = n3.value;
        var quotient;
        if (b4 === 0)
          throw new Error("Cannot divide by zero");
        if (self2.isSmall) {
          if (n3.isSmall) {
            return [new SmallInteger(truncate(a4 / b4)), new SmallInteger(a4 % b4)];
          }
          return [Integer[0], self2];
        }
        if (n3.isSmall) {
          if (b4 === 1)
            return [self2, Integer[0]];
          if (b4 == -1)
            return [self2.negate(), Integer[0]];
          var abs = Math.abs(b4);
          if (abs < BASE) {
            value = divModSmall(a4, abs);
            quotient = arrayToSmall(value[0]);
            var remainder = value[1];
            if (self2.sign)
              remainder = -remainder;
            if (typeof quotient === "number") {
              if (self2.sign !== n3.sign)
                quotient = -quotient;
              return [new SmallInteger(quotient), new SmallInteger(remainder)];
            }
            return [new BigInteger(quotient, self2.sign !== n3.sign), new SmallInteger(remainder)];
          }
          b4 = smallToArray(abs);
        }
        var comparison = compareAbs(a4, b4);
        if (comparison === -1)
          return [Integer[0], self2];
        if (comparison === 0)
          return [Integer[self2.sign === n3.sign ? 1 : -1], Integer[0]];
        if (a4.length + b4.length <= 200)
          value = divMod1(a4, b4);
        else
          value = divMod2(a4, b4);
        quotient = value[0];
        var qSign = self2.sign !== n3.sign, mod = value[1], mSign = self2.sign;
        if (typeof quotient === "number") {
          if (qSign)
            quotient = -quotient;
          quotient = new SmallInteger(quotient);
        } else
          quotient = new BigInteger(quotient, qSign);
        if (typeof mod === "number") {
          if (mSign)
            mod = -mod;
          mod = new SmallInteger(mod);
        } else
          mod = new BigInteger(mod, mSign);
        return [quotient, mod];
      }
      BigInteger.prototype.divmod = function(v4) {
        var result = divModAny(this, v4);
        return {
          quotient: result[0],
          remainder: result[1]
        };
      };
      NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
      BigInteger.prototype.divide = function(v4) {
        return divModAny(this, v4)[0];
      };
      NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function(v4) {
        return new NativeBigInt(this.value / parseValue(v4).value);
      };
      SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
      BigInteger.prototype.mod = function(v4) {
        return divModAny(this, v4)[1];
      };
      NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function(v4) {
        return new NativeBigInt(this.value % parseValue(v4).value);
      };
      SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
      BigInteger.prototype.pow = function(v4) {
        var n3 = parseValue(v4), a4 = this.value, b4 = n3.value, value, x3, y4;
        if (b4 === 0)
          return Integer[1];
        if (a4 === 0)
          return Integer[0];
        if (a4 === 1)
          return Integer[1];
        if (a4 === -1)
          return n3.isEven() ? Integer[1] : Integer[-1];
        if (n3.sign) {
          return Integer[0];
        }
        if (!n3.isSmall)
          throw new Error("The exponent " + n3.toString() + " is too large.");
        if (this.isSmall) {
          if (isPrecise(value = Math.pow(a4, b4)))
            return new SmallInteger(truncate(value));
        }
        x3 = this;
        y4 = Integer[1];
        while (true) {
          if (b4 & true) {
            y4 = y4.times(x3);
            --b4;
          }
          if (b4 === 0)
            break;
          b4 /= 2;
          x3 = x3.square();
        }
        return y4;
      };
      SmallInteger.prototype.pow = BigInteger.prototype.pow;
      NativeBigInt.prototype.pow = function(v4) {
        var n3 = parseValue(v4);
        var a4 = this.value, b4 = n3.value;
        var _0 = BigInt(0), _1 = BigInt(1), _22 = BigInt(2);
        if (b4 === _0)
          return Integer[1];
        if (a4 === _0)
          return Integer[0];
        if (a4 === _1)
          return Integer[1];
        if (a4 === BigInt(-1))
          return n3.isEven() ? Integer[1] : Integer[-1];
        if (n3.isNegative())
          return new NativeBigInt(_0);
        var x3 = this;
        var y4 = Integer[1];
        while (true) {
          if ((b4 & _1) === _1) {
            y4 = y4.times(x3);
            --b4;
          }
          if (b4 === _0)
            break;
          b4 /= _22;
          x3 = x3.square();
        }
        return y4;
      };
      BigInteger.prototype.modPow = function(exp, mod) {
        exp = parseValue(exp);
        mod = parseValue(mod);
        if (mod.isZero())
          throw new Error("Cannot take modPow with modulus 0");
        var r4 = Integer[1], base3 = this.mod(mod);
        if (exp.isNegative()) {
          exp = exp.multiply(Integer[-1]);
          base3 = base3.modInv(mod);
        }
        while (exp.isPositive()) {
          if (base3.isZero())
            return Integer[0];
          if (exp.isOdd())
            r4 = r4.multiply(base3).mod(mod);
          exp = exp.divide(2);
          base3 = base3.square().mod(mod);
        }
        return r4;
      };
      NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
      function compareAbs(a4, b4) {
        if (a4.length !== b4.length) {
          return a4.length > b4.length ? 1 : -1;
        }
        for (var i5 = a4.length - 1; i5 >= 0; i5--) {
          if (a4[i5] !== b4[i5])
            return a4[i5] > b4[i5] ? 1 : -1;
        }
        return 0;
      }
      BigInteger.prototype.compareAbs = function(v4) {
        var n3 = parseValue(v4), a4 = this.value, b4 = n3.value;
        if (n3.isSmall)
          return 1;
        return compareAbs(a4, b4);
      };
      SmallInteger.prototype.compareAbs = function(v4) {
        var n3 = parseValue(v4), a4 = Math.abs(this.value), b4 = n3.value;
        if (n3.isSmall) {
          b4 = Math.abs(b4);
          return a4 === b4 ? 0 : a4 > b4 ? 1 : -1;
        }
        return -1;
      };
      NativeBigInt.prototype.compareAbs = function(v4) {
        var a4 = this.value;
        var b4 = parseValue(v4).value;
        a4 = a4 >= 0 ? a4 : -a4;
        b4 = b4 >= 0 ? b4 : -b4;
        return a4 === b4 ? 0 : a4 > b4 ? 1 : -1;
      };
      BigInteger.prototype.compare = function(v4) {
        if (v4 === Infinity) {
          return -1;
        }
        if (v4 === -Infinity) {
          return 1;
        }
        var n3 = parseValue(v4), a4 = this.value, b4 = n3.value;
        if (this.sign !== n3.sign) {
          return n3.sign ? 1 : -1;
        }
        if (n3.isSmall) {
          return this.sign ? -1 : 1;
        }
        return compareAbs(a4, b4) * (this.sign ? -1 : 1);
      };
      BigInteger.prototype.compareTo = BigInteger.prototype.compare;
      SmallInteger.prototype.compare = function(v4) {
        if (v4 === Infinity) {
          return -1;
        }
        if (v4 === -Infinity) {
          return 1;
        }
        var n3 = parseValue(v4), a4 = this.value, b4 = n3.value;
        if (n3.isSmall) {
          return a4 == b4 ? 0 : a4 > b4 ? 1 : -1;
        }
        if (a4 < 0 !== n3.sign) {
          return a4 < 0 ? -1 : 1;
        }
        return a4 < 0 ? 1 : -1;
      };
      SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
      NativeBigInt.prototype.compare = function(v4) {
        if (v4 === Infinity) {
          return -1;
        }
        if (v4 === -Infinity) {
          return 1;
        }
        var a4 = this.value;
        var b4 = parseValue(v4).value;
        return a4 === b4 ? 0 : a4 > b4 ? 1 : -1;
      };
      NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;
      BigInteger.prototype.equals = function(v4) {
        return this.compare(v4) === 0;
      };
      NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
      BigInteger.prototype.notEquals = function(v4) {
        return this.compare(v4) !== 0;
      };
      NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
      BigInteger.prototype.greater = function(v4) {
        return this.compare(v4) > 0;
      };
      NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
      BigInteger.prototype.lesser = function(v4) {
        return this.compare(v4) < 0;
      };
      NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
      BigInteger.prototype.greaterOrEquals = function(v4) {
        return this.compare(v4) >= 0;
      };
      NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
      BigInteger.prototype.lesserOrEquals = function(v4) {
        return this.compare(v4) <= 0;
      };
      NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
      BigInteger.prototype.isEven = function() {
        return (this.value[0] & 1) === 0;
      };
      SmallInteger.prototype.isEven = function() {
        return (this.value & 1) === 0;
      };
      NativeBigInt.prototype.isEven = function() {
        return (this.value & BigInt(1)) === BigInt(0);
      };
      BigInteger.prototype.isOdd = function() {
        return (this.value[0] & 1) === 1;
      };
      SmallInteger.prototype.isOdd = function() {
        return (this.value & 1) === 1;
      };
      NativeBigInt.prototype.isOdd = function() {
        return (this.value & BigInt(1)) === BigInt(1);
      };
      BigInteger.prototype.isPositive = function() {
        return !this.sign;
      };
      SmallInteger.prototype.isPositive = function() {
        return this.value > 0;
      };
      NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;
      BigInteger.prototype.isNegative = function() {
        return this.sign;
      };
      SmallInteger.prototype.isNegative = function() {
        return this.value < 0;
      };
      NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;
      BigInteger.prototype.isUnit = function() {
        return false;
      };
      SmallInteger.prototype.isUnit = function() {
        return Math.abs(this.value) === 1;
      };
      NativeBigInt.prototype.isUnit = function() {
        return this.abs().value === BigInt(1);
      };
      BigInteger.prototype.isZero = function() {
        return false;
      };
      SmallInteger.prototype.isZero = function() {
        return this.value === 0;
      };
      NativeBigInt.prototype.isZero = function() {
        return this.value === BigInt(0);
      };
      BigInteger.prototype.isDivisibleBy = function(v4) {
        var n3 = parseValue(v4);
        if (n3.isZero())
          return false;
        if (n3.isUnit())
          return true;
        if (n3.compareAbs(2) === 0)
          return this.isEven();
        return this.mod(n3).isZero();
      };
      NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
      function isBasicPrime(v4) {
        var n3 = v4.abs();
        if (n3.isUnit())
          return false;
        if (n3.equals(2) || n3.equals(3) || n3.equals(5))
          return true;
        if (n3.isEven() || n3.isDivisibleBy(3) || n3.isDivisibleBy(5))
          return false;
        if (n3.lesser(49))
          return true;
      }
      function millerRabinTest(n3, a4) {
        var nPrev = n3.prev(), b4 = nPrev, r4 = 0, d4, t4, i5, x3;
        while (b4.isEven())
          b4 = b4.divide(2), r4++;
        next:
          for (i5 = 0; i5 < a4.length; i5++) {
            if (n3.lesser(a4[i5]))
              continue;
            x3 = bigInt(a4[i5]).modPow(b4, n3);
            if (x3.isUnit() || x3.equals(nPrev))
              continue;
            for (d4 = r4 - 1; d4 != 0; d4--) {
              x3 = x3.square().mod(n3);
              if (x3.isUnit())
                return false;
              if (x3.equals(nPrev))
                continue next;
            }
            return false;
          }
        return true;
      }
      BigInteger.prototype.isPrime = function(strict) {
        var isPrime2 = isBasicPrime(this);
        if (isPrime2 !== undefined2)
          return isPrime2;
        var n3 = this.abs();
        var bits2 = n3.bitLength();
        if (bits2 <= 64)
          return millerRabinTest(n3, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);
        var logN = Math.log(2) * bits2.toJSNumber();
        var t4 = Math.ceil(strict === true ? 2 * Math.pow(logN, 2) : logN);
        for (var a4 = [], i5 = 0; i5 < t4; i5++) {
          a4.push(bigInt(i5 + 2));
        }
        return millerRabinTest(n3, a4);
      };
      NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
      BigInteger.prototype.isProbablePrime = function(iterations, rng) {
        var isPrime2 = isBasicPrime(this);
        if (isPrime2 !== undefined2)
          return isPrime2;
        var n3 = this.abs();
        var t4 = iterations === undefined2 ? 5 : iterations;
        for (var a4 = [], i5 = 0; i5 < t4; i5++) {
          a4.push(bigInt.randBetween(2, n3.minus(2), rng));
        }
        return millerRabinTest(n3, a4);
      };
      NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
      BigInteger.prototype.modInv = function(n3) {
        var t4 = bigInt.zero, newT = bigInt.one, r4 = parseValue(n3), newR = this.abs(), q4, lastT, lastR;
        while (!newR.isZero()) {
          q4 = r4.divide(newR);
          lastT = t4;
          lastR = r4;
          t4 = newT;
          r4 = newR;
          newT = lastT.subtract(q4.multiply(newT));
          newR = lastR.subtract(q4.multiply(newR));
        }
        if (!r4.isUnit())
          throw new Error(this.toString() + " and " + n3.toString() + " are not co-prime");
        if (t4.compare(0) === -1) {
          t4 = t4.add(n3);
        }
        if (this.isNegative()) {
          return t4.negate();
        }
        return t4;
      };
      NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;
      BigInteger.prototype.next = function() {
        var value = this.value;
        if (this.sign) {
          return subtractSmall(value, 1, this.sign);
        }
        return new BigInteger(addSmall(value, 1), this.sign);
      };
      SmallInteger.prototype.next = function() {
        var value = this.value;
        if (value + 1 < MAX_INT)
          return new SmallInteger(value + 1);
        return new BigInteger(MAX_INT_ARR, false);
      };
      NativeBigInt.prototype.next = function() {
        return new NativeBigInt(this.value + BigInt(1));
      };
      BigInteger.prototype.prev = function() {
        var value = this.value;
        if (this.sign) {
          return new BigInteger(addSmall(value, 1), true);
        }
        return subtractSmall(value, 1, this.sign);
      };
      SmallInteger.prototype.prev = function() {
        var value = this.value;
        if (value - 1 > -MAX_INT)
          return new SmallInteger(value - 1);
        return new BigInteger(MAX_INT_ARR, true);
      };
      NativeBigInt.prototype.prev = function() {
        return new NativeBigInt(this.value - BigInt(1));
      };
      var powersOfTwo = [1];
      while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE)
        powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
      var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
      function shift_isSmall(n3) {
        return Math.abs(n3) <= BASE;
      }
      BigInteger.prototype.shiftLeft = function(v4) {
        var n3 = parseValue(v4).toJSNumber();
        if (!shift_isSmall(n3)) {
          throw new Error(String(n3) + " is too large for shifting.");
        }
        if (n3 < 0)
          return this.shiftRight(-n3);
        var result = this;
        if (result.isZero())
          return result;
        while (n3 >= powers2Length) {
          result = result.multiply(highestPower2);
          n3 -= powers2Length - 1;
        }
        return result.multiply(powersOfTwo[n3]);
      };
      NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
      BigInteger.prototype.shiftRight = function(v4) {
        var remQuo;
        var n3 = parseValue(v4).toJSNumber();
        if (!shift_isSmall(n3)) {
          throw new Error(String(n3) + " is too large for shifting.");
        }
        if (n3 < 0)
          return this.shiftLeft(-n3);
        var result = this;
        while (n3 >= powers2Length) {
          if (result.isZero() || result.isNegative() && result.isUnit())
            return result;
          remQuo = divModAny(result, highestPower2);
          result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
          n3 -= powers2Length - 1;
        }
        remQuo = divModAny(result, powersOfTwo[n3]);
        return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
      };
      NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
      function bitwise(x3, y4, fn) {
        y4 = parseValue(y4);
        var xSign = x3.isNegative(), ySign = y4.isNegative();
        var xRem = xSign ? x3.not() : x3, yRem = ySign ? y4.not() : y4;
        var xDigit = 0, yDigit = 0;
        var xDivMod = null, yDivMod = null;
        var result = [];
        while (!xRem.isZero() || !yRem.isZero()) {
          xDivMod = divModAny(xRem, highestPower2);
          xDigit = xDivMod[1].toJSNumber();
          if (xSign) {
            xDigit = highestPower2 - 1 - xDigit;
          }
          yDivMod = divModAny(yRem, highestPower2);
          yDigit = yDivMod[1].toJSNumber();
          if (ySign) {
            yDigit = highestPower2 - 1 - yDigit;
          }
          xRem = xDivMod[0];
          yRem = yDivMod[0];
          result.push(fn(xDigit, yDigit));
        }
        var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);
        for (var i5 = result.length - 1; i5 >= 0; i5 -= 1) {
          sum = sum.multiply(highestPower2).add(bigInt(result[i5]));
        }
        return sum;
      }
      BigInteger.prototype.not = function() {
        return this.negate().prev();
      };
      NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;
      BigInteger.prototype.and = function(n3) {
        return bitwise(this, n3, function(a4, b4) {
          return a4 & b4;
        });
      };
      NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;
      BigInteger.prototype.or = function(n3) {
        return bitwise(this, n3, function(a4, b4) {
          return a4 | b4;
        });
      };
      NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;
      BigInteger.prototype.xor = function(n3) {
        return bitwise(this, n3, function(a4, b4) {
          return a4 ^ b4;
        });
      };
      NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;
      var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
      function roughLOB(n3) {
        var v4 = n3.value, x3 = typeof v4 === "number" ? v4 | LOBMASK_I : typeof v4 === "bigint" ? v4 | BigInt(LOBMASK_I) : v4[0] + v4[1] * BASE | LOBMASK_BI;
        return x3 & -x3;
      }
      function integerLogarithm(value, base3) {
        if (base3.compareTo(value) <= 0) {
          var tmp = integerLogarithm(value, base3.square(base3));
          var p5 = tmp.p;
          var e4 = tmp.e;
          var t4 = p5.multiply(base3);
          return t4.compareTo(value) <= 0 ? { p: t4, e: e4 * 2 + 1 } : { p: p5, e: e4 * 2 };
        }
        return { p: bigInt(1), e: 0 };
      }
      BigInteger.prototype.bitLength = function() {
        var n3 = this;
        if (n3.compareTo(bigInt(0)) < 0) {
          n3 = n3.negate().subtract(bigInt(1));
        }
        if (n3.compareTo(bigInt(0)) === 0) {
          return bigInt(0);
        }
        return bigInt(integerLogarithm(n3, bigInt(2)).e).add(bigInt(1));
      };
      NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;
      function max2(a4, b4) {
        a4 = parseValue(a4);
        b4 = parseValue(b4);
        return a4.greater(b4) ? a4 : b4;
      }
      function min(a4, b4) {
        a4 = parseValue(a4);
        b4 = parseValue(b4);
        return a4.lesser(b4) ? a4 : b4;
      }
      function gcd(a4, b4) {
        a4 = parseValue(a4).abs();
        b4 = parseValue(b4).abs();
        if (a4.equals(b4))
          return a4;
        if (a4.isZero())
          return b4;
        if (b4.isZero())
          return a4;
        var c4 = Integer[1], d4, t4;
        while (a4.isEven() && b4.isEven()) {
          d4 = min(roughLOB(a4), roughLOB(b4));
          a4 = a4.divide(d4);
          b4 = b4.divide(d4);
          c4 = c4.multiply(d4);
        }
        while (a4.isEven()) {
          a4 = a4.divide(roughLOB(a4));
        }
        do {
          while (b4.isEven()) {
            b4 = b4.divide(roughLOB(b4));
          }
          if (a4.greater(b4)) {
            t4 = b4;
            b4 = a4;
            a4 = t4;
          }
          b4 = b4.subtract(a4);
        } while (!b4.isZero());
        return c4.isUnit() ? a4 : a4.multiply(c4);
      }
      function lcm(a4, b4) {
        a4 = parseValue(a4).abs();
        b4 = parseValue(b4).abs();
        return a4.divide(gcd(a4, b4)).multiply(b4);
      }
      function randBetween(a4, b4, rng) {
        a4 = parseValue(a4);
        b4 = parseValue(b4);
        var usedRNG = rng || Math.random;
        var low = min(a4, b4), high = max2(a4, b4);
        var range = high.subtract(low).add(1);
        if (range.isSmall)
          return low.add(Math.floor(usedRNG() * range));
        var digits = toBase(range, BASE).value;
        var result = [], restricted = true;
        for (var i5 = 0; i5 < digits.length; i5++) {
          var top = restricted ? digits[i5] + (i5 + 1 < digits.length ? digits[i5 + 1] / BASE : 0) : BASE;
          var digit2 = truncate(usedRNG() * top);
          result.push(digit2);
          if (digit2 < digits[i5])
            restricted = false;
        }
        return low.add(Integer.fromArray(result, BASE, false));
      }
      var parseBase = function(text, base3, alphabet, caseSensitive) {
        alphabet = alphabet || DEFAULT_ALPHABET;
        text = String(text);
        if (!caseSensitive) {
          text = text.toLowerCase();
          alphabet = alphabet.toLowerCase();
        }
        var length = text.length;
        var i5;
        var absBase = Math.abs(base3);
        var alphabetValues = {};
        for (i5 = 0; i5 < alphabet.length; i5++) {
          alphabetValues[alphabet[i5]] = i5;
        }
        for (i5 = 0; i5 < length; i5++) {
          var c4 = text[i5];
          if (c4 === "-")
            continue;
          if (c4 in alphabetValues) {
            if (alphabetValues[c4] >= absBase) {
              if (c4 === "1" && absBase === 1)
                continue;
              throw new Error(c4 + " is not a valid digit in base " + base3 + ".");
            }
          }
        }
        base3 = parseValue(base3);
        var digits = [];
        var isNegative = text[0] === "-";
        for (i5 = isNegative ? 1 : 0; i5 < text.length; i5++) {
          var c4 = text[i5];
          if (c4 in alphabetValues)
            digits.push(parseValue(alphabetValues[c4]));
          else if (c4 === "<") {
            var start = i5;
            do {
              i5++;
            } while (text[i5] !== ">" && i5 < text.length);
            digits.push(parseValue(text.slice(start + 1, i5)));
          } else
            throw new Error(c4 + " is not a valid character");
        }
        return parseBaseFromArray(digits, base3, isNegative);
      };
      function parseBaseFromArray(digits, base3, isNegative) {
        var val = Integer[0], pow = Integer[1], i5;
        for (i5 = digits.length - 1; i5 >= 0; i5--) {
          val = val.add(digits[i5].times(pow));
          pow = pow.times(base3);
        }
        return isNegative ? val.negate() : val;
      }
      function stringify(digit2, alphabet) {
        alphabet = alphabet || DEFAULT_ALPHABET;
        if (digit2 < alphabet.length) {
          return alphabet[digit2];
        }
        return "<" + digit2 + ">";
      }
      function toBase(n3, base3) {
        base3 = bigInt(base3);
        if (base3.isZero()) {
          if (n3.isZero())
            return { value: [0], isNegative: false };
          throw new Error("Cannot convert nonzero numbers to base 0.");
        }
        if (base3.equals(-1)) {
          if (n3.isZero())
            return { value: [0], isNegative: false };
          if (n3.isNegative())
            return {
              value: [].concat.apply(
                [],
                Array.apply(null, Array(-n3.toJSNumber())).map(Array.prototype.valueOf, [1, 0])
              ),
              isNegative: false
            };
          var arr = Array.apply(null, Array(n3.toJSNumber() - 1)).map(Array.prototype.valueOf, [0, 1]);
          arr.unshift([1]);
          return {
            value: [].concat.apply([], arr),
            isNegative: false
          };
        }
        var neg = false;
        if (n3.isNegative() && base3.isPositive()) {
          neg = true;
          n3 = n3.abs();
        }
        if (base3.isUnit()) {
          if (n3.isZero())
            return { value: [0], isNegative: false };
          return {
            value: Array.apply(null, Array(n3.toJSNumber())).map(Number.prototype.valueOf, 1),
            isNegative: neg
          };
        }
        var out = [];
        var left = n3, divmod;
        while (left.isNegative() || left.compareAbs(base3) >= 0) {
          divmod = left.divmod(base3);
          left = divmod.quotient;
          var digit2 = divmod.remainder;
          if (digit2.isNegative()) {
            digit2 = base3.minus(digit2).abs();
            left = left.next();
          }
          out.push(digit2.toJSNumber());
        }
        out.push(left.toJSNumber());
        return { value: out.reverse(), isNegative: neg };
      }
      function toBaseString(n3, base3, alphabet) {
        var arr = toBase(n3, base3);
        return (arr.isNegative ? "-" : "") + arr.value.map(function(x3) {
          return stringify(x3, alphabet);
        }).join("");
      }
      BigInteger.prototype.toArray = function(radix) {
        return toBase(this, radix);
      };
      SmallInteger.prototype.toArray = function(radix) {
        return toBase(this, radix);
      };
      NativeBigInt.prototype.toArray = function(radix) {
        return toBase(this, radix);
      };
      BigInteger.prototype.toString = function(radix, alphabet) {
        if (radix === undefined2)
          radix = 10;
        if (radix !== 10 || alphabet)
          return toBaseString(this, radix, alphabet);
        var v4 = this.value, l4 = v4.length, str = String(v4[--l4]), zeros = "0000000", digit2;
        while (--l4 >= 0) {
          digit2 = String(v4[l4]);
          str += zeros.slice(digit2.length) + digit2;
        }
        var sign2 = this.sign ? "-" : "";
        return sign2 + str;
      };
      SmallInteger.prototype.toString = function(radix, alphabet) {
        if (radix === undefined2)
          radix = 10;
        if (radix != 10 || alphabet)
          return toBaseString(this, radix, alphabet);
        return String(this.value);
      };
      NativeBigInt.prototype.toString = SmallInteger.prototype.toString;
      NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function() {
        return this.toString();
      };
      BigInteger.prototype.valueOf = function() {
        return parseInt(this.toString(), 10);
      };
      BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
      SmallInteger.prototype.valueOf = function() {
        return this.value;
      };
      SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
      NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function() {
        return parseInt(this.toString(), 10);
      };
      function parseStringValue(v4) {
        if (isPrecise(+v4)) {
          var x3 = +v4;
          if (x3 === truncate(x3))
            return supportsNativeBigInt ? new NativeBigInt(BigInt(x3)) : new SmallInteger(x3);
          throw new Error("Invalid integer: " + v4);
        }
        var sign2 = v4[0] === "-";
        if (sign2)
          v4 = v4.slice(1);
        var split = v4.split(/e/i);
        if (split.length > 2)
          throw new Error("Invalid integer: " + split.join("e"));
        if (split.length === 2) {
          var exp = split[1];
          if (exp[0] === "+")
            exp = exp.slice(1);
          exp = +exp;
          if (exp !== truncate(exp) || !isPrecise(exp))
            throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
          var text = split[0];
          var decimalPlace = text.indexOf(".");
          if (decimalPlace >= 0) {
            exp -= text.length - decimalPlace - 1;
            text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
          }
          if (exp < 0)
            throw new Error("Cannot include negative exponent part for integers");
          text += new Array(exp + 1).join("0");
          v4 = text;
        }
        var isValid2 = /^([0-9][0-9]*)$/.test(v4);
        if (!isValid2)
          throw new Error("Invalid integer: " + v4);
        if (supportsNativeBigInt) {
          return new NativeBigInt(BigInt(sign2 ? "-" + v4 : v4));
        }
        var r4 = [], max3 = v4.length, l4 = LOG_BASE, min2 = max3 - l4;
        while (max3 > 0) {
          r4.push(+v4.slice(min2, max3));
          min2 -= l4;
          if (min2 < 0)
            min2 = 0;
          max3 -= l4;
        }
        trim(r4);
        return new BigInteger(r4, sign2);
      }
      function parseNumberValue(v4) {
        if (supportsNativeBigInt) {
          return new NativeBigInt(BigInt(v4));
        }
        if (isPrecise(v4)) {
          if (v4 !== truncate(v4))
            throw new Error(v4 + " is not an integer.");
          return new SmallInteger(v4);
        }
        return parseStringValue(v4.toString());
      }
      function parseValue(v4) {
        if (typeof v4 === "number") {
          return parseNumberValue(v4);
        }
        if (typeof v4 === "string") {
          return parseStringValue(v4);
        }
        if (typeof v4 === "bigint") {
          return new NativeBigInt(v4);
        }
        return v4;
      }
      for (var i4 = 0; i4 < 1e3; i4++) {
        Integer[i4] = parseValue(i4);
        if (i4 > 0)
          Integer[-i4] = parseValue(-i4);
      }
      Integer.one = Integer[1];
      Integer.zero = Integer[0];
      Integer.minusOne = Integer[-1];
      Integer.max = max2;
      Integer.min = min;
      Integer.gcd = gcd;
      Integer.lcm = lcm;
      Integer.isInstance = function(x3) {
        return x3 instanceof BigInteger || x3 instanceof SmallInteger || x3 instanceof NativeBigInt;
      };
      Integer.randBetween = randBetween;
      Integer.fromArray = function(digits, base3, isNegative) {
        return parseBaseFromArray(digits.map(parseValue), parseValue(base3 || 10), isNegative);
      };
      return Integer;
    }();
    if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
      module.exports = bigInt;
    }
    if (typeof define === "function" && define.amd) {
      define(function() {
        return bigInt;
      });
    }
  }
});

// ../../node_modules/.pnpm/jed@1.1.1/node_modules/jed/jed.js
var require_jed = __commonJS({
  "../../node_modules/.pnpm/jed@1.1.1/node_modules/jed/jed.js"(exports, module) {
    (function(root, undef) {
      var ArrayProto = Array.prototype, ObjProto = Object.prototype, slice = ArrayProto.slice, hasOwnProp = ObjProto.hasOwnProperty, nativeForEach = ArrayProto.forEach, breaker = {};
      var _4 = {
        forEach: function(obj, iterator, context) {
          var i4, l4, key;
          if (obj === null) {
            return;
          }
          if (nativeForEach && obj.forEach === nativeForEach) {
            obj.forEach(iterator, context);
          } else if (obj.length === +obj.length) {
            for (i4 = 0, l4 = obj.length; i4 < l4; i4++) {
              if (i4 in obj && iterator.call(context, obj[i4], i4, obj) === breaker) {
                return;
              }
            }
          } else {
            for (key in obj) {
              if (hasOwnProp.call(obj, key)) {
                if (iterator.call(context, obj[key], key, obj) === breaker) {
                  return;
                }
              }
            }
          }
        },
        extend: function(obj) {
          this.forEach(slice.call(arguments, 1), function(source) {
            for (var prop in source) {
              obj[prop] = source[prop];
            }
          });
          return obj;
        }
      };
      var Jed2 = function(options) {
        this.defaults = {
          "locale_data": {
            "messages": {
              "": {
                "domain": "messages",
                "lang": "en",
                "plural_forms": "nplurals=2; plural=(n != 1);"
              }
              // There are no default keys, though
            }
          },
          // The default domain if one is missing
          "domain": "messages",
          // enable debug mode to log untranslated strings to the console
          "debug": false
        };
        this.options = _4.extend({}, this.defaults, options);
        this.textdomain(this.options.domain);
        if (options.domain && !this.options.locale_data[this.options.domain]) {
          throw new Error("Text domain set to non-existent domain: `" + options.domain + "`");
        }
      };
      Jed2.context_delimiter = String.fromCharCode(4);
      function getPluralFormFunc(plural_form_string) {
        return Jed2.PF.compile(plural_form_string || "nplurals=2; plural=(n != 1);");
      }
      function Chain(key, i18n2) {
        this._key = key;
        this._i18n = i18n2;
      }
      _4.extend(Chain.prototype, {
        onDomain: function(domain) {
          this._domain = domain;
          return this;
        },
        withContext: function(context) {
          this._context = context;
          return this;
        },
        ifPlural: function(num, pkey) {
          this._val = num;
          this._pkey = pkey;
          return this;
        },
        fetch: function(sArr) {
          if ({}.toString.call(sArr) != "[object Array]") {
            sArr = [].slice.call(arguments, 0);
          }
          return (sArr && sArr.length ? Jed2.sprintf : function(x3) {
            return x3;
          })(
            this._i18n.dcnpgettext(this._domain, this._context, this._key, this._pkey, this._val),
            sArr
          );
        }
      });
      _4.extend(Jed2.prototype, {
        // The sexier api start point
        translate: function(key) {
          return new Chain(key, this);
        },
        textdomain: function(domain) {
          if (!domain) {
            return this._textdomain;
          }
          this._textdomain = domain;
        },
        gettext: function(key) {
          return this.dcnpgettext.call(this, undef, undef, key);
        },
        dgettext: function(domain, key) {
          return this.dcnpgettext.call(this, domain, undef, key);
        },
        dcgettext: function(domain, key) {
          return this.dcnpgettext.call(this, domain, undef, key);
        },
        ngettext: function(skey, pkey, val) {
          return this.dcnpgettext.call(this, undef, undef, skey, pkey, val);
        },
        dngettext: function(domain, skey, pkey, val) {
          return this.dcnpgettext.call(this, domain, undef, skey, pkey, val);
        },
        dcngettext: function(domain, skey, pkey, val) {
          return this.dcnpgettext.call(this, domain, undef, skey, pkey, val);
        },
        pgettext: function(context, key) {
          return this.dcnpgettext.call(this, undef, context, key);
        },
        dpgettext: function(domain, context, key) {
          return this.dcnpgettext.call(this, domain, context, key);
        },
        dcpgettext: function(domain, context, key) {
          return this.dcnpgettext.call(this, domain, context, key);
        },
        npgettext: function(context, skey, pkey, val) {
          return this.dcnpgettext.call(this, undef, context, skey, pkey, val);
        },
        dnpgettext: function(domain, context, skey, pkey, val) {
          return this.dcnpgettext.call(this, domain, context, skey, pkey, val);
        },
        // The most fully qualified gettext function. It has every option.
        // Since it has every option, we can use it from every other method.
        // This is the bread and butter.
        // Technically there should be one more argument in this function for 'Category',
        // but since we never use it, we might as well not waste the bytes to define it.
        dcnpgettext: function(domain, context, singular_key, plural_key, val) {
          plural_key = plural_key || singular_key;
          domain = domain || this._textdomain;
          var fallback;
          if (!this.options) {
            fallback = new Jed2();
            return fallback.dcnpgettext.call(fallback, void 0, void 0, singular_key, plural_key, val);
          }
          if (!this.options.locale_data) {
            throw new Error("No locale data provided.");
          }
          if (!this.options.locale_data[domain]) {
            throw new Error("Domain `" + domain + "` was not found.");
          }
          if (!this.options.locale_data[domain][""]) {
            throw new Error("No locale meta information provided.");
          }
          if (!singular_key) {
            throw new Error("No translation key found.");
          }
          var key = context ? context + Jed2.context_delimiter + singular_key : singular_key, locale_data = this.options.locale_data, dict = locale_data[domain], defaultConf = (locale_data.messages || this.defaults.locale_data.messages)[""], pluralForms = dict[""].plural_forms || dict[""]["Plural-Forms"] || dict[""]["plural-forms"] || defaultConf.plural_forms || defaultConf["Plural-Forms"] || defaultConf["plural-forms"], val_list, res;
          var val_idx;
          if (val === void 0) {
            val_idx = 0;
          } else {
            if (typeof val != "number") {
              val = parseInt(val, 10);
              if (isNaN(val)) {
                throw new Error("The number that was passed in is not a number.");
              }
            }
            val_idx = getPluralFormFunc(pluralForms)(val);
          }
          if (!dict) {
            throw new Error("No domain named `" + domain + "` could be found.");
          }
          val_list = dict[key];
          if (!val_list || val_idx > val_list.length) {
            if (this.options.missing_key_callback) {
              this.options.missing_key_callback(key, domain);
            }
            res = [singular_key, plural_key];
            if (this.options.debug === true) {
              console.log(res[getPluralFormFunc(pluralForms)(val)]);
            }
            return res[getPluralFormFunc()(val)];
          }
          res = val_list[val_idx];
          if (!res) {
            res = [singular_key, plural_key];
            return res[getPluralFormFunc()(val)];
          }
          return res;
        }
      });
      var sprintf = function() {
        function get_type(variable) {
          return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
        }
        function str_repeat(input, multiplier) {
          for (var output = []; multiplier > 0; output[--multiplier] = input) {
          }
          return output.join("");
        }
        var str_format = function() {
          if (!str_format.cache.hasOwnProperty(arguments[0])) {
            str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
          }
          return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
        };
        str_format.format = function(parse_tree, argv) {
          var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i4, k4, match2, pad, pad_character, pad_length;
          for (i4 = 0; i4 < tree_length; i4++) {
            node_type = get_type(parse_tree[i4]);
            if (node_type === "string") {
              output.push(parse_tree[i4]);
            } else if (node_type === "array") {
              match2 = parse_tree[i4];
              if (match2[2]) {
                arg = argv[cursor];
                for (k4 = 0; k4 < match2[2].length; k4++) {
                  if (!arg.hasOwnProperty(match2[2][k4])) {
                    throw sprintf('[sprintf] property "%s" does not exist', match2[2][k4]);
                  }
                  arg = arg[match2[2][k4]];
                }
              } else if (match2[1]) {
                arg = argv[match2[1]];
              } else {
                arg = argv[cursor++];
              }
              if (/[^s]/.test(match2[8]) && get_type(arg) != "number") {
                throw sprintf("[sprintf] expecting number but found %s", get_type(arg));
              }
              if (typeof arg == "undefined" || arg === null) {
                arg = "";
              }
              switch (match2[8]) {
                case "b":
                  arg = arg.toString(2);
                  break;
                case "c":
                  arg = String.fromCharCode(arg);
                  break;
                case "d":
                  arg = parseInt(arg, 10);
                  break;
                case "e":
                  arg = match2[7] ? arg.toExponential(match2[7]) : arg.toExponential();
                  break;
                case "f":
                  arg = match2[7] ? parseFloat(arg).toFixed(match2[7]) : parseFloat(arg);
                  break;
                case "o":
                  arg = arg.toString(8);
                  break;
                case "s":
                  arg = (arg = String(arg)) && match2[7] ? arg.substring(0, match2[7]) : arg;
                  break;
                case "u":
                  arg = Math.abs(arg);
                  break;
                case "x":
                  arg = arg.toString(16);
                  break;
                case "X":
                  arg = arg.toString(16).toUpperCase();
                  break;
              }
              arg = /[def]/.test(match2[8]) && match2[3] && arg >= 0 ? "+" + arg : arg;
              pad_character = match2[4] ? match2[4] == "0" ? "0" : match2[4].charAt(1) : " ";
              pad_length = match2[6] - String(arg).length;
              pad = match2[6] ? str_repeat(pad_character, pad_length) : "";
              output.push(match2[5] ? arg + pad : pad + arg);
            }
          }
          return output.join("");
        };
        str_format.cache = {};
        str_format.parse = function(fmt) {
          var _fmt = fmt, match2 = [], parse_tree = [], arg_names = 0;
          while (_fmt) {
            if ((match2 = /^[^\x25]+/.exec(_fmt)) !== null) {
              parse_tree.push(match2[0]);
            } else if ((match2 = /^\x25{2}/.exec(_fmt)) !== null) {
              parse_tree.push("%");
            } else if ((match2 = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
              if (match2[2]) {
                arg_names |= 1;
                var field_list = [], replacement_field = match2[2], field_match = [];
                if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
                  field_list.push(field_match[1]);
                  while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") {
                    if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
                      field_list.push(field_match[1]);
                    } else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
                      field_list.push(field_match[1]);
                    } else {
                      throw "[sprintf] huh?";
                    }
                  }
                } else {
                  throw "[sprintf] huh?";
                }
                match2[2] = field_list;
              } else {
                arg_names |= 2;
              }
              if (arg_names === 3) {
                throw "[sprintf] mixing positional and named placeholders is not (yet) supported";
              }
              parse_tree.push(match2);
            } else {
              throw "[sprintf] huh?";
            }
            _fmt = _fmt.substring(match2[0].length);
          }
          return parse_tree;
        };
        return str_format;
      }();
      var vsprintf = function(fmt, argv) {
        argv.unshift(fmt);
        return sprintf.apply(null, argv);
      };
      Jed2.parse_plural = function(plural_forms, n3) {
        plural_forms = plural_forms.replace(/n/g, n3);
        return Jed2.parse_expression(plural_forms);
      };
      Jed2.sprintf = function(fmt, args) {
        if ({}.toString.call(args) == "[object Array]") {
          return vsprintf(fmt, [].slice.call(args));
        }
        return sprintf.apply(this, [].slice.call(arguments));
      };
      Jed2.prototype.sprintf = function() {
        return Jed2.sprintf.apply(this, arguments);
      };
      Jed2.PF = {};
      Jed2.PF.parse = function(p5) {
        var plural_str = Jed2.PF.extractPluralExpr(p5);
        return Jed2.PF.parser.parse.call(Jed2.PF.parser, plural_str);
      };
      Jed2.PF.compile = function(p5) {
        function imply(val) {
          return val === true ? 1 : val ? val : 0;
        }
        var ast = Jed2.PF.parse(p5);
        return function(n3) {
          return imply(Jed2.PF.interpreter(ast)(n3));
        };
      };
      Jed2.PF.interpreter = function(ast) {
        return function(n3) {
          var res;
          switch (ast.type) {
            case "GROUP":
              return Jed2.PF.interpreter(ast.expr)(n3);
            case "TERNARY":
              if (Jed2.PF.interpreter(ast.expr)(n3)) {
                return Jed2.PF.interpreter(ast.truthy)(n3);
              }
              return Jed2.PF.interpreter(ast.falsey)(n3);
            case "OR":
              return Jed2.PF.interpreter(ast.left)(n3) || Jed2.PF.interpreter(ast.right)(n3);
            case "AND":
              return Jed2.PF.interpreter(ast.left)(n3) && Jed2.PF.interpreter(ast.right)(n3);
            case "LT":
              return Jed2.PF.interpreter(ast.left)(n3) < Jed2.PF.interpreter(ast.right)(n3);
            case "GT":
              return Jed2.PF.interpreter(ast.left)(n3) > Jed2.PF.interpreter(ast.right)(n3);
            case "LTE":
              return Jed2.PF.interpreter(ast.left)(n3) <= Jed2.PF.interpreter(ast.right)(n3);
            case "GTE":
              return Jed2.PF.interpreter(ast.left)(n3) >= Jed2.PF.interpreter(ast.right)(n3);
            case "EQ":
              return Jed2.PF.interpreter(ast.left)(n3) == Jed2.PF.interpreter(ast.right)(n3);
            case "NEQ":
              return Jed2.PF.interpreter(ast.left)(n3) != Jed2.PF.interpreter(ast.right)(n3);
            case "MOD":
              return Jed2.PF.interpreter(ast.left)(n3) % Jed2.PF.interpreter(ast.right)(n3);
            case "VAR":
              return n3;
            case "NUM":
              return ast.val;
            default:
              throw new Error("Invalid Token found.");
          }
        };
      };
      Jed2.PF.extractPluralExpr = function(p5) {
        p5 = p5.replace(/^\s\s*/, "").replace(/\s\s*$/, "");
        if (!/;\s*$/.test(p5)) {
          p5 = p5.concat(";");
        }
        var nplurals_re = /nplurals\=(\d+);/, plural_re = /plural\=(.*);/, nplurals_matches = p5.match(nplurals_re), res = {}, plural_matches;
        if (nplurals_matches.length > 1) {
          res.nplurals = nplurals_matches[1];
        } else {
          throw new Error("nplurals not found in plural_forms string: " + p5);
        }
        p5 = p5.replace(nplurals_re, "");
        plural_matches = p5.match(plural_re);
        if (!(plural_matches && plural_matches.length > 1)) {
          throw new Error("`plural` expression not found: " + p5);
        }
        return plural_matches[1];
      };
      Jed2.PF.parser = function() {
        var parser = {
          trace: function trace() {
          },
          yy: {},
          symbols_: { "error": 2, "expressions": 3, "e": 4, "EOF": 5, "?": 6, ":": 7, "||": 8, "&&": 9, "<": 10, "<=": 11, ">": 12, ">=": 13, "!=": 14, "==": 15, "%": 16, "(": 17, ")": 18, "n": 19, "NUMBER": 20, "$accept": 0, "$end": 1 },
          terminals_: { 2: "error", 5: "EOF", 6: "?", 7: ":", 8: "||", 9: "&&", 10: "<", 11: "<=", 12: ">", 13: ">=", 14: "!=", 15: "==", 16: "%", 17: "(", 18: ")", 19: "n", 20: "NUMBER" },
          productions_: [0, [3, 2], [4, 5], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 1], [4, 1]],
          performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) {
            var $0 = $$.length - 1;
            switch (yystate) {
              case 1:
                return { type: "GROUP", expr: $$[$0 - 1] };
                break;
              case 2:
                this.$ = { type: "TERNARY", expr: $$[$0 - 4], truthy: $$[$0 - 2], falsey: $$[$0] };
                break;
              case 3:
                this.$ = { type: "OR", left: $$[$0 - 2], right: $$[$0] };
                break;
              case 4:
                this.$ = { type: "AND", left: $$[$0 - 2], right: $$[$0] };
                break;
              case 5:
                this.$ = { type: "LT", left: $$[$0 - 2], right: $$[$0] };
                break;
              case 6:
                this.$ = { type: "LTE", left: $$[$0 - 2], right: $$[$0] };
                break;
              case 7:
                this.$ = { type: "GT", left: $$[$0 - 2], right: $$[$0] };
                break;
              case 8:
                this.$ = { type: "GTE", left: $$[$0 - 2], right: $$[$0] };
                break;
              case 9:
                this.$ = { type: "NEQ", left: $$[$0 - 2], right: $$[$0] };
                break;
              case 10:
                this.$ = { type: "EQ", left: $$[$0 - 2], right: $$[$0] };
                break;
              case 11:
                this.$ = { type: "MOD", left: $$[$0 - 2], right: $$[$0] };
                break;
              case 12:
                this.$ = { type: "GROUP", expr: $$[$0 - 1] };
                break;
              case 13:
                this.$ = { type: "VAR" };
                break;
              case 14:
                this.$ = { type: "NUM", val: Number(yytext) };
                break;
            }
          },
          table: [{ 3: 1, 4: 2, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 1: [3] }, { 5: [1, 6], 6: [1, 7], 8: [1, 8], 9: [1, 9], 10: [1, 10], 11: [1, 11], 12: [1, 12], 13: [1, 13], 14: [1, 14], 15: [1, 15], 16: [1, 16] }, { 4: 17, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 5: [2, 13], 6: [2, 13], 7: [2, 13], 8: [2, 13], 9: [2, 13], 10: [2, 13], 11: [2, 13], 12: [2, 13], 13: [2, 13], 14: [2, 13], 15: [2, 13], 16: [2, 13], 18: [2, 13] }, { 5: [2, 14], 6: [2, 14], 7: [2, 14], 8: [2, 14], 9: [2, 14], 10: [2, 14], 11: [2, 14], 12: [2, 14], 13: [2, 14], 14: [2, 14], 15: [2, 14], 16: [2, 14], 18: [2, 14] }, { 1: [2, 1] }, { 4: 18, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 4: 19, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 4: 20, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 4: 21, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 4: 22, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 4: 23, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 4: 24, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 4: 25, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 4: 26, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 4: 27, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 6: [1, 7], 8: [1, 8], 9: [1, 9], 10: [1, 10], 11: [1, 11], 12: [1, 12], 13: [1, 13], 14: [1, 14], 15: [1, 15], 16: [1, 16], 18: [1, 28] }, { 6: [1, 7], 7: [1, 29], 8: [1, 8], 9: [1, 9], 10: [1, 10], 11: [1, 11], 12: [1, 12], 13: [1, 13], 14: [1, 14], 15: [1, 15], 16: [1, 16] }, { 5: [2, 3], 6: [2, 3], 7: [2, 3], 8: [2, 3], 9: [1, 9], 10: [1, 10], 11: [1, 11], 12: [1, 12], 13: [1, 13], 14: [1, 14], 15: [1, 15], 16: [1, 16], 18: [2, 3] }, { 5: [2, 4], 6: [2, 4], 7: [2, 4], 8: [2, 4], 9: [2, 4], 10: [1, 10], 11: [1, 11], 12: [1, 12], 13: [1, 13], 14: [1, 14], 15: [1, 15], 16: [1, 16], 18: [2, 4] }, { 5: [2, 5], 6: [2, 5], 7: [2, 5], 8: [2, 5], 9: [2, 5], 10: [2, 5], 11: [2, 5], 12: [2, 5], 13: [2, 5], 14: [2, 5], 15: [2, 5], 16: [1, 16], 18: [2, 5] }, { 5: [2, 6], 6: [2, 6], 7: [2, 6], 8: [2, 6], 9: [2, 6], 10: [2, 6], 11: [2, 6], 12: [2, 6], 13: [2, 6], 14: [2, 6], 15: [2, 6], 16: [1, 16], 18: [2, 6] }, { 5: [2, 7], 6: [2, 7], 7: [2, 7], 8: [2, 7], 9: [2, 7], 10: [2, 7], 11: [2, 7], 12: [2, 7], 13: [2, 7], 14: [2, 7], 15: [2, 7], 16: [1, 16], 18: [2, 7] }, { 5: [2, 8], 6: [2, 8], 7: [2, 8], 8: [2, 8], 9: [2, 8], 10: [2, 8], 11: [2, 8], 12: [2, 8], 13: [2, 8], 14: [2, 8], 15: [2, 8], 16: [1, 16], 18: [2, 8] }, { 5: [2, 9], 6: [2, 9], 7: [2, 9], 8: [2, 9], 9: [2, 9], 10: [2, 9], 11: [2, 9], 12: [2, 9], 13: [2, 9], 14: [2, 9], 15: [2, 9], 16: [1, 16], 18: [2, 9] }, { 5: [2, 10], 6: [2, 10], 7: [2, 10], 8: [2, 10], 9: [2, 10], 10: [2, 10], 11: [2, 10], 12: [2, 10], 13: [2, 10], 14: [2, 10], 15: [2, 10], 16: [1, 16], 18: [2, 10] }, { 5: [2, 11], 6: [2, 11], 7: [2, 11], 8: [2, 11], 9: [2, 11], 10: [2, 11], 11: [2, 11], 12: [2, 11], 13: [2, 11], 14: [2, 11], 15: [2, 11], 16: [2, 11], 18: [2, 11] }, { 5: [2, 12], 6: [2, 12], 7: [2, 12], 8: [2, 12], 9: [2, 12], 10: [2, 12], 11: [2, 12], 12: [2, 12], 13: [2, 12], 14: [2, 12], 15: [2, 12], 16: [2, 12], 18: [2, 12] }, { 4: 30, 17: [1, 3], 19: [1, 4], 20: [1, 5] }, { 5: [2, 2], 6: [1, 7], 7: [2, 2], 8: [1, 8], 9: [1, 9], 10: [1, 10], 11: [1, 11], 12: [1, 12], 13: [1, 13], 14: [1, 14], 15: [1, 15], 16: [1, 16], 18: [2, 2] }],
          defaultActions: { 6: [2, 1] },
          parseError: function parseError(str, hash3) {
            throw new Error(str);
          },
          parse: function parse2(input) {
            var self2 = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;
            this.lexer.setInput(input);
            this.lexer.yy = this.yy;
            this.yy.lexer = this.lexer;
            if (typeof this.lexer.yylloc == "undefined")
              this.lexer.yylloc = {};
            var yyloc = this.lexer.yylloc;
            lstack.push(yyloc);
            if (typeof this.yy.parseError === "function")
              this.parseError = this.yy.parseError;
            function popStack(n3) {
              stack.length = stack.length - 2 * n3;
              vstack.length = vstack.length - n3;
              lstack.length = lstack.length - n3;
            }
            function lex() {
              var token;
              token = self2.lexer.lex() || 1;
              if (typeof token !== "number") {
                token = self2.symbols_[token] || token;
              }
              return token;
            }
            var symbol, preErrorSymbol, state, action, a4, r4, yyval = {}, p5, len, newState, expected;
            while (true) {
              state = stack[stack.length - 1];
              if (this.defaultActions[state]) {
                action = this.defaultActions[state];
              } else {
                if (symbol == null)
                  symbol = lex();
                action = table[state] && table[state][symbol];
              }
              _handle_error:
                if (typeof action === "undefined" || !action.length || !action[0]) {
                  if (!recovering) {
                    expected = [];
                    for (p5 in table[state])
                      if (this.terminals_[p5] && p5 > 2) {
                        expected.push("'" + this.terminals_[p5] + "'");
                      }
                    var errStr = "";
                    if (this.lexer.showPosition) {
                      errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + this.terminals_[symbol] + "'";
                    } else {
                      errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
                    }
                    this.parseError(
                      errStr,
                      { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected }
                    );
                  }
                  if (recovering == 3) {
                    if (symbol == EOF) {
                      throw new Error(errStr || "Parsing halted.");
                    }
                    yyleng = this.lexer.yyleng;
                    yytext = this.lexer.yytext;
                    yylineno = this.lexer.yylineno;
                    yyloc = this.lexer.yylloc;
                    symbol = lex();
                  }
                  while (1) {
                    if (TERROR.toString() in table[state]) {
                      break;
                    }
                    if (state == 0) {
                      throw new Error(errStr || "Parsing halted.");
                    }
                    popStack(1);
                    state = stack[stack.length - 1];
                  }
                  preErrorSymbol = symbol;
                  symbol = TERROR;
                  state = stack[stack.length - 1];
                  action = table[state] && table[state][TERROR];
                  recovering = 3;
                }
              if (action[0] instanceof Array && action.length > 1) {
                throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
              }
              switch (action[0]) {
                case 1:
                  stack.push(symbol);
                  vstack.push(this.lexer.yytext);
                  lstack.push(this.lexer.yylloc);
                  stack.push(action[1]);
                  symbol = null;
                  if (!preErrorSymbol) {
                    yyleng = this.lexer.yyleng;
                    yytext = this.lexer.yytext;
                    yylineno = this.lexer.yylineno;
                    yyloc = this.lexer.yylloc;
                    if (recovering > 0)
                      recovering--;
                  } else {
                    symbol = preErrorSymbol;
                    preErrorSymbol = null;
                  }
                  break;
                case 2:
                  len = this.productions_[action[1]][1];
                  yyval.$ = vstack[vstack.length - len];
                  yyval._$ = {
                    first_line: lstack[lstack.length - (len || 1)].first_line,
                    last_line: lstack[lstack.length - 1].last_line,
                    first_column: lstack[lstack.length - (len || 1)].first_column,
                    last_column: lstack[lstack.length - 1].last_column
                  };
                  r4 = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
                  if (typeof r4 !== "undefined") {
                    return r4;
                  }
                  if (len) {
                    stack = stack.slice(0, -1 * len * 2);
                    vstack = vstack.slice(0, -1 * len);
                    lstack = lstack.slice(0, -1 * len);
                  }
                  stack.push(this.productions_[action[1]][0]);
                  vstack.push(yyval.$);
                  lstack.push(yyval._$);
                  newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
                  stack.push(newState);
                  break;
                case 3:
                  return true;
              }
            }
            return true;
          }
        };
        var lexer = function() {
          var lexer2 = {
            EOF: 1,
            parseError: function parseError(str, hash3) {
              if (this.yy.parseError) {
                this.yy.parseError(str, hash3);
              } else {
                throw new Error(str);
              }
            },
            setInput: function(input) {
              this._input = input;
              this._more = this._less = this.done = false;
              this.yylineno = this.yyleng = 0;
              this.yytext = this.matched = this.match = "";
              this.conditionStack = ["INITIAL"];
              this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
              return this;
            },
            input: function() {
              var ch = this._input[0];
              this.yytext += ch;
              this.yyleng++;
              this.match += ch;
              this.matched += ch;
              var lines = ch.match(/\n/);
              if (lines)
                this.yylineno++;
              this._input = this._input.slice(1);
              return ch;
            },
            unput: function(ch) {
              this._input = ch + this._input;
              return this;
            },
            more: function() {
              this._more = true;
              return this;
            },
            pastInput: function() {
              var past = this.matched.substr(0, this.matched.length - this.match.length);
              return (past.length > 20 ? "..." : "") + past.substr(-20).replace(/\n/g, "");
            },
            upcomingInput: function() {
              var next = this.match;
              if (next.length < 20) {
                next += this._input.substr(0, 20 - next.length);
              }
              return (next.substr(0, 20) + (next.length > 20 ? "..." : "")).replace(/\n/g, "");
            },
            showPosition: function() {
              var pre = this.pastInput();
              var c4 = new Array(pre.length + 1).join("-");
              return pre + this.upcomingInput() + "\n" + c4 + "^";
            },
            next: function() {
              if (this.done) {
                return this.EOF;
              }
              if (!this._input)
                this.done = true;
              var token, match2, col, lines;
              if (!this._more) {
                this.yytext = "";
                this.match = "";
              }
              var rules = this._currentRules();
              for (var i4 = 0; i4 < rules.length; i4++) {
                match2 = this._input.match(this.rules[rules[i4]]);
                if (match2) {
                  lines = match2[0].match(/\n.*/g);
                  if (lines)
                    this.yylineno += lines.length;
                  this.yylloc = {
                    first_line: this.yylloc.last_line,
                    last_line: this.yylineno + 1,
                    first_column: this.yylloc.last_column,
                    last_column: lines ? lines[lines.length - 1].length - 1 : this.yylloc.last_column + match2[0].length
                  };
                  this.yytext += match2[0];
                  this.match += match2[0];
                  this.matches = match2;
                  this.yyleng = this.yytext.length;
                  this._more = false;
                  this._input = this._input.slice(match2[0].length);
                  this.matched += match2[0];
                  token = this.performAction.call(this, this.yy, this, rules[i4], this.conditionStack[this.conditionStack.length - 1]);
                  if (token)
                    return token;
                  else
                    return;
                }
              }
              if (this._input === "") {
                return this.EOF;
              } else {
                this.parseError(
                  "Lexical error on line " + (this.yylineno + 1) + ". Unrecognized text.\n" + this.showPosition(),
                  { text: "", token: null, line: this.yylineno }
                );
              }
            },
            lex: function lex() {
              var r4 = this.next();
              if (typeof r4 !== "undefined") {
                return r4;
              } else {
                return this.lex();
              }
            },
            begin: function begin(condition) {
              this.conditionStack.push(condition);
            },
            popState: function popState() {
              return this.conditionStack.pop();
            },
            _currentRules: function _currentRules() {
              return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
            },
            topState: function() {
              return this.conditionStack[this.conditionStack.length - 2];
            },
            pushState: function begin(condition) {
              this.begin(condition);
            }
          };
          lexer2.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) {
            var YYSTATE = YY_START;
            switch ($avoiding_name_collisions) {
              case 0:
                break;
              case 1:
                return 20;
                break;
              case 2:
                return 19;
                break;
              case 3:
                return 8;
                break;
              case 4:
                return 9;
                break;
              case 5:
                return 6;
                break;
              case 6:
                return 7;
                break;
              case 7:
                return 11;
                break;
              case 8:
                return 13;
                break;
              case 9:
                return 10;
                break;
              case 10:
                return 12;
                break;
              case 11:
                return 14;
                break;
              case 12:
                return 15;
                break;
              case 13:
                return 16;
                break;
              case 14:
                return 17;
                break;
              case 15:
                return 18;
                break;
              case 16:
                return 5;
                break;
              case 17:
                return "INVALID";
                break;
            }
          };
          lexer2.rules = [/^\s+/, /^[0-9]+(\.[0-9]+)?\b/, /^n\b/, /^\|\|/, /^&&/, /^\?/, /^:/, /^<=/, /^>=/, /^</, /^>/, /^!=/, /^==/, /^%/, /^\(/, /^\)/, /^$/, /^./];
          lexer2.conditions = { "INITIAL": { "rules": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17], "inclusive": true } };
          return lexer2;
        }();
        parser.lexer = lexer;
        return parser;
      }();
      if (typeof exports !== "undefined") {
        if (typeof module !== "undefined" && module.exports) {
          exports = module.exports = Jed2;
        }
        exports.Jed = Jed2;
      } else {
        if (typeof define === "function" && define.amd) {
          define(function() {
            return Jed2;
          });
        }
        root["Jed"] = Jed2;
      }
    })(exports);
  }
});

// ../../node_modules/.pnpm/preact-router@3.2.1_preact@10.11.3/node_modules/preact-router/dist/preact-router.js
var require_preact_router = __commonJS({
  "../../node_modules/.pnpm/preact-router@3.2.1_preact@10.11.3/node_modules/preact-router/dist/preact-router.js"(exports, module) {
    !function(t4, e4) {
      "object" == typeof exports && "undefined" != typeof module ? module.exports = e4((init_preact_module(), __toCommonJS(preact_module_exports))) : "function" == typeof define && define.amd ? define(["preact"], e4) : t4.preactRouter = e4(t4.preact);
    }(exports, function(t4) {
      function e4(t5, e5) {
        for (var n4 in e5)
          t5[n4] = e5[n4];
        return t5;
      }
      function n3(t5, e5, n4) {
        var r5, o5 = /(?:\?([^#]*))?(#.*)?$/, u5 = t5.match(o5), a5 = {};
        if (u5 && u5[1])
          for (var p6 = u5[1].split("&"), c5 = 0; c5 < p6.length; c5++) {
            var f5 = p6[c5].split("=");
            a5[decodeURIComponent(f5[0])] = decodeURIComponent(f5.slice(1).join("="));
          }
        t5 = i4(t5.replace(o5, "")), e5 = i4(e5 || "");
        for (var l5 = Math.max(t5.length, e5.length), s5 = 0; s5 < l5; s5++)
          if (e5[s5] && ":" === e5[s5].charAt(0)) {
            var h5 = e5[s5].replace(/(^:|[+*?]+$)/g, ""), d5 = (e5[s5].match(/[+*?]+$/) || C3)[0] || "", g5 = ~d5.indexOf("+"), y5 = ~d5.indexOf("*"), m5 = t5[s5] || "";
            if (!m5 && !y5 && (d5.indexOf("?") < 0 || g5)) {
              r5 = false;
              break;
            }
            if (a5[h5] = decodeURIComponent(m5), g5 || y5) {
              a5[h5] = t5.slice(s5).map(decodeURIComponent).join("/");
              break;
            }
          } else if (e5[s5] !== t5[s5]) {
            r5 = false;
            break;
          }
        return (true === n4.default || false !== r5) && a5;
      }
      function r4(t5, e5) {
        return t5.rank < e5.rank ? 1 : t5.rank > e5.rank ? -1 : t5.index - e5.index;
      }
      function o4(t5, e5) {
        return t5.index = e5, t5.rank = p5(t5), t5.props;
      }
      function i4(t5) {
        return t5.replace(/(^\/+|\/+$)/g, "").split("/");
      }
      function u4(t5) {
        return ":" == t5.charAt(0) ? 1 + "*+?".indexOf(t5.charAt(t5.length - 1)) || 4 : 5;
      }
      function a4(t5) {
        return i4(t5).map(u4).join("");
      }
      function p5(t5) {
        return t5.props.default ? 0 : a4(t5.props.path);
      }
      function c4(t5, e5) {
        void 0 === e5 && (e5 = "push"), b4 && b4[e5] ? b4[e5](t5) : "undefined" != typeof history && history[e5 + "State"] && history[e5 + "State"](null, null, t5);
      }
      function f4() {
        var t5;
        return t5 = b4 && b4.location ? b4.location : b4 && b4.getCurrentLocation ? b4.getCurrentLocation() : "undefined" != typeof location ? location : x3, "" + (t5.pathname || "") + (t5.search || "");
      }
      function l4(t5, e5) {
        return void 0 === e5 && (e5 = false), "string" != typeof t5 && t5.url && (e5 = t5.replace, t5 = t5.url), s4(t5) && c4(t5, e5 ? "replace" : "push"), h4(t5);
      }
      function s4(t5) {
        for (var e5 = U2.length; e5--; )
          if (U2[e5].canRoute(t5))
            return true;
        return false;
      }
      function h4(t5) {
        for (var e5 = false, n4 = 0; n4 < U2.length; n4++)
          true === U2[n4].routeTo(t5) && (e5 = true);
        for (var r5 = k4.length; r5--; )
          k4[r5](t5);
        return e5;
      }
      function d4(t5) {
        if (t5 && t5.getAttribute) {
          var e5 = t5.getAttribute("href"), n4 = t5.getAttribute("target");
          if (e5 && e5.match(/^\//g) && (!n4 || n4.match(/^_?self$/i)))
            return l4(e5);
        }
      }
      function g4(t5) {
        if (!(t5.ctrlKey || t5.metaKey || t5.altKey || t5.shiftKey || 0 !== t5.button))
          return d4(t5.currentTarget || t5.target || this), y4(t5);
      }
      function y4(t5) {
        return t5 && (t5.stopImmediatePropagation && t5.stopImmediatePropagation(), t5.stopPropagation && t5.stopPropagation(), t5.preventDefault()), false;
      }
      function m4(t5) {
        if (!(t5.ctrlKey || t5.metaKey || t5.altKey || t5.shiftKey || 0 !== t5.button)) {
          var e5 = t5.target;
          do {
            if ("A" === (e5.nodeName + "").toUpperCase() && e5.getAttribute("href")) {
              if (e5.hasAttribute("native"))
                return;
              if (d4(e5))
                return y4(t5);
            }
          } while (e5 = e5.parentNode);
        }
      }
      function v4() {
        A4 || ("function" == typeof addEventListener && (b4 || addEventListener("popstate", function() {
          h4(f4());
        }), addEventListener("click", m4)), A4 = true);
      }
      var C3 = {}, b4 = null, U2 = [], k4 = [], x3 = {}, A4 = false, R2 = function(i5) {
        function u5(t5) {
          i5.call(this, t5), t5.history && (b4 = t5.history), this.state = { url: t5.url || f4() }, v4();
        }
        return i5 && (u5.__proto__ = i5), u5.prototype = Object.create(i5 && i5.prototype), u5.prototype.constructor = u5, u5.prototype.shouldComponentUpdate = function(t5) {
          return true !== t5.static || (t5.url !== this.props.url || t5.onChange !== this.props.onChange);
        }, u5.prototype.canRoute = function(e5) {
          return this.getMatchingChildren(t4.toChildArray(this.props.children), e5, false).length > 0;
        }, u5.prototype.routeTo = function(t5) {
          this.setState({ url: t5 });
          var e5 = this.canRoute(t5);
          return this.updating || this.forceUpdate(), e5;
        }, u5.prototype.componentWillMount = function() {
          U2.push(this), this.updating = true;
        }, u5.prototype.componentDidMount = function() {
          var t5 = this;
          b4 && (this.unlisten = b4.listen(function(e5) {
            t5.routeTo("" + (e5.pathname || "") + (e5.search || ""));
          })), this.updating = false;
        }, u5.prototype.componentWillUnmount = function() {
          "function" == typeof this.unlisten && this.unlisten(), U2.splice(U2.indexOf(this), 1);
        }, u5.prototype.componentWillUpdate = function() {
          this.updating = true;
        }, u5.prototype.componentDidUpdate = function() {
          this.updating = false;
        }, u5.prototype.getMatchingChildren = function(i6, u6, a5) {
          return i6.filter(o4).sort(r4).map(function(r5) {
            var o5 = n3(u6, r5.props.path, r5.props);
            if (o5) {
              if (false !== a5) {
                var i7 = { url: u6, matches: o5 };
                return e4(i7, o5), delete i7.ref, delete i7.key, t4.cloneElement(r5, i7);
              }
              return r5;
            }
          }).filter(Boolean);
        }, u5.prototype.render = function(e5, n4) {
          var r5 = e5.children, o5 = e5.onChange, i6 = n4.url, u6 = this.getMatchingChildren(t4.toChildArray(r5), i6, true), a5 = u6[0] || null, p6 = this.previousUrl;
          return i6 !== p6 && (this.previousUrl = i6, "function" == typeof o5 && o5({ router: this, url: i6, previous: p6, active: u6, current: a5 })), a5;
        }, u5;
      }(t4.Component), K4 = function(n4) {
        return t4.createElement("a", e4({ onClick: g4 }, n4));
      }, E2 = function(e5) {
        return t4.createElement(e5.component, e5);
      };
      return R2.subscribers = k4, R2.getCurrentUrl = f4, R2.route = l4, R2.Router = R2, R2.Route = E2, R2.Link = K4, R2.exec = n3, R2;
    });
  }
});

// ../../node_modules/.pnpm/preact-router@3.2.1_preact@10.11.3/node_modules/preact-router/match.js
var require_match = __commonJS({
  "../../node_modules/.pnpm/preact-router@3.2.1_preact@10.11.3/node_modules/preact-router/match.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.Link = exports.Match = void 0;
    var _extends = Object.assign || function(target) {
      for (var i4 = 1; i4 < arguments.length; i4++) {
        var source = arguments[i4];
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
      return target;
    };
    var _preact = (init_preact_module(), __toCommonJS(preact_module_exports));
    var _preactRouter = require_preact_router();
    function _objectWithoutProperties(obj, keys) {
      var target = {};
      for (var i4 in obj) {
        if (keys.indexOf(i4) >= 0)
          continue;
        if (!Object.prototype.hasOwnProperty.call(obj, i4))
          continue;
        target[i4] = obj[i4];
      }
      return target;
    }
    function _classCallCheck(instance, Constructor) {
      if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
      }
    }
    function _possibleConstructorReturn(self2, call) {
      if (!self2) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
      }
      return call && (typeof call === "object" || typeof call === "function") ? call : self2;
    }
    function _inherits(subClass, superClass) {
      if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
      }
      subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });
      if (superClass)
        Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
    }
    var Match2 = exports.Match = function(_Component) {
      _inherits(Match3, _Component);
      function Match3() {
        var _temp, _this, _ret;
        _classCallCheck(this, Match3);
        for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.update = function(url) {
          _this.nextUrl = url;
          _this.setState({});
        }, _temp), _possibleConstructorReturn(_this, _ret);
      }
      Match3.prototype.componentDidMount = function componentDidMount() {
        _preactRouter.subscribers.push(this.update);
      };
      Match3.prototype.componentWillUnmount = function componentWillUnmount() {
        _preactRouter.subscribers.splice(_preactRouter.subscribers.indexOf(this.update) >>> 0, 1);
      };
      Match3.prototype.render = function render(props) {
        var url = this.nextUrl || (0, _preactRouter.getCurrentUrl)(), path = url.replace(/\?.+$/, "");
        this.nextUrl = null;
        return props.children({
          url,
          path,
          matches: (0, _preactRouter.exec)(path, props.path, {}) !== false
        });
      };
      return Match3;
    }(_preact.Component);
    var Link = function Link2(_ref) {
      var activeClassName = _ref.activeClassName, path = _ref.path, props = _objectWithoutProperties(_ref, ["activeClassName", "path"]);
      return (0, _preact.h)(
        Match2,
        { path: path || props.href },
        function(_ref2) {
          var matches = _ref2.matches;
          return (0, _preact.h)(_preactRouter.Link, _extends({}, props, { "class": [props.class || props.className, matches && activeClassName].filter(Boolean).join(" ") }));
        }
      );
    };
    exports.Link = Link;
    exports.default = Match2;
    Match2.Link = Link;
  }
});

// ../../node_modules/.pnpm/qrcode-generator@1.4.4/node_modules/qrcode-generator/qrcode.js
var require_qrcode = __commonJS({
  "../../node_modules/.pnpm/qrcode-generator@1.4.4/node_modules/qrcode-generator/qrcode.js"(exports, module) {
    var qrcode2 = function() {
      var qrcode3 = function(typeNumber, errorCorrectionLevel) {
        var PAD0 = 236;
        var PAD1 = 17;
        var _typeNumber = typeNumber;
        var _errorCorrectionLevel = QRErrorCorrectionLevel[errorCorrectionLevel];
        var _modules = null;
        var _moduleCount = 0;
        var _dataCache = null;
        var _dataList = [];
        var _this = {};
        var makeImpl = function(test, maskPattern) {
          _moduleCount = _typeNumber * 4 + 17;
          _modules = function(moduleCount) {
            var modules = new Array(moduleCount);
            for (var row = 0; row < moduleCount; row += 1) {
              modules[row] = new Array(moduleCount);
              for (var col = 0; col < moduleCount; col += 1) {
                modules[row][col] = null;
              }
            }
            return modules;
          }(_moduleCount);
          setupPositionProbePattern(0, 0);
          setupPositionProbePattern(_moduleCount - 7, 0);
          setupPositionProbePattern(0, _moduleCount - 7);
          setupPositionAdjustPattern();
          setupTimingPattern();
          setupTypeInfo(test, maskPattern);
          if (_typeNumber >= 7) {
            setupTypeNumber(test);
          }
          if (_dataCache == null) {
            _dataCache = createData(_typeNumber, _errorCorrectionLevel, _dataList);
          }
          mapData(_dataCache, maskPattern);
        };
        var setupPositionProbePattern = function(row, col) {
          for (var r4 = -1; r4 <= 7; r4 += 1) {
            if (row + r4 <= -1 || _moduleCount <= row + r4)
              continue;
            for (var c4 = -1; c4 <= 7; c4 += 1) {
              if (col + c4 <= -1 || _moduleCount <= col + c4)
                continue;
              if (0 <= r4 && r4 <= 6 && (c4 == 0 || c4 == 6) || 0 <= c4 && c4 <= 6 && (r4 == 0 || r4 == 6) || 2 <= r4 && r4 <= 4 && 2 <= c4 && c4 <= 4) {
                _modules[row + r4][col + c4] = true;
              } else {
                _modules[row + r4][col + c4] = false;
              }
            }
          }
        };
        var getBestMaskPattern = function() {
          var minLostPoint = 0;
          var pattern = 0;
          for (var i4 = 0; i4 < 8; i4 += 1) {
            makeImpl(true, i4);
            var lostPoint = QRUtil.getLostPoint(_this);
            if (i4 == 0 || minLostPoint > lostPoint) {
              minLostPoint = lostPoint;
              pattern = i4;
            }
          }
          return pattern;
        };
        var setupTimingPattern = function() {
          for (var r4 = 8; r4 < _moduleCount - 8; r4 += 1) {
            if (_modules[r4][6] != null) {
              continue;
            }
            _modules[r4][6] = r4 % 2 == 0;
          }
          for (var c4 = 8; c4 < _moduleCount - 8; c4 += 1) {
            if (_modules[6][c4] != null) {
              continue;
            }
            _modules[6][c4] = c4 % 2 == 0;
          }
        };
        var setupPositionAdjustPattern = function() {
          var pos = QRUtil.getPatternPosition(_typeNumber);
          for (var i4 = 0; i4 < pos.length; i4 += 1) {
            for (var j4 = 0; j4 < pos.length; j4 += 1) {
              var row = pos[i4];
              var col = pos[j4];
              if (_modules[row][col] != null) {
                continue;
              }
              for (var r4 = -2; r4 <= 2; r4 += 1) {
                for (var c4 = -2; c4 <= 2; c4 += 1) {
                  if (r4 == -2 || r4 == 2 || c4 == -2 || c4 == 2 || r4 == 0 && c4 == 0) {
                    _modules[row + r4][col + c4] = true;
                  } else {
                    _modules[row + r4][col + c4] = false;
                  }
                }
              }
            }
          }
        };
        var setupTypeNumber = function(test) {
          var bits2 = QRUtil.getBCHTypeNumber(_typeNumber);
          for (var i4 = 0; i4 < 18; i4 += 1) {
            var mod = !test && (bits2 >> i4 & 1) == 1;
            _modules[Math.floor(i4 / 3)][i4 % 3 + _moduleCount - 8 - 3] = mod;
          }
          for (var i4 = 0; i4 < 18; i4 += 1) {
            var mod = !test && (bits2 >> i4 & 1) == 1;
            _modules[i4 % 3 + _moduleCount - 8 - 3][Math.floor(i4 / 3)] = mod;
          }
        };
        var setupTypeInfo = function(test, maskPattern) {
          var data = _errorCorrectionLevel << 3 | maskPattern;
          var bits2 = QRUtil.getBCHTypeInfo(data);
          for (var i4 = 0; i4 < 15; i4 += 1) {
            var mod = !test && (bits2 >> i4 & 1) == 1;
            if (i4 < 6) {
              _modules[i4][8] = mod;
            } else if (i4 < 8) {
              _modules[i4 + 1][8] = mod;
            } else {
              _modules[_moduleCount - 15 + i4][8] = mod;
            }
          }
          for (var i4 = 0; i4 < 15; i4 += 1) {
            var mod = !test && (bits2 >> i4 & 1) == 1;
            if (i4 < 8) {
              _modules[8][_moduleCount - i4 - 1] = mod;
            } else if (i4 < 9) {
              _modules[8][15 - i4 - 1 + 1] = mod;
            } else {
              _modules[8][15 - i4 - 1] = mod;
            }
          }
          _modules[_moduleCount - 8][8] = !test;
        };
        var mapData = function(data, maskPattern) {
          var inc = -1;
          var row = _moduleCount - 1;
          var bitIndex = 7;
          var byteIndex = 0;
          var maskFunc = QRUtil.getMaskFunction(maskPattern);
          for (var col = _moduleCount - 1; col > 0; col -= 2) {
            if (col == 6)
              col -= 1;
            while (true) {
              for (var c4 = 0; c4 < 2; c4 += 1) {
                if (_modules[row][col - c4] == null) {
                  var dark = false;
                  if (byteIndex < data.length) {
                    dark = (data[byteIndex] >>> bitIndex & 1) == 1;
                  }
                  var mask = maskFunc(row, col - c4);
                  if (mask) {
                    dark = !dark;
                  }
                  _modules[row][col - c4] = dark;
                  bitIndex -= 1;
                  if (bitIndex == -1) {
                    byteIndex += 1;
                    bitIndex = 7;
                  }
                }
              }
              row += inc;
              if (row < 0 || _moduleCount <= row) {
                row -= inc;
                inc = -inc;
                break;
              }
            }
          }
        };
        var createBytes = function(buffer, rsBlocks) {
          var offset = 0;
          var maxDcCount = 0;
          var maxEcCount = 0;
          var dcdata = new Array(rsBlocks.length);
          var ecdata = new Array(rsBlocks.length);
          for (var r4 = 0; r4 < rsBlocks.length; r4 += 1) {
            var dcCount = rsBlocks[r4].dataCount;
            var ecCount = rsBlocks[r4].totalCount - dcCount;
            maxDcCount = Math.max(maxDcCount, dcCount);
            maxEcCount = Math.max(maxEcCount, ecCount);
            dcdata[r4] = new Array(dcCount);
            for (var i4 = 0; i4 < dcdata[r4].length; i4 += 1) {
              dcdata[r4][i4] = 255 & buffer.getBuffer()[i4 + offset];
            }
            offset += dcCount;
            var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
            var rawPoly = qrPolynomial(dcdata[r4], rsPoly.getLength() - 1);
            var modPoly = rawPoly.mod(rsPoly);
            ecdata[r4] = new Array(rsPoly.getLength() - 1);
            for (var i4 = 0; i4 < ecdata[r4].length; i4 += 1) {
              var modIndex = i4 + modPoly.getLength() - ecdata[r4].length;
              ecdata[r4][i4] = modIndex >= 0 ? modPoly.getAt(modIndex) : 0;
            }
          }
          var totalCodeCount = 0;
          for (var i4 = 0; i4 < rsBlocks.length; i4 += 1) {
            totalCodeCount += rsBlocks[i4].totalCount;
          }
          var data = new Array(totalCodeCount);
          var index = 0;
          for (var i4 = 0; i4 < maxDcCount; i4 += 1) {
            for (var r4 = 0; r4 < rsBlocks.length; r4 += 1) {
              if (i4 < dcdata[r4].length) {
                data[index] = dcdata[r4][i4];
                index += 1;
              }
            }
          }
          for (var i4 = 0; i4 < maxEcCount; i4 += 1) {
            for (var r4 = 0; r4 < rsBlocks.length; r4 += 1) {
              if (i4 < ecdata[r4].length) {
                data[index] = ecdata[r4][i4];
                index += 1;
              }
            }
          }
          return data;
        };
        var createData = function(typeNumber2, errorCorrectionLevel2, dataList) {
          var rsBlocks = QRRSBlock.getRSBlocks(typeNumber2, errorCorrectionLevel2);
          var buffer = qrBitBuffer();
          for (var i4 = 0; i4 < dataList.length; i4 += 1) {
            var data = dataList[i4];
            buffer.put(data.getMode(), 4);
            buffer.put(data.getLength(), QRUtil.getLengthInBits(data.getMode(), typeNumber2));
            data.write(buffer);
          }
          var totalDataCount = 0;
          for (var i4 = 0; i4 < rsBlocks.length; i4 += 1) {
            totalDataCount += rsBlocks[i4].dataCount;
          }
          if (buffer.getLengthInBits() > totalDataCount * 8) {
            throw "code length overflow. (" + buffer.getLengthInBits() + ">" + totalDataCount * 8 + ")";
          }
          if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) {
            buffer.put(0, 4);
          }
          while (buffer.getLengthInBits() % 8 != 0) {
            buffer.putBit(false);
          }
          while (true) {
            if (buffer.getLengthInBits() >= totalDataCount * 8) {
              break;
            }
            buffer.put(PAD0, 8);
            if (buffer.getLengthInBits() >= totalDataCount * 8) {
              break;
            }
            buffer.put(PAD1, 8);
          }
          return createBytes(buffer, rsBlocks);
        };
        _this.addData = function(data, mode) {
          mode = mode || "Byte";
          var newData = null;
          switch (mode) {
            case "Numeric":
              newData = qrNumber(data);
              break;
            case "Alphanumeric":
              newData = qrAlphaNum(data);
              break;
            case "Byte":
              newData = qr8BitByte(data);
              break;
            case "Kanji":
              newData = qrKanji(data);
              break;
            default:
              throw "mode:" + mode;
          }
          _dataList.push(newData);
          _dataCache = null;
        };
        _this.isDark = function(row, col) {
          if (row < 0 || _moduleCount <= row || col < 0 || _moduleCount <= col) {
            throw row + "," + col;
          }
          return _modules[row][col];
        };
        _this.getModuleCount = function() {
          return _moduleCount;
        };
        _this.make = function() {
          if (_typeNumber < 1) {
            var typeNumber2 = 1;
            for (; typeNumber2 < 40; typeNumber2++) {
              var rsBlocks = QRRSBlock.getRSBlocks(typeNumber2, _errorCorrectionLevel);
              var buffer = qrBitBuffer();
              for (var i4 = 0; i4 < _dataList.length; i4++) {
                var data = _dataList[i4];
                buffer.put(data.getMode(), 4);
                buffer.put(data.getLength(), QRUtil.getLengthInBits(data.getMode(), typeNumber2));
                data.write(buffer);
              }
              var totalDataCount = 0;
              for (var i4 = 0; i4 < rsBlocks.length; i4++) {
                totalDataCount += rsBlocks[i4].dataCount;
              }
              if (buffer.getLengthInBits() <= totalDataCount * 8) {
                break;
              }
            }
            _typeNumber = typeNumber2;
          }
          makeImpl(false, getBestMaskPattern());
        };
        _this.createTableTag = function(cellSize, margin) {
          cellSize = cellSize || 2;
          margin = typeof margin == "undefined" ? cellSize * 4 : margin;
          var qrHtml = "";
          qrHtml += '<table style="';
          qrHtml += " border-width: 0px; border-style: none;";
          qrHtml += " border-collapse: collapse;";
          qrHtml += " padding: 0px; margin: " + margin + "px;";
          qrHtml += '">';
          qrHtml += "<tbody>";
          for (var r4 = 0; r4 < _this.getModuleCount(); r4 += 1) {
            qrHtml += "<tr>";
            for (var c4 = 0; c4 < _this.getModuleCount(); c4 += 1) {
              qrHtml += '<td style="';
              qrHtml += " border-width: 0px; border-style: none;";
              qrHtml += " border-collapse: collapse;";
              qrHtml += " padding: 0px; margin: 0px;";
              qrHtml += " width: " + cellSize + "px;";
              qrHtml += " height: " + cellSize + "px;";
              qrHtml += " background-color: ";
              qrHtml += _this.isDark(r4, c4) ? "#000000" : "#ffffff";
              qrHtml += ";";
              qrHtml += '"/>';
            }
            qrHtml += "</tr>";
          }
          qrHtml += "</tbody>";
          qrHtml += "</table>";
          return qrHtml;
        };
        _this.createSvgTag = function(cellSize, margin, alt, title) {
          var opts = {};
          if (typeof arguments[0] == "object") {
            opts = arguments[0];
            cellSize = opts.cellSize;
            margin = opts.margin;
            alt = opts.alt;
            title = opts.title;
          }
          cellSize = cellSize || 2;
          margin = typeof margin == "undefined" ? cellSize * 4 : margin;
          alt = typeof alt === "string" ? { text: alt } : alt || {};
          alt.text = alt.text || null;
          alt.id = alt.text ? alt.id || "qrcode-description" : null;
          title = typeof title === "string" ? { text: title } : title || {};
          title.text = title.text || null;
          title.id = title.text ? title.id || "qrcode-title" : null;
          var size = _this.getModuleCount() * cellSize + margin * 2;
          var c4, mc, r4, mr, qrSvg = "", rect;
          rect = "l" + cellSize + ",0 0," + cellSize + " -" + cellSize + ",0 0,-" + cellSize + "z ";
          qrSvg += '<svg version="1.1" xmlns="http://www.w3.org/2000/svg"';
          qrSvg += !opts.scalable ? ' width="' + size + 'px" height="' + size + 'px"' : "";
          qrSvg += ' viewBox="0 0 ' + size + " " + size + '" ';
          qrSvg += ' preserveAspectRatio="xMinYMin meet"';
          qrSvg += title.text || alt.text ? ' role="img" aria-labelledby="' + escapeXml([title.id, alt.id].join(" ").trim()) + '"' : "";
          qrSvg += ">";
          qrSvg += title.text ? '<title id="' + escapeXml(title.id) + '">' + escapeXml(title.text) + "</title>" : "";
          qrSvg += alt.text ? '<description id="' + escapeXml(alt.id) + '">' + escapeXml(alt.text) + "</description>" : "";
          qrSvg += '<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>';
          qrSvg += '<path d="';
          for (r4 = 0; r4 < _this.getModuleCount(); r4 += 1) {
            mr = r4 * cellSize + margin;
            for (c4 = 0; c4 < _this.getModuleCount(); c4 += 1) {
              if (_this.isDark(r4, c4)) {
                mc = c4 * cellSize + margin;
                qrSvg += "M" + mc + "," + mr + rect;
              }
            }
          }
          qrSvg += '" stroke="transparent" fill="black"/>';
          qrSvg += "</svg>";
          return qrSvg;
        };
        _this.createDataURL = function(cellSize, margin) {
          cellSize = cellSize || 2;
          margin = typeof margin == "undefined" ? cellSize * 4 : margin;
          var size = _this.getModuleCount() * cellSize + margin * 2;
          var min = margin;
          var max2 = size - margin;
          return createDataURL(size, size, function(x3, y4) {
            if (min <= x3 && x3 < max2 && min <= y4 && y4 < max2) {
              var c4 = Math.floor((x3 - min) / cellSize);
              var r4 = Math.floor((y4 - min) / cellSize);
              return _this.isDark(r4, c4) ? 0 : 1;
            } else {
              return 1;
            }
          });
        };
        _this.createImgTag = function(cellSize, margin, alt) {
          cellSize = cellSize || 2;
          margin = typeof margin == "undefined" ? cellSize * 4 : margin;
          var size = _this.getModuleCount() * cellSize + margin * 2;
          var img = "";
          img += "<img";
          img += ' src="';
          img += _this.createDataURL(cellSize, margin);
          img += '"';
          img += ' width="';
          img += size;
          img += '"';
          img += ' height="';
          img += size;
          img += '"';
          if (alt) {
            img += ' alt="';
            img += escapeXml(alt);
            img += '"';
          }
          img += "/>";
          return img;
        };
        var escapeXml = function(s4) {
          var escaped = "";
          for (var i4 = 0; i4 < s4.length; i4 += 1) {
            var c4 = s4.charAt(i4);
            switch (c4) {
              case "<":
                escaped += "&lt;";
                break;
              case ">":
                escaped += "&gt;";
                break;
              case "&":
                escaped += "&amp;";
                break;
              case '"':
                escaped += "&quot;";
                break;
              default:
                escaped += c4;
                break;
            }
          }
          return escaped;
        };
        var _createHalfASCII = function(margin) {
          var cellSize = 1;
          margin = typeof margin == "undefined" ? cellSize * 2 : margin;
          var size = _this.getModuleCount() * cellSize + margin * 2;
          var min = margin;
          var max2 = size - margin;
          var y4, x3, r1, r22, p5;
          var blocks = {
            "\u2588\u2588": "\u2588",
            "\u2588 ": "\u2580",
            " \u2588": "\u2584",
            "  ": " "
          };
          var blocksLastLineNoMargin = {
            "\u2588\u2588": "\u2580",
            "\u2588 ": "\u2580",
            " \u2588": " ",
            "  ": " "
          };
          var ascii = "";
          for (y4 = 0; y4 < size; y4 += 2) {
            r1 = Math.floor((y4 - min) / cellSize);
            r22 = Math.floor((y4 + 1 - min) / cellSize);
            for (x3 = 0; x3 < size; x3 += 1) {
              p5 = "\u2588";
              if (min <= x3 && x3 < max2 && min <= y4 && y4 < max2 && _this.isDark(r1, Math.floor((x3 - min) / cellSize))) {
                p5 = " ";
              }
              if (min <= x3 && x3 < max2 && min <= y4 + 1 && y4 + 1 < max2 && _this.isDark(r22, Math.floor((x3 - min) / cellSize))) {
                p5 += " ";
              } else {
                p5 += "\u2588";
              }
              ascii += margin < 1 && y4 + 1 >= max2 ? blocksLastLineNoMargin[p5] : blocks[p5];
            }
            ascii += "\n";
          }
          if (size % 2 && margin > 0) {
            return ascii.substring(0, ascii.length - size - 1) + Array(size + 1).join("\u2580");
          }
          return ascii.substring(0, ascii.length - 1);
        };
        _this.createASCII = function(cellSize, margin) {
          cellSize = cellSize || 1;
          if (cellSize < 2) {
            return _createHalfASCII(margin);
          }
          cellSize -= 1;
          margin = typeof margin == "undefined" ? cellSize * 2 : margin;
          var size = _this.getModuleCount() * cellSize + margin * 2;
          var min = margin;
          var max2 = size - margin;
          var y4, x3, r4, p5;
          var white = Array(cellSize + 1).join("\u2588\u2588");
          var black = Array(cellSize + 1).join("  ");
          var ascii = "";
          var line = "";
          for (y4 = 0; y4 < size; y4 += 1) {
            r4 = Math.floor((y4 - min) / cellSize);
            line = "";
            for (x3 = 0; x3 < size; x3 += 1) {
              p5 = 1;
              if (min <= x3 && x3 < max2 && min <= y4 && y4 < max2 && _this.isDark(r4, Math.floor((x3 - min) / cellSize))) {
                p5 = 0;
              }
              line += p5 ? white : black;
            }
            for (r4 = 0; r4 < cellSize; r4 += 1) {
              ascii += line + "\n";
            }
          }
          return ascii.substring(0, ascii.length - 1);
        };
        _this.renderTo2dContext = function(context, cellSize) {
          cellSize = cellSize || 2;
          var length = _this.getModuleCount();
          for (var row = 0; row < length; row++) {
            for (var col = 0; col < length; col++) {
              context.fillStyle = _this.isDark(row, col) ? "black" : "white";
              context.fillRect(row * cellSize, col * cellSize, cellSize, cellSize);
            }
          }
        };
        return _this;
      };
      qrcode3.stringToBytesFuncs = {
        "default": function(s4) {
          var bytes = [];
          for (var i4 = 0; i4 < s4.length; i4 += 1) {
            var c4 = s4.charCodeAt(i4);
            bytes.push(c4 & 255);
          }
          return bytes;
        }
      };
      qrcode3.stringToBytes = qrcode3.stringToBytesFuncs["default"];
      qrcode3.createStringToBytes = function(unicodeData, numChars) {
        var unicodeMap = function() {
          var bin = base64DecodeInputStream(unicodeData);
          var read = function() {
            var b4 = bin.read();
            if (b4 == -1)
              throw "eof";
            return b4;
          };
          var count = 0;
          var unicodeMap2 = {};
          while (true) {
            var b0 = bin.read();
            if (b0 == -1)
              break;
            var b1 = read();
            var b22 = read();
            var b32 = read();
            var k4 = String.fromCharCode(b0 << 8 | b1);
            var v4 = b22 << 8 | b32;
            unicodeMap2[k4] = v4;
            count += 1;
          }
          if (count != numChars) {
            throw count + " != " + numChars;
          }
          return unicodeMap2;
        }();
        var unknownChar = "?".charCodeAt(0);
        return function(s4) {
          var bytes = [];
          for (var i4 = 0; i4 < s4.length; i4 += 1) {
            var c4 = s4.charCodeAt(i4);
            if (c4 < 128) {
              bytes.push(c4);
            } else {
              var b4 = unicodeMap[s4.charAt(i4)];
              if (typeof b4 == "number") {
                if ((b4 & 255) == b4) {
                  bytes.push(b4);
                } else {
                  bytes.push(b4 >>> 8);
                  bytes.push(b4 & 255);
                }
              } else {
                bytes.push(unknownChar);
              }
            }
          }
          return bytes;
        };
      };
      var QRMode = {
        MODE_NUMBER: 1 << 0,
        MODE_ALPHA_NUM: 1 << 1,
        MODE_8BIT_BYTE: 1 << 2,
        MODE_KANJI: 1 << 3
      };
      var QRErrorCorrectionLevel = {
        L: 1,
        M: 0,
        Q: 3,
        H: 2
      };
      var QRMaskPattern = {
        PATTERN000: 0,
        PATTERN001: 1,
        PATTERN010: 2,
        PATTERN011: 3,
        PATTERN100: 4,
        PATTERN101: 5,
        PATTERN110: 6,
        PATTERN111: 7
      };
      var QRUtil = function() {
        var PATTERN_POSITION_TABLE = [
          [],
          [6, 18],
          [6, 22],
          [6, 26],
          [6, 30],
          [6, 34],
          [6, 22, 38],
          [6, 24, 42],
          [6, 26, 46],
          [6, 28, 50],
          [6, 30, 54],
          [6, 32, 58],
          [6, 34, 62],
          [6, 26, 46, 66],
          [6, 26, 48, 70],
          [6, 26, 50, 74],
          [6, 30, 54, 78],
          [6, 30, 56, 82],
          [6, 30, 58, 86],
          [6, 34, 62, 90],
          [6, 28, 50, 72, 94],
          [6, 26, 50, 74, 98],
          [6, 30, 54, 78, 102],
          [6, 28, 54, 80, 106],
          [6, 32, 58, 84, 110],
          [6, 30, 58, 86, 114],
          [6, 34, 62, 90, 118],
          [6, 26, 50, 74, 98, 122],
          [6, 30, 54, 78, 102, 126],
          [6, 26, 52, 78, 104, 130],
          [6, 30, 56, 82, 108, 134],
          [6, 34, 60, 86, 112, 138],
          [6, 30, 58, 86, 114, 142],
          [6, 34, 62, 90, 118, 146],
          [6, 30, 54, 78, 102, 126, 150],
          [6, 24, 50, 76, 102, 128, 154],
          [6, 28, 54, 80, 106, 132, 158],
          [6, 32, 58, 84, 110, 136, 162],
          [6, 26, 54, 82, 110, 138, 166],
          [6, 30, 58, 86, 114, 142, 170]
        ];
        var G15 = 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0;
        var G18 = 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0;
        var G15_MASK = 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1;
        var _this = {};
        var getBCHDigit = function(data) {
          var digit2 = 0;
          while (data != 0) {
            digit2 += 1;
            data >>>= 1;
          }
          return digit2;
        };
        _this.getBCHTypeInfo = function(data) {
          var d4 = data << 10;
          while (getBCHDigit(d4) - getBCHDigit(G15) >= 0) {
            d4 ^= G15 << getBCHDigit(d4) - getBCHDigit(G15);
          }
          return (data << 10 | d4) ^ G15_MASK;
        };
        _this.getBCHTypeNumber = function(data) {
          var d4 = data << 12;
          while (getBCHDigit(d4) - getBCHDigit(G18) >= 0) {
            d4 ^= G18 << getBCHDigit(d4) - getBCHDigit(G18);
          }
          return data << 12 | d4;
        };
        _this.getPatternPosition = function(typeNumber) {
          return PATTERN_POSITION_TABLE[typeNumber - 1];
        };
        _this.getMaskFunction = function(maskPattern) {
          switch (maskPattern) {
            case QRMaskPattern.PATTERN000:
              return function(i4, j4) {
                return (i4 + j4) % 2 == 0;
              };
            case QRMaskPattern.PATTERN001:
              return function(i4, j4) {
                return i4 % 2 == 0;
              };
            case QRMaskPattern.PATTERN010:
              return function(i4, j4) {
                return j4 % 3 == 0;
              };
            case QRMaskPattern.PATTERN011:
              return function(i4, j4) {
                return (i4 + j4) % 3 == 0;
              };
            case QRMaskPattern.PATTERN100:
              return function(i4, j4) {
                return (Math.floor(i4 / 2) + Math.floor(j4 / 3)) % 2 == 0;
              };
            case QRMaskPattern.PATTERN101:
              return function(i4, j4) {
                return i4 * j4 % 2 + i4 * j4 % 3 == 0;
              };
            case QRMaskPattern.PATTERN110:
              return function(i4, j4) {
                return (i4 * j4 % 2 + i4 * j4 % 3) % 2 == 0;
              };
            case QRMaskPattern.PATTERN111:
              return function(i4, j4) {
                return (i4 * j4 % 3 + (i4 + j4) % 2) % 2 == 0;
              };
            default:
              throw "bad maskPattern:" + maskPattern;
          }
        };
        _this.getErrorCorrectPolynomial = function(errorCorrectLength) {
          var a4 = qrPolynomial([1], 0);
          for (var i4 = 0; i4 < errorCorrectLength; i4 += 1) {
            a4 = a4.multiply(qrPolynomial([1, QRMath.gexp(i4)], 0));
          }
          return a4;
        };
        _this.getLengthInBits = function(mode, type) {
          if (1 <= type && type < 10) {
            switch (mode) {
              case QRMode.MODE_NUMBER:
                return 10;
              case QRMode.MODE_ALPHA_NUM:
                return 9;
              case QRMode.MODE_8BIT_BYTE:
                return 8;
              case QRMode.MODE_KANJI:
                return 8;
              default:
                throw "mode:" + mode;
            }
          } else if (type < 27) {
            switch (mode) {
              case QRMode.MODE_NUMBER:
                return 12;
              case QRMode.MODE_ALPHA_NUM:
                return 11;
              case QRMode.MODE_8BIT_BYTE:
                return 16;
              case QRMode.MODE_KANJI:
                return 10;
              default:
                throw "mode:" + mode;
            }
          } else if (type < 41) {
            switch (mode) {
              case QRMode.MODE_NUMBER:
                return 14;
              case QRMode.MODE_ALPHA_NUM:
                return 13;
              case QRMode.MODE_8BIT_BYTE:
                return 16;
              case QRMode.MODE_KANJI:
                return 12;
              default:
                throw "mode:" + mode;
            }
          } else {
            throw "type:" + type;
          }
        };
        _this.getLostPoint = function(qrcode4) {
          var moduleCount = qrcode4.getModuleCount();
          var lostPoint = 0;
          for (var row = 0; row < moduleCount; row += 1) {
            for (var col = 0; col < moduleCount; col += 1) {
              var sameCount = 0;
              var dark = qrcode4.isDark(row, col);
              for (var r4 = -1; r4 <= 1; r4 += 1) {
                if (row + r4 < 0 || moduleCount <= row + r4) {
                  continue;
                }
                for (var c4 = -1; c4 <= 1; c4 += 1) {
                  if (col + c4 < 0 || moduleCount <= col + c4) {
                    continue;
                  }
                  if (r4 == 0 && c4 == 0) {
                    continue;
                  }
                  if (dark == qrcode4.isDark(row + r4, col + c4)) {
                    sameCount += 1;
                  }
                }
              }
              if (sameCount > 5) {
                lostPoint += 3 + sameCount - 5;
              }
            }
          }
          ;
          for (var row = 0; row < moduleCount - 1; row += 1) {
            for (var col = 0; col < moduleCount - 1; col += 1) {
              var count = 0;
              if (qrcode4.isDark(row, col))
                count += 1;
              if (qrcode4.isDark(row + 1, col))
                count += 1;
              if (qrcode4.isDark(row, col + 1))
                count += 1;
              if (qrcode4.isDark(row + 1, col + 1))
                count += 1;
              if (count == 0 || count == 4) {
                lostPoint += 3;
              }
            }
          }
          for (var row = 0; row < moduleCount; row += 1) {
            for (var col = 0; col < moduleCount - 6; col += 1) {
              if (qrcode4.isDark(row, col) && !qrcode4.isDark(row, col + 1) && qrcode4.isDark(row, col + 2) && qrcode4.isDark(row, col + 3) && qrcode4.isDark(row, col + 4) && !qrcode4.isDark(row, col + 5) && qrcode4.isDark(row, col + 6)) {
                lostPoint += 40;
              }
            }
          }
          for (var col = 0; col < moduleCount; col += 1) {
            for (var row = 0; row < moduleCount - 6; row += 1) {
              if (qrcode4.isDark(row, col) && !qrcode4.isDark(row + 1, col) && qrcode4.isDark(row + 2, col) && qrcode4.isDark(row + 3, col) && qrcode4.isDark(row + 4, col) && !qrcode4.isDark(row + 5, col) && qrcode4.isDark(row + 6, col)) {
                lostPoint += 40;
              }
            }
          }
          var darkCount = 0;
          for (var col = 0; col < moduleCount; col += 1) {
            for (var row = 0; row < moduleCount; row += 1) {
              if (qrcode4.isDark(row, col)) {
                darkCount += 1;
              }
            }
          }
          var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
          lostPoint += ratio * 10;
          return lostPoint;
        };
        return _this;
      }();
      var QRMath = function() {
        var EXP_TABLE = new Array(256);
        var LOG_TABLE = new Array(256);
        for (var i4 = 0; i4 < 8; i4 += 1) {
          EXP_TABLE[i4] = 1 << i4;
        }
        for (var i4 = 8; i4 < 256; i4 += 1) {
          EXP_TABLE[i4] = EXP_TABLE[i4 - 4] ^ EXP_TABLE[i4 - 5] ^ EXP_TABLE[i4 - 6] ^ EXP_TABLE[i4 - 8];
        }
        for (var i4 = 0; i4 < 255; i4 += 1) {
          LOG_TABLE[EXP_TABLE[i4]] = i4;
        }
        var _this = {};
        _this.glog = function(n3) {
          if (n3 < 1) {
            throw "glog(" + n3 + ")";
          }
          return LOG_TABLE[n3];
        };
        _this.gexp = function(n3) {
          while (n3 < 0) {
            n3 += 255;
          }
          while (n3 >= 256) {
            n3 -= 255;
          }
          return EXP_TABLE[n3];
        };
        return _this;
      }();
      function qrPolynomial(num, shift) {
        if (typeof num.length == "undefined") {
          throw num.length + "/" + shift;
        }
        var _num = function() {
          var offset = 0;
          while (offset < num.length && num[offset] == 0) {
            offset += 1;
          }
          var _num2 = new Array(num.length - offset + shift);
          for (var i4 = 0; i4 < num.length - offset; i4 += 1) {
            _num2[i4] = num[i4 + offset];
          }
          return _num2;
        }();
        var _this = {};
        _this.getAt = function(index) {
          return _num[index];
        };
        _this.getLength = function() {
          return _num.length;
        };
        _this.multiply = function(e4) {
          var num2 = new Array(_this.getLength() + e4.getLength() - 1);
          for (var i4 = 0; i4 < _this.getLength(); i4 += 1) {
            for (var j4 = 0; j4 < e4.getLength(); j4 += 1) {
              num2[i4 + j4] ^= QRMath.gexp(QRMath.glog(_this.getAt(i4)) + QRMath.glog(e4.getAt(j4)));
            }
          }
          return qrPolynomial(num2, 0);
        };
        _this.mod = function(e4) {
          if (_this.getLength() - e4.getLength() < 0) {
            return _this;
          }
          var ratio = QRMath.glog(_this.getAt(0)) - QRMath.glog(e4.getAt(0));
          var num2 = new Array(_this.getLength());
          for (var i4 = 0; i4 < _this.getLength(); i4 += 1) {
            num2[i4] = _this.getAt(i4);
          }
          for (var i4 = 0; i4 < e4.getLength(); i4 += 1) {
            num2[i4] ^= QRMath.gexp(QRMath.glog(e4.getAt(i4)) + ratio);
          }
          return qrPolynomial(num2, 0).mod(e4);
        };
        return _this;
      }
      ;
      var QRRSBlock = function() {
        var RS_BLOCK_TABLE = [
          // L
          // M
          // Q
          // H
          // 1
          [1, 26, 19],
          [1, 26, 16],
          [1, 26, 13],
          [1, 26, 9],
          // 2
          [1, 44, 34],
          [1, 44, 28],
          [1, 44, 22],
          [1, 44, 16],
          // 3
          [1, 70, 55],
          [1, 70, 44],
          [2, 35, 17],
          [2, 35, 13],
          // 4
          [1, 100, 80],
          [2, 50, 32],
          [2, 50, 24],
          [4, 25, 9],
          // 5
          [1, 134, 108],
          [2, 67, 43],
          [2, 33, 15, 2, 34, 16],
          [2, 33, 11, 2, 34, 12],
          // 6
          [2, 86, 68],
          [4, 43, 27],
          [4, 43, 19],
          [4, 43, 15],
          // 7
          [2, 98, 78],
          [4, 49, 31],
          [2, 32, 14, 4, 33, 15],
          [4, 39, 13, 1, 40, 14],
          // 8
          [2, 121, 97],
          [2, 60, 38, 2, 61, 39],
          [4, 40, 18, 2, 41, 19],
          [4, 40, 14, 2, 41, 15],
          // 9
          [2, 146, 116],
          [3, 58, 36, 2, 59, 37],
          [4, 36, 16, 4, 37, 17],
          [4, 36, 12, 4, 37, 13],
          // 10
          [2, 86, 68, 2, 87, 69],
          [4, 69, 43, 1, 70, 44],
          [6, 43, 19, 2, 44, 20],
          [6, 43, 15, 2, 44, 16],
          // 11
          [4, 101, 81],
          [1, 80, 50, 4, 81, 51],
          [4, 50, 22, 4, 51, 23],
          [3, 36, 12, 8, 37, 13],
          // 12
          [2, 116, 92, 2, 117, 93],
          [6, 58, 36, 2, 59, 37],
          [4, 46, 20, 6, 47, 21],
          [7, 42, 14, 4, 43, 15],
          // 13
          [4, 133, 107],
          [8, 59, 37, 1, 60, 38],
          [8, 44, 20, 4, 45, 21],
          [12, 33, 11, 4, 34, 12],
          // 14
          [3, 145, 115, 1, 146, 116],
          [4, 64, 40, 5, 65, 41],
          [11, 36, 16, 5, 37, 17],
          [11, 36, 12, 5, 37, 13],
          // 15
          [5, 109, 87, 1, 110, 88],
          [5, 65, 41, 5, 66, 42],
          [5, 54, 24, 7, 55, 25],
          [11, 36, 12, 7, 37, 13],
          // 16
          [5, 122, 98, 1, 123, 99],
          [7, 73, 45, 3, 74, 46],
          [15, 43, 19, 2, 44, 20],
          [3, 45, 15, 13, 46, 16],
          // 17
          [1, 135, 107, 5, 136, 108],
          [10, 74, 46, 1, 75, 47],
          [1, 50, 22, 15, 51, 23],
          [2, 42, 14, 17, 43, 15],
          // 18
          [5, 150, 120, 1, 151, 121],
          [9, 69, 43, 4, 70, 44],
          [17, 50, 22, 1, 51, 23],
          [2, 42, 14, 19, 43, 15],
          // 19
          [3, 141, 113, 4, 142, 114],
          [3, 70, 44, 11, 71, 45],
          [17, 47, 21, 4, 48, 22],
          [9, 39, 13, 16, 40, 14],
          // 20
          [3, 135, 107, 5, 136, 108],
          [3, 67, 41, 13, 68, 42],
          [15, 54, 24, 5, 55, 25],
          [15, 43, 15, 10, 44, 16],
          // 21
          [4, 144, 116, 4, 145, 117],
          [17, 68, 42],
          [17, 50, 22, 6, 51, 23],
          [19, 46, 16, 6, 47, 17],
          // 22
          [2, 139, 111, 7, 140, 112],
          [17, 74, 46],
          [7, 54, 24, 16, 55, 25],
          [34, 37, 13],
          // 23
          [4, 151, 121, 5, 152, 122],
          [4, 75, 47, 14, 76, 48],
          [11, 54, 24, 14, 55, 25],
          [16, 45, 15, 14, 46, 16],
          // 24
          [6, 147, 117, 4, 148, 118],
          [6, 73, 45, 14, 74, 46],
          [11, 54, 24, 16, 55, 25],
          [30, 46, 16, 2, 47, 17],
          // 25
          [8, 132, 106, 4, 133, 107],
          [8, 75, 47, 13, 76, 48],
          [7, 54, 24, 22, 55, 25],
          [22, 45, 15, 13, 46, 16],
          // 26
          [10, 142, 114, 2, 143, 115],
          [19, 74, 46, 4, 75, 47],
          [28, 50, 22, 6, 51, 23],
          [33, 46, 16, 4, 47, 17],
          // 27
          [8, 152, 122, 4, 153, 123],
          [22, 73, 45, 3, 74, 46],
          [8, 53, 23, 26, 54, 24],
          [12, 45, 15, 28, 46, 16],
          // 28
          [3, 147, 117, 10, 148, 118],
          [3, 73, 45, 23, 74, 46],
          [4, 54, 24, 31, 55, 25],
          [11, 45, 15, 31, 46, 16],
          // 29
          [7, 146, 116, 7, 147, 117],
          [21, 73, 45, 7, 74, 46],
          [1, 53, 23, 37, 54, 24],
          [19, 45, 15, 26, 46, 16],
          // 30
          [5, 145, 115, 10, 146, 116],
          [19, 75, 47, 10, 76, 48],
          [15, 54, 24, 25, 55, 25],
          [23, 45, 15, 25, 46, 16],
          // 31
          [13, 145, 115, 3, 146, 116],
          [2, 74, 46, 29, 75, 47],
          [42, 54, 24, 1, 55, 25],
          [23, 45, 15, 28, 46, 16],
          // 32
          [17, 145, 115],
          [10, 74, 46, 23, 75, 47],
          [10, 54, 24, 35, 55, 25],
          [19, 45, 15, 35, 46, 16],
          // 33
          [17, 145, 115, 1, 146, 116],
          [14, 74, 46, 21, 75, 47],
          [29, 54, 24, 19, 55, 25],
          [11, 45, 15, 46, 46, 16],
          // 34
          [13, 145, 115, 6, 146, 116],
          [14, 74, 46, 23, 75, 47],
          [44, 54, 24, 7, 55, 25],
          [59, 46, 16, 1, 47, 17],
          // 35
          [12, 151, 121, 7, 152, 122],
          [12, 75, 47, 26, 76, 48],
          [39, 54, 24, 14, 55, 25],
          [22, 45, 15, 41, 46, 16],
          // 36
          [6, 151, 121, 14, 152, 122],
          [6, 75, 47, 34, 76, 48],
          [46, 54, 24, 10, 55, 25],
          [2, 45, 15, 64, 46, 16],
          // 37
          [17, 152, 122, 4, 153, 123],
          [29, 74, 46, 14, 75, 47],
          [49, 54, 24, 10, 55, 25],
          [24, 45, 15, 46, 46, 16],
          // 38
          [4, 152, 122, 18, 153, 123],
          [13, 74, 46, 32, 75, 47],
          [48, 54, 24, 14, 55, 25],
          [42, 45, 15, 32, 46, 16],
          // 39
          [20, 147, 117, 4, 148, 118],
          [40, 75, 47, 7, 76, 48],
          [43, 54, 24, 22, 55, 25],
          [10, 45, 15, 67, 46, 16],
          // 40
          [19, 148, 118, 6, 149, 119],
          [18, 75, 47, 31, 76, 48],
          [34, 54, 24, 34, 55, 25],
          [20, 45, 15, 61, 46, 16]
        ];
        var qrRSBlock = function(totalCount, dataCount) {
          var _this2 = {};
          _this2.totalCount = totalCount;
          _this2.dataCount = dataCount;
          return _this2;
        };
        var _this = {};
        var getRsBlockTable = function(typeNumber, errorCorrectionLevel) {
          switch (errorCorrectionLevel) {
            case QRErrorCorrectionLevel.L:
              return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0];
            case QRErrorCorrectionLevel.M:
              return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1];
            case QRErrorCorrectionLevel.Q:
              return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2];
            case QRErrorCorrectionLevel.H:
              return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3];
            default:
              return void 0;
          }
        };
        _this.getRSBlocks = function(typeNumber, errorCorrectionLevel) {
          var rsBlock = getRsBlockTable(typeNumber, errorCorrectionLevel);
          if (typeof rsBlock == "undefined") {
            throw "bad rs block @ typeNumber:" + typeNumber + "/errorCorrectionLevel:" + errorCorrectionLevel;
          }
          var length = rsBlock.length / 3;
          var list = [];
          for (var i4 = 0; i4 < length; i4 += 1) {
            var count = rsBlock[i4 * 3 + 0];
            var totalCount = rsBlock[i4 * 3 + 1];
            var dataCount = rsBlock[i4 * 3 + 2];
            for (var j4 = 0; j4 < count; j4 += 1) {
              list.push(qrRSBlock(totalCount, dataCount));
            }
          }
          return list;
        };
        return _this;
      }();
      var qrBitBuffer = function() {
        var _buffer = [];
        var _length = 0;
        var _this = {};
        _this.getBuffer = function() {
          return _buffer;
        };
        _this.getAt = function(index) {
          var bufIndex = Math.floor(index / 8);
          return (_buffer[bufIndex] >>> 7 - index % 8 & 1) == 1;
        };
        _this.put = function(num, length) {
          for (var i4 = 0; i4 < length; i4 += 1) {
            _this.putBit((num >>> length - i4 - 1 & 1) == 1);
          }
        };
        _this.getLengthInBits = function() {
          return _length;
        };
        _this.putBit = function(bit) {
          var bufIndex = Math.floor(_length / 8);
          if (_buffer.length <= bufIndex) {
            _buffer.push(0);
          }
          if (bit) {
            _buffer[bufIndex] |= 128 >>> _length % 8;
          }
          _length += 1;
        };
        return _this;
      };
      var qrNumber = function(data) {
        var _mode = QRMode.MODE_NUMBER;
        var _data = data;
        var _this = {};
        _this.getMode = function() {
          return _mode;
        };
        _this.getLength = function(buffer) {
          return _data.length;
        };
        _this.write = function(buffer) {
          var data2 = _data;
          var i4 = 0;
          while (i4 + 2 < data2.length) {
            buffer.put(strToNum(data2.substring(i4, i4 + 3)), 10);
            i4 += 3;
          }
          if (i4 < data2.length) {
            if (data2.length - i4 == 1) {
              buffer.put(strToNum(data2.substring(i4, i4 + 1)), 4);
            } else if (data2.length - i4 == 2) {
              buffer.put(strToNum(data2.substring(i4, i4 + 2)), 7);
            }
          }
        };
        var strToNum = function(s4) {
          var num = 0;
          for (var i4 = 0; i4 < s4.length; i4 += 1) {
            num = num * 10 + chatToNum(s4.charAt(i4));
          }
          return num;
        };
        var chatToNum = function(c4) {
          if ("0" <= c4 && c4 <= "9") {
            return c4.charCodeAt(0) - "0".charCodeAt(0);
          }
          throw "illegal char :" + c4;
        };
        return _this;
      };
      var qrAlphaNum = function(data) {
        var _mode = QRMode.MODE_ALPHA_NUM;
        var _data = data;
        var _this = {};
        _this.getMode = function() {
          return _mode;
        };
        _this.getLength = function(buffer) {
          return _data.length;
        };
        _this.write = function(buffer) {
          var s4 = _data;
          var i4 = 0;
          while (i4 + 1 < s4.length) {
            buffer.put(
              getCode(s4.charAt(i4)) * 45 + getCode(s4.charAt(i4 + 1)),
              11
            );
            i4 += 2;
          }
          if (i4 < s4.length) {
            buffer.put(getCode(s4.charAt(i4)), 6);
          }
        };
        var getCode = function(c4) {
          if ("0" <= c4 && c4 <= "9") {
            return c4.charCodeAt(0) - "0".charCodeAt(0);
          } else if ("A" <= c4 && c4 <= "Z") {
            return c4.charCodeAt(0) - "A".charCodeAt(0) + 10;
          } else {
            switch (c4) {
              case " ":
                return 36;
              case "$":
                return 37;
              case "%":
                return 38;
              case "*":
                return 39;
              case "+":
                return 40;
              case "-":
                return 41;
              case ".":
                return 42;
              case "/":
                return 43;
              case ":":
                return 44;
              default:
                throw "illegal char :" + c4;
            }
          }
        };
        return _this;
      };
      var qr8BitByte = function(data) {
        var _mode = QRMode.MODE_8BIT_BYTE;
        var _data = data;
        var _bytes = qrcode3.stringToBytes(data);
        var _this = {};
        _this.getMode = function() {
          return _mode;
        };
        _this.getLength = function(buffer) {
          return _bytes.length;
        };
        _this.write = function(buffer) {
          for (var i4 = 0; i4 < _bytes.length; i4 += 1) {
            buffer.put(_bytes[i4], 8);
          }
        };
        return _this;
      };
      var qrKanji = function(data) {
        var _mode = QRMode.MODE_KANJI;
        var _data = data;
        var stringToBytes2 = qrcode3.stringToBytesFuncs["SJIS"];
        if (!stringToBytes2) {
          throw "sjis not supported.";
        }
        !function(c4, code) {
          var test = stringToBytes2(c4);
          if (test.length != 2 || (test[0] << 8 | test[1]) != code) {
            throw "sjis not supported.";
          }
        }("\u53CB", 38726);
        var _bytes = stringToBytes2(data);
        var _this = {};
        _this.getMode = function() {
          return _mode;
        };
        _this.getLength = function(buffer) {
          return ~~(_bytes.length / 2);
        };
        _this.write = function(buffer) {
          var data2 = _bytes;
          var i4 = 0;
          while (i4 + 1 < data2.length) {
            var c4 = (255 & data2[i4]) << 8 | 255 & data2[i4 + 1];
            if (33088 <= c4 && c4 <= 40956) {
              c4 -= 33088;
            } else if (57408 <= c4 && c4 <= 60351) {
              c4 -= 49472;
            } else {
              throw "illegal char at " + (i4 + 1) + "/" + c4;
            }
            c4 = (c4 >>> 8 & 255) * 192 + (c4 & 255);
            buffer.put(c4, 13);
            i4 += 2;
          }
          if (i4 < data2.length) {
            throw "illegal char at " + (i4 + 1);
          }
        };
        return _this;
      };
      var byteArrayOutputStream = function() {
        var _bytes = [];
        var _this = {};
        _this.writeByte = function(b4) {
          _bytes.push(b4 & 255);
        };
        _this.writeShort = function(i4) {
          _this.writeByte(i4);
          _this.writeByte(i4 >>> 8);
        };
        _this.writeBytes = function(b4, off, len) {
          off = off || 0;
          len = len || b4.length;
          for (var i4 = 0; i4 < len; i4 += 1) {
            _this.writeByte(b4[i4 + off]);
          }
        };
        _this.writeString = function(s4) {
          for (var i4 = 0; i4 < s4.length; i4 += 1) {
            _this.writeByte(s4.charCodeAt(i4));
          }
        };
        _this.toByteArray = function() {
          return _bytes;
        };
        _this.toString = function() {
          var s4 = "";
          s4 += "[";
          for (var i4 = 0; i4 < _bytes.length; i4 += 1) {
            if (i4 > 0) {
              s4 += ",";
            }
            s4 += _bytes[i4];
          }
          s4 += "]";
          return s4;
        };
        return _this;
      };
      var base64EncodeOutputStream = function() {
        var _buffer = 0;
        var _buflen = 0;
        var _length = 0;
        var _base64 = "";
        var _this = {};
        var writeEncoded = function(b4) {
          _base64 += String.fromCharCode(encode2(b4 & 63));
        };
        var encode2 = function(n3) {
          if (n3 < 0) {
          } else if (n3 < 26) {
            return 65 + n3;
          } else if (n3 < 52) {
            return 97 + (n3 - 26);
          } else if (n3 < 62) {
            return 48 + (n3 - 52);
          } else if (n3 == 62) {
            return 43;
          } else if (n3 == 63) {
            return 47;
          }
          throw "n:" + n3;
        };
        _this.writeByte = function(n3) {
          _buffer = _buffer << 8 | n3 & 255;
          _buflen += 8;
          _length += 1;
          while (_buflen >= 6) {
            writeEncoded(_buffer >>> _buflen - 6);
            _buflen -= 6;
          }
        };
        _this.flush = function() {
          if (_buflen > 0) {
            writeEncoded(_buffer << 6 - _buflen);
            _buffer = 0;
            _buflen = 0;
          }
          if (_length % 3 != 0) {
            var padlen = 3 - _length % 3;
            for (var i4 = 0; i4 < padlen; i4 += 1) {
              _base64 += "=";
            }
          }
        };
        _this.toString = function() {
          return _base64;
        };
        return _this;
      };
      var base64DecodeInputStream = function(str) {
        var _str = str;
        var _pos = 0;
        var _buffer = 0;
        var _buflen = 0;
        var _this = {};
        _this.read = function() {
          while (_buflen < 8) {
            if (_pos >= _str.length) {
              if (_buflen == 0) {
                return -1;
              }
              throw "unexpected end of file./" + _buflen;
            }
            var c4 = _str.charAt(_pos);
            _pos += 1;
            if (c4 == "=") {
              _buflen = 0;
              return -1;
            } else if (c4.match(/^\s$/)) {
              continue;
            }
            _buffer = _buffer << 6 | decode2(c4.charCodeAt(0));
            _buflen += 6;
          }
          var n3 = _buffer >>> _buflen - 8 & 255;
          _buflen -= 8;
          return n3;
        };
        var decode2 = function(c4) {
          if (65 <= c4 && c4 <= 90) {
            return c4 - 65;
          } else if (97 <= c4 && c4 <= 122) {
            return c4 - 97 + 26;
          } else if (48 <= c4 && c4 <= 57) {
            return c4 - 48 + 52;
          } else if (c4 == 43) {
            return 62;
          } else if (c4 == 47) {
            return 63;
          } else {
            throw "c:" + c4;
          }
        };
        return _this;
      };
      var gifImage = function(width, height) {
        var _width = width;
        var _height = height;
        var _data = new Array(width * height);
        var _this = {};
        _this.setPixel = function(x3, y4, pixel) {
          _data[y4 * _width + x3] = pixel;
        };
        _this.write = function(out) {
          out.writeString("GIF87a");
          out.writeShort(_width);
          out.writeShort(_height);
          out.writeByte(128);
          out.writeByte(0);
          out.writeByte(0);
          out.writeByte(0);
          out.writeByte(0);
          out.writeByte(0);
          out.writeByte(255);
          out.writeByte(255);
          out.writeByte(255);
          out.writeString(",");
          out.writeShort(0);
          out.writeShort(0);
          out.writeShort(_width);
          out.writeShort(_height);
          out.writeByte(0);
          var lzwMinCodeSize = 2;
          var raster = getLZWRaster(lzwMinCodeSize);
          out.writeByte(lzwMinCodeSize);
          var offset = 0;
          while (raster.length - offset > 255) {
            out.writeByte(255);
            out.writeBytes(raster, offset, 255);
            offset += 255;
          }
          out.writeByte(raster.length - offset);
          out.writeBytes(raster, offset, raster.length - offset);
          out.writeByte(0);
          out.writeString(";");
        };
        var bitOutputStream = function(out) {
          var _out = out;
          var _bitLength = 0;
          var _bitBuffer = 0;
          var _this2 = {};
          _this2.write = function(data, length) {
            if (data >>> length != 0) {
              throw "length over";
            }
            while (_bitLength + length >= 8) {
              _out.writeByte(255 & (data << _bitLength | _bitBuffer));
              length -= 8 - _bitLength;
              data >>>= 8 - _bitLength;
              _bitBuffer = 0;
              _bitLength = 0;
            }
            _bitBuffer = data << _bitLength | _bitBuffer;
            _bitLength = _bitLength + length;
          };
          _this2.flush = function() {
            if (_bitLength > 0) {
              _out.writeByte(_bitBuffer);
            }
          };
          return _this2;
        };
        var getLZWRaster = function(lzwMinCodeSize) {
          var clearCode = 1 << lzwMinCodeSize;
          var endCode = (1 << lzwMinCodeSize) + 1;
          var bitLength = lzwMinCodeSize + 1;
          var table = lzwTable();
          for (var i4 = 0; i4 < clearCode; i4 += 1) {
            table.add(String.fromCharCode(i4));
          }
          table.add(String.fromCharCode(clearCode));
          table.add(String.fromCharCode(endCode));
          var byteOut = byteArrayOutputStream();
          var bitOut = bitOutputStream(byteOut);
          bitOut.write(clearCode, bitLength);
          var dataIndex = 0;
          var s4 = String.fromCharCode(_data[dataIndex]);
          dataIndex += 1;
          while (dataIndex < _data.length) {
            var c4 = String.fromCharCode(_data[dataIndex]);
            dataIndex += 1;
            if (table.contains(s4 + c4)) {
              s4 = s4 + c4;
            } else {
              bitOut.write(table.indexOf(s4), bitLength);
              if (table.size() < 4095) {
                if (table.size() == 1 << bitLength) {
                  bitLength += 1;
                }
                table.add(s4 + c4);
              }
              s4 = c4;
            }
          }
          bitOut.write(table.indexOf(s4), bitLength);
          bitOut.write(endCode, bitLength);
          bitOut.flush();
          return byteOut.toByteArray();
        };
        var lzwTable = function() {
          var _map = {};
          var _size = 0;
          var _this2 = {};
          _this2.add = function(key) {
            if (_this2.contains(key)) {
              throw "dup key:" + key;
            }
            _map[key] = _size;
            _size += 1;
          };
          _this2.size = function() {
            return _size;
          };
          _this2.indexOf = function(key) {
            return _map[key];
          };
          _this2.contains = function(key) {
            return typeof _map[key] != "undefined";
          };
          return _this2;
        };
        return _this;
      };
      var createDataURL = function(width, height, getPixel) {
        var gif = gifImage(width, height);
        for (var y4 = 0; y4 < height; y4 += 1) {
          for (var x3 = 0; x3 < width; x3 += 1) {
            gif.setPixel(x3, y4, getPixel(x3, y4));
          }
        }
        var b4 = byteArrayOutputStream();
        gif.write(b4);
        var base64 = base64EncodeOutputStream();
        var bytes = b4.toByteArray();
        for (var i4 = 0; i4 < bytes.length; i4 += 1) {
          base64.writeByte(bytes[i4]);
        }
        base64.flush();
        return "data:image/gif;base64," + base64;
      };
      return qrcode3;
    }();
    !function() {
      qrcode2.stringToBytesFuncs["UTF-8"] = function(s4) {
        function toUTF8Array(str) {
          var utf8 = [];
          for (var i4 = 0; i4 < str.length; i4++) {
            var charcode = str.charCodeAt(i4);
            if (charcode < 128)
              utf8.push(charcode);
            else if (charcode < 2048) {
              utf8.push(
                192 | charcode >> 6,
                128 | charcode & 63
              );
            } else if (charcode < 55296 || charcode >= 57344) {
              utf8.push(
                224 | charcode >> 12,
                128 | charcode >> 6 & 63,
                128 | charcode & 63
              );
            } else {
              i4++;
              charcode = 65536 + ((charcode & 1023) << 10 | str.charCodeAt(i4) & 1023);
              utf8.push(
                240 | charcode >> 18,
                128 | charcode >> 12 & 63,
                128 | charcode >> 6 & 63,
                128 | charcode & 63
              );
            }
          }
          return utf8;
        }
        return toUTF8Array(s4);
      };
    }();
    (function(factory) {
      if (typeof define === "function" && define.amd) {
        define([], factory);
      } else if (typeof exports === "object") {
        module.exports = factory();
      }
    })(function() {
      return qrcode2;
    });
  }
});

// src/index.ts
init_preact_module();

// src/components/app.tsx
init_preact_module();

// ../taler-util/lib/nacl-fast.js
var gf = function(init = []) {
  const r4 = new Float64Array(16);
  if (init)
    for (let i4 = 0; i4 < init.length; i4++)
      r4[i4] = init[i4];
  return r4;
};
var randombytes = function(x3, n3) {
  throw new Error("no PRNG");
};
var _9 = new Uint8Array(32);
_9[0] = 9;
var gf0 = gf();
var gf1 = gf([1]);
var _121665 = gf([56129, 1]);
var D = gf([
  30883,
  4953,
  19914,
  30187,
  55467,
  16705,
  2637,
  112,
  59544,
  30585,
  16505,
  36039,
  65139,
  11119,
  27886,
  20995
]);
var D2 = gf([
  61785,
  9906,
  39828,
  60374,
  45398,
  33411,
  5274,
  224,
  53552,
  61171,
  33010,
  6542,
  64743,
  22239,
  55772,
  9222
]);
var X = gf([
  54554,
  36645,
  11616,
  51542,
  42930,
  38181,
  51040,
  26924,
  56412,
  64982,
  57905,
  49316,
  21502,
  52590,
  14035,
  8553
]);
var Y = gf([
  26200,
  26214,
  26214,
  26214,
  26214,
  26214,
  26214,
  26214,
  26214,
  26214,
  26214,
  26214,
  26214,
  26214,
  26214,
  26214
]);
var I2 = gf([
  41136,
  18958,
  6951,
  50414,
  58488,
  44335,
  6150,
  12099,
  55207,
  15867,
  153,
  11085,
  57099,
  20417,
  9344,
  11139
]);
function ts64(x3, i4, h4, l4) {
  x3[i4] = h4 >> 24 & 255;
  x3[i4 + 1] = h4 >> 16 & 255;
  x3[i4 + 2] = h4 >> 8 & 255;
  x3[i4 + 3] = h4 & 255;
  x3[i4 + 4] = l4 >> 24 & 255;
  x3[i4 + 5] = l4 >> 16 & 255;
  x3[i4 + 6] = l4 >> 8 & 255;
  x3[i4 + 7] = l4 & 255;
}
function vn(x3, xi, y4, yi, n3) {
  let i4, d4 = 0;
  for (i4 = 0; i4 < n3; i4++)
    d4 |= x3[xi + i4] ^ y4[yi + i4];
  return (1 & d4 - 1 >>> 8) - 1;
}
function crypto_verify_16(x3, xi, y4, yi) {
  return vn(x3, xi, y4, yi, 16);
}
function crypto_verify_32(x3, xi, y4, yi) {
  return vn(x3, xi, y4, yi, 32);
}
function core_salsa20(o4, p5, k4, c4) {
  var j0 = c4[0] & 255 | (c4[1] & 255) << 8 | (c4[2] & 255) << 16 | (c4[3] & 255) << 24, j1 = k4[0] & 255 | (k4[1] & 255) << 8 | (k4[2] & 255) << 16 | (k4[3] & 255) << 24, j22 = k4[4] & 255 | (k4[5] & 255) << 8 | (k4[6] & 255) << 16 | (k4[7] & 255) << 24, j32 = k4[8] & 255 | (k4[9] & 255) << 8 | (k4[10] & 255) << 16 | (k4[11] & 255) << 24, j4 = k4[12] & 255 | (k4[13] & 255) << 8 | (k4[14] & 255) << 16 | (k4[15] & 255) << 24, j5 = c4[4] & 255 | (c4[5] & 255) << 8 | (c4[6] & 255) << 16 | (c4[7] & 255) << 24, j6 = p5[0] & 255 | (p5[1] & 255) << 8 | (p5[2] & 255) << 16 | (p5[3] & 255) << 24, j7 = p5[4] & 255 | (p5[5] & 255) << 8 | (p5[6] & 255) << 16 | (p5[7] & 255) << 24, j8 = p5[8] & 255 | (p5[9] & 255) << 8 | (p5[10] & 255) << 16 | (p5[11] & 255) << 24, j9 = p5[12] & 255 | (p5[13] & 255) << 8 | (p5[14] & 255) << 16 | (p5[15] & 255) << 24, j10 = c4[8] & 255 | (c4[9] & 255) << 8 | (c4[10] & 255) << 16 | (c4[11] & 255) << 24, j11 = k4[16] & 255 | (k4[17] & 255) << 8 | (k4[18] & 255) << 16 | (k4[19] & 255) << 24, j12 = k4[20] & 255 | (k4[21] & 255) << 8 | (k4[22] & 255) << 16 | (k4[23] & 255) << 24, j13 = k4[24] & 255 | (k4[25] & 255) << 8 | (k4[26] & 255) << 16 | (k4[27] & 255) << 24, j14 = k4[28] & 255 | (k4[29] & 255) << 8 | (k4[30] & 255) << 16 | (k4[31] & 255) << 24, j15 = c4[12] & 255 | (c4[13] & 255) << 8 | (c4[14] & 255) << 16 | (c4[15] & 255) << 24;
  var x0 = j0, x1 = j1, x22 = j22, x3 = j32, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u4;
  for (var i4 = 0; i4 < 20; i4 += 2) {
    u4 = x0 + x12 | 0;
    x4 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x4 + x0 | 0;
    x8 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x8 + x4 | 0;
    x12 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x12 + x8 | 0;
    x0 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x5 + x1 | 0;
    x9 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x9 + x5 | 0;
    x13 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x13 + x9 | 0;
    x1 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x1 + x13 | 0;
    x5 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x10 + x6 | 0;
    x14 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x14 + x10 | 0;
    x22 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x22 + x14 | 0;
    x6 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x6 + x22 | 0;
    x10 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x15 + x11 | 0;
    x3 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x3 + x15 | 0;
    x7 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x7 + x3 | 0;
    x11 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x11 + x7 | 0;
    x15 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x0 + x3 | 0;
    x1 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x1 + x0 | 0;
    x22 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x22 + x1 | 0;
    x3 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x3 + x22 | 0;
    x0 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x5 + x4 | 0;
    x6 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x6 + x5 | 0;
    x7 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x7 + x6 | 0;
    x4 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x4 + x7 | 0;
    x5 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x10 + x9 | 0;
    x11 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x11 + x10 | 0;
    x8 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x8 + x11 | 0;
    x9 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x9 + x8 | 0;
    x10 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x15 + x14 | 0;
    x12 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x12 + x15 | 0;
    x13 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x13 + x12 | 0;
    x14 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x14 + x13 | 0;
    x15 ^= u4 << 18 | u4 >>> 32 - 18;
  }
  x0 = x0 + j0 | 0;
  x1 = x1 + j1 | 0;
  x22 = x22 + j22 | 0;
  x3 = x3 + j32 | 0;
  x4 = x4 + j4 | 0;
  x5 = x5 + j5 | 0;
  x6 = x6 + j6 | 0;
  x7 = x7 + j7 | 0;
  x8 = x8 + j8 | 0;
  x9 = x9 + j9 | 0;
  x10 = x10 + j10 | 0;
  x11 = x11 + j11 | 0;
  x12 = x12 + j12 | 0;
  x13 = x13 + j13 | 0;
  x14 = x14 + j14 | 0;
  x15 = x15 + j15 | 0;
  o4[0] = x0 >>> 0 & 255;
  o4[1] = x0 >>> 8 & 255;
  o4[2] = x0 >>> 16 & 255;
  o4[3] = x0 >>> 24 & 255;
  o4[4] = x1 >>> 0 & 255;
  o4[5] = x1 >>> 8 & 255;
  o4[6] = x1 >>> 16 & 255;
  o4[7] = x1 >>> 24 & 255;
  o4[8] = x22 >>> 0 & 255;
  o4[9] = x22 >>> 8 & 255;
  o4[10] = x22 >>> 16 & 255;
  o4[11] = x22 >>> 24 & 255;
  o4[12] = x3 >>> 0 & 255;
  o4[13] = x3 >>> 8 & 255;
  o4[14] = x3 >>> 16 & 255;
  o4[15] = x3 >>> 24 & 255;
  o4[16] = x4 >>> 0 & 255;
  o4[17] = x4 >>> 8 & 255;
  o4[18] = x4 >>> 16 & 255;
  o4[19] = x4 >>> 24 & 255;
  o4[20] = x5 >>> 0 & 255;
  o4[21] = x5 >>> 8 & 255;
  o4[22] = x5 >>> 16 & 255;
  o4[23] = x5 >>> 24 & 255;
  o4[24] = x6 >>> 0 & 255;
  o4[25] = x6 >>> 8 & 255;
  o4[26] = x6 >>> 16 & 255;
  o4[27] = x6 >>> 24 & 255;
  o4[28] = x7 >>> 0 & 255;
  o4[29] = x7 >>> 8 & 255;
  o4[30] = x7 >>> 16 & 255;
  o4[31] = x7 >>> 24 & 255;
  o4[32] = x8 >>> 0 & 255;
  o4[33] = x8 >>> 8 & 255;
  o4[34] = x8 >>> 16 & 255;
  o4[35] = x8 >>> 24 & 255;
  o4[36] = x9 >>> 0 & 255;
  o4[37] = x9 >>> 8 & 255;
  o4[38] = x9 >>> 16 & 255;
  o4[39] = x9 >>> 24 & 255;
  o4[40] = x10 >>> 0 & 255;
  o4[41] = x10 >>> 8 & 255;
  o4[42] = x10 >>> 16 & 255;
  o4[43] = x10 >>> 24 & 255;
  o4[44] = x11 >>> 0 & 255;
  o4[45] = x11 >>> 8 & 255;
  o4[46] = x11 >>> 16 & 255;
  o4[47] = x11 >>> 24 & 255;
  o4[48] = x12 >>> 0 & 255;
  o4[49] = x12 >>> 8 & 255;
  o4[50] = x12 >>> 16 & 255;
  o4[51] = x12 >>> 24 & 255;
  o4[52] = x13 >>> 0 & 255;
  o4[53] = x13 >>> 8 & 255;
  o4[54] = x13 >>> 16 & 255;
  o4[55] = x13 >>> 24 & 255;
  o4[56] = x14 >>> 0 & 255;
  o4[57] = x14 >>> 8 & 255;
  o4[58] = x14 >>> 16 & 255;
  o4[59] = x14 >>> 24 & 255;
  o4[60] = x15 >>> 0 & 255;
  o4[61] = x15 >>> 8 & 255;
  o4[62] = x15 >>> 16 & 255;
  o4[63] = x15 >>> 24 & 255;
}
function core_hsalsa20(o4, p5, k4, c4) {
  var j0 = c4[0] & 255 | (c4[1] & 255) << 8 | (c4[2] & 255) << 16 | (c4[3] & 255) << 24, j1 = k4[0] & 255 | (k4[1] & 255) << 8 | (k4[2] & 255) << 16 | (k4[3] & 255) << 24, j22 = k4[4] & 255 | (k4[5] & 255) << 8 | (k4[6] & 255) << 16 | (k4[7] & 255) << 24, j32 = k4[8] & 255 | (k4[9] & 255) << 8 | (k4[10] & 255) << 16 | (k4[11] & 255) << 24, j4 = k4[12] & 255 | (k4[13] & 255) << 8 | (k4[14] & 255) << 16 | (k4[15] & 255) << 24, j5 = c4[4] & 255 | (c4[5] & 255) << 8 | (c4[6] & 255) << 16 | (c4[7] & 255) << 24, j6 = p5[0] & 255 | (p5[1] & 255) << 8 | (p5[2] & 255) << 16 | (p5[3] & 255) << 24, j7 = p5[4] & 255 | (p5[5] & 255) << 8 | (p5[6] & 255) << 16 | (p5[7] & 255) << 24, j8 = p5[8] & 255 | (p5[9] & 255) << 8 | (p5[10] & 255) << 16 | (p5[11] & 255) << 24, j9 = p5[12] & 255 | (p5[13] & 255) << 8 | (p5[14] & 255) << 16 | (p5[15] & 255) << 24, j10 = c4[8] & 255 | (c4[9] & 255) << 8 | (c4[10] & 255) << 16 | (c4[11] & 255) << 24, j11 = k4[16] & 255 | (k4[17] & 255) << 8 | (k4[18] & 255) << 16 | (k4[19] & 255) << 24, j12 = k4[20] & 255 | (k4[21] & 255) << 8 | (k4[22] & 255) << 16 | (k4[23] & 255) << 24, j13 = k4[24] & 255 | (k4[25] & 255) << 8 | (k4[26] & 255) << 16 | (k4[27] & 255) << 24, j14 = k4[28] & 255 | (k4[29] & 255) << 8 | (k4[30] & 255) << 16 | (k4[31] & 255) << 24, j15 = c4[12] & 255 | (c4[13] & 255) << 8 | (c4[14] & 255) << 16 | (c4[15] & 255) << 24;
  var x0 = j0, x1 = j1, x22 = j22, x3 = j32, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u4;
  for (var i4 = 0; i4 < 20; i4 += 2) {
    u4 = x0 + x12 | 0;
    x4 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x4 + x0 | 0;
    x8 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x8 + x4 | 0;
    x12 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x12 + x8 | 0;
    x0 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x5 + x1 | 0;
    x9 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x9 + x5 | 0;
    x13 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x13 + x9 | 0;
    x1 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x1 + x13 | 0;
    x5 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x10 + x6 | 0;
    x14 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x14 + x10 | 0;
    x22 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x22 + x14 | 0;
    x6 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x6 + x22 | 0;
    x10 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x15 + x11 | 0;
    x3 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x3 + x15 | 0;
    x7 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x7 + x3 | 0;
    x11 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x11 + x7 | 0;
    x15 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x0 + x3 | 0;
    x1 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x1 + x0 | 0;
    x22 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x22 + x1 | 0;
    x3 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x3 + x22 | 0;
    x0 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x5 + x4 | 0;
    x6 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x6 + x5 | 0;
    x7 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x7 + x6 | 0;
    x4 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x4 + x7 | 0;
    x5 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x10 + x9 | 0;
    x11 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x11 + x10 | 0;
    x8 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x8 + x11 | 0;
    x9 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x9 + x8 | 0;
    x10 ^= u4 << 18 | u4 >>> 32 - 18;
    u4 = x15 + x14 | 0;
    x12 ^= u4 << 7 | u4 >>> 32 - 7;
    u4 = x12 + x15 | 0;
    x13 ^= u4 << 9 | u4 >>> 32 - 9;
    u4 = x13 + x12 | 0;
    x14 ^= u4 << 13 | u4 >>> 32 - 13;
    u4 = x14 + x13 | 0;
    x15 ^= u4 << 18 | u4 >>> 32 - 18;
  }
  o4[0] = x0 >>> 0 & 255;
  o4[1] = x0 >>> 8 & 255;
  o4[2] = x0 >>> 16 & 255;
  o4[3] = x0 >>> 24 & 255;
  o4[4] = x5 >>> 0 & 255;
  o4[5] = x5 >>> 8 & 255;
  o4[6] = x5 >>> 16 & 255;
  o4[7] = x5 >>> 24 & 255;
  o4[8] = x10 >>> 0 & 255;
  o4[9] = x10 >>> 8 & 255;
  o4[10] = x10 >>> 16 & 255;
  o4[11] = x10 >>> 24 & 255;
  o4[12] = x15 >>> 0 & 255;
  o4[13] = x15 >>> 8 & 255;
  o4[14] = x15 >>> 16 & 255;
  o4[15] = x15 >>> 24 & 255;
  o4[16] = x6 >>> 0 & 255;
  o4[17] = x6 >>> 8 & 255;
  o4[18] = x6 >>> 16 & 255;
  o4[19] = x6 >>> 24 & 255;
  o4[20] = x7 >>> 0 & 255;
  o4[21] = x7 >>> 8 & 255;
  o4[22] = x7 >>> 16 & 255;
  o4[23] = x7 >>> 24 & 255;
  o4[24] = x8 >>> 0 & 255;
  o4[25] = x8 >>> 8 & 255;
  o4[26] = x8 >>> 16 & 255;
  o4[27] = x8 >>> 24 & 255;
  o4[28] = x9 >>> 0 & 255;
  o4[29] = x9 >>> 8 & 255;
  o4[30] = x9 >>> 16 & 255;
  o4[31] = x9 >>> 24 & 255;
}
var sigma = new Uint8Array([
  101,
  120,
  112,
  97,
  110,
  100,
  32,
  51,
  50,
  45,
  98,
  121,
  116,
  101,
  32,
  107
]);
function crypto_stream_salsa20_xor(c4, cpos, m4, mpos, b4, n3, k4) {
  var z4 = new Uint8Array(16), x3 = new Uint8Array(64);
  var u4, i4;
  for (i4 = 0; i4 < 16; i4++)
    z4[i4] = 0;
  for (i4 = 0; i4 < 8; i4++)
    z4[i4] = n3[i4];
  while (b4 >= 64) {
    core_salsa20(x3, z4, k4, sigma);
    for (i4 = 0; i4 < 64; i4++)
      c4[cpos + i4] = m4[mpos + i4] ^ x3[i4];
    u4 = 1;
    for (i4 = 8; i4 < 16; i4++) {
      u4 = u4 + (z4[i4] & 255) | 0;
      z4[i4] = u4 & 255;
      u4 >>>= 8;
    }
    b4 -= 64;
    cpos += 64;
    mpos += 64;
  }
  if (b4 > 0) {
    core_salsa20(x3, z4, k4, sigma);
    for (i4 = 0; i4 < b4; i4++)
      c4[cpos + i4] = m4[mpos + i4] ^ x3[i4];
  }
  return 0;
}
function crypto_stream_salsa20(c4, cpos, b4, n3, k4) {
  var z4 = new Uint8Array(16), x3 = new Uint8Array(64);
  var u4, i4;
  for (i4 = 0; i4 < 16; i4++)
    z4[i4] = 0;
  for (i4 = 0; i4 < 8; i4++)
    z4[i4] = n3[i4];
  while (b4 >= 64) {
    core_salsa20(x3, z4, k4, sigma);
    for (i4 = 0; i4 < 64; i4++)
      c4[cpos + i4] = x3[i4];
    u4 = 1;
    for (i4 = 8; i4 < 16; i4++) {
      u4 = u4 + (z4[i4] & 255) | 0;
      z4[i4] = u4 & 255;
      u4 >>>= 8;
    }
    b4 -= 64;
    cpos += 64;
  }
  if (b4 > 0) {
    core_salsa20(x3, z4, k4, sigma);
    for (i4 = 0; i4 < b4; i4++)
      c4[cpos + i4] = x3[i4];
  }
  return 0;
}
function crypto_stream(c4, cpos, d4, n3, k4) {
  var s4 = new Uint8Array(32);
  core_hsalsa20(s4, n3, k4, sigma);
  var sn = new Uint8Array(8);
  for (var i4 = 0; i4 < 8; i4++)
    sn[i4] = n3[i4 + 16];
  return crypto_stream_salsa20(c4, cpos, d4, sn, s4);
}
function crypto_stream_xor(c4, cpos, m4, mpos, d4, n3, k4) {
  var s4 = new Uint8Array(32);
  core_hsalsa20(s4, n3, k4, sigma);
  var sn = new Uint8Array(8);
  for (var i4 = 0; i4 < 8; i4++)
    sn[i4] = n3[i4 + 16];
  return crypto_stream_salsa20_xor(c4, cpos, m4, mpos, d4, sn, s4);
}
var poly1305 = class {
  constructor(key) {
    this.buffer = new Uint8Array(16);
    this.r = new Uint16Array(10);
    this.h = new Uint16Array(10);
    this.pad = new Uint16Array(8);
    this.leftover = 0;
    this.fin = 0;
    var t0, t1, t22, t32, t4, t5, t6, t7;
    t0 = key[0] & 255 | (key[1] & 255) << 8;
    this.r[0] = t0 & 8191;
    t1 = key[2] & 255 | (key[3] & 255) << 8;
    this.r[1] = (t0 >>> 13 | t1 << 3) & 8191;
    t22 = key[4] & 255 | (key[5] & 255) << 8;
    this.r[2] = (t1 >>> 10 | t22 << 6) & 7939;
    t32 = key[6] & 255 | (key[7] & 255) << 8;
    this.r[3] = (t22 >>> 7 | t32 << 9) & 8191;
    t4 = key[8] & 255 | (key[9] & 255) << 8;
    this.r[4] = (t32 >>> 4 | t4 << 12) & 255;
    this.r[5] = t4 >>> 1 & 8190;
    t5 = key[10] & 255 | (key[11] & 255) << 8;
    this.r[6] = (t4 >>> 14 | t5 << 2) & 8191;
    t6 = key[12] & 255 | (key[13] & 255) << 8;
    this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
    t7 = key[14] & 255 | (key[15] & 255) << 8;
    this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
    this.r[9] = t7 >>> 5 & 127;
    this.pad[0] = key[16] & 255 | (key[17] & 255) << 8;
    this.pad[1] = key[18] & 255 | (key[19] & 255) << 8;
    this.pad[2] = key[20] & 255 | (key[21] & 255) << 8;
    this.pad[3] = key[22] & 255 | (key[23] & 255) << 8;
    this.pad[4] = key[24] & 255 | (key[25] & 255) << 8;
    this.pad[5] = key[26] & 255 | (key[27] & 255) << 8;
    this.pad[6] = key[28] & 255 | (key[29] & 255) << 8;
    this.pad[7] = key[30] & 255 | (key[31] & 255) << 8;
  }
  blocks(m4, mpos, bytes) {
    var hibit = this.fin ? 0 : 1 << 11;
    var t0, t1, t22, t32, t4, t5, t6, t7, c4;
    var d0, d1, d22, d32, d4, d5, d6, d7, d8, d9;
    var h0 = this.h[0], h1 = this.h[1], h22 = this.h[2], h32 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9];
    var r0 = this.r[0], r1 = this.r[1], r22 = this.r[2], r32 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9];
    while (bytes >= 16) {
      t0 = m4[mpos + 0] & 255 | (m4[mpos + 1] & 255) << 8;
      h0 += t0 & 8191;
      t1 = m4[mpos + 2] & 255 | (m4[mpos + 3] & 255) << 8;
      h1 += (t0 >>> 13 | t1 << 3) & 8191;
      t22 = m4[mpos + 4] & 255 | (m4[mpos + 5] & 255) << 8;
      h22 += (t1 >>> 10 | t22 << 6) & 8191;
      t32 = m4[mpos + 6] & 255 | (m4[mpos + 7] & 255) << 8;
      h32 += (t22 >>> 7 | t32 << 9) & 8191;
      t4 = m4[mpos + 8] & 255 | (m4[mpos + 9] & 255) << 8;
      h4 += (t32 >>> 4 | t4 << 12) & 8191;
      h5 += t4 >>> 1 & 8191;
      t5 = m4[mpos + 10] & 255 | (m4[mpos + 11] & 255) << 8;
      h6 += (t4 >>> 14 | t5 << 2) & 8191;
      t6 = m4[mpos + 12] & 255 | (m4[mpos + 13] & 255) << 8;
      h7 += (t5 >>> 11 | t6 << 5) & 8191;
      t7 = m4[mpos + 14] & 255 | (m4[mpos + 15] & 255) << 8;
      h8 += (t6 >>> 8 | t7 << 8) & 8191;
      h9 += t7 >>> 5 | hibit;
      c4 = 0;
      d0 = c4;
      d0 += h0 * r0;
      d0 += h1 * (5 * r9);
      d0 += h22 * (5 * r8);
      d0 += h32 * (5 * r7);
      d0 += h4 * (5 * r6);
      c4 = d0 >>> 13;
      d0 &= 8191;
      d0 += h5 * (5 * r5);
      d0 += h6 * (5 * r4);
      d0 += h7 * (5 * r32);
      d0 += h8 * (5 * r22);
      d0 += h9 * (5 * r1);
      c4 += d0 >>> 13;
      d0 &= 8191;
      d1 = c4;
      d1 += h0 * r1;
      d1 += h1 * r0;
      d1 += h22 * (5 * r9);
      d1 += h32 * (5 * r8);
      d1 += h4 * (5 * r7);
      c4 = d1 >>> 13;
      d1 &= 8191;
      d1 += h5 * (5 * r6);
      d1 += h6 * (5 * r5);
      d1 += h7 * (5 * r4);
      d1 += h8 * (5 * r32);
      d1 += h9 * (5 * r22);
      c4 += d1 >>> 13;
      d1 &= 8191;
      d22 = c4;
      d22 += h0 * r22;
      d22 += h1 * r1;
      d22 += h22 * r0;
      d22 += h32 * (5 * r9);
      d22 += h4 * (5 * r8);
      c4 = d22 >>> 13;
      d22 &= 8191;
      d22 += h5 * (5 * r7);
      d22 += h6 * (5 * r6);
      d22 += h7 * (5 * r5);
      d22 += h8 * (5 * r4);
      d22 += h9 * (5 * r32);
      c4 += d22 >>> 13;
      d22 &= 8191;
      d32 = c4;
      d32 += h0 * r32;
      d32 += h1 * r22;
      d32 += h22 * r1;
      d32 += h32 * r0;
      d32 += h4 * (5 * r9);
      c4 = d32 >>> 13;
      d32 &= 8191;
      d32 += h5 * (5 * r8);
      d32 += h6 * (5 * r7);
      d32 += h7 * (5 * r6);
      d32 += h8 * (5 * r5);
      d32 += h9 * (5 * r4);
      c4 += d32 >>> 13;
      d32 &= 8191;
      d4 = c4;
      d4 += h0 * r4;
      d4 += h1 * r32;
      d4 += h22 * r22;
      d4 += h32 * r1;
      d4 += h4 * r0;
      c4 = d4 >>> 13;
      d4 &= 8191;
      d4 += h5 * (5 * r9);
      d4 += h6 * (5 * r8);
      d4 += h7 * (5 * r7);
      d4 += h8 * (5 * r6);
      d4 += h9 * (5 * r5);
      c4 += d4 >>> 13;
      d4 &= 8191;
      d5 = c4;
      d5 += h0 * r5;
      d5 += h1 * r4;
      d5 += h22 * r32;
      d5 += h32 * r22;
      d5 += h4 * r1;
      c4 = d5 >>> 13;
      d5 &= 8191;
      d5 += h5 * r0;
      d5 += h6 * (5 * r9);
      d5 += h7 * (5 * r8);
      d5 += h8 * (5 * r7);
      d5 += h9 * (5 * r6);
      c4 += d5 >>> 13;
      d5 &= 8191;
      d6 = c4;
      d6 += h0 * r6;
      d6 += h1 * r5;
      d6 += h22 * r4;
      d6 += h32 * r32;
      d6 += h4 * r22;
      c4 = d6 >>> 13;
      d6 &= 8191;
      d6 += h5 * r1;
      d6 += h6 * r0;
      d6 += h7 * (5 * r9);
      d6 += h8 * (5 * r8);
      d6 += h9 * (5 * r7);
      c4 += d6 >>> 13;
      d6 &= 8191;
      d7 = c4;
      d7 += h0 * r7;
      d7 += h1 * r6;
      d7 += h22 * r5;
      d7 += h32 * r4;
      d7 += h4 * r32;
      c4 = d7 >>> 13;
      d7 &= 8191;
      d7 += h5 * r22;
      d7 += h6 * r1;
      d7 += h7 * r0;
      d7 += h8 * (5 * r9);
      d7 += h9 * (5 * r8);
      c4 += d7 >>> 13;
      d7 &= 8191;
      d8 = c4;
      d8 += h0 * r8;
      d8 += h1 * r7;
      d8 += h22 * r6;
      d8 += h32 * r5;
      d8 += h4 * r4;
      c4 = d8 >>> 13;
      d8 &= 8191;
      d8 += h5 * r32;
      d8 += h6 * r22;
      d8 += h7 * r1;
      d8 += h8 * r0;
      d8 += h9 * (5 * r9);
      c4 += d8 >>> 13;
      d8 &= 8191;
      d9 = c4;
      d9 += h0 * r9;
      d9 += h1 * r8;
      d9 += h22 * r7;
      d9 += h32 * r6;
      d9 += h4 * r5;
      c4 = d9 >>> 13;
      d9 &= 8191;
      d9 += h5 * r4;
      d9 += h6 * r32;
      d9 += h7 * r22;
      d9 += h8 * r1;
      d9 += h9 * r0;
      c4 += d9 >>> 13;
      d9 &= 8191;
      c4 = (c4 << 2) + c4 | 0;
      c4 = c4 + d0 | 0;
      d0 = c4 & 8191;
      c4 = c4 >>> 13;
      d1 += c4;
      h0 = d0;
      h1 = d1;
      h22 = d22;
      h32 = d32;
      h4 = d4;
      h5 = d5;
      h6 = d6;
      h7 = d7;
      h8 = d8;
      h9 = d9;
      mpos += 16;
      bytes -= 16;
    }
    this.h[0] = h0;
    this.h[1] = h1;
    this.h[2] = h22;
    this.h[3] = h32;
    this.h[4] = h4;
    this.h[5] = h5;
    this.h[6] = h6;
    this.h[7] = h7;
    this.h[8] = h8;
    this.h[9] = h9;
  }
  finish(mac, macpos) {
    var g4 = new Uint16Array(10);
    var c4, mask, f4, i4;
    if (this.leftover) {
      i4 = this.leftover;
      this.buffer[i4++] = 1;
      for (; i4 < 16; i4++)
        this.buffer[i4] = 0;
      this.fin = 1;
      this.blocks(this.buffer, 0, 16);
    }
    c4 = this.h[1] >>> 13;
    this.h[1] &= 8191;
    for (i4 = 2; i4 < 10; i4++) {
      this.h[i4] += c4;
      c4 = this.h[i4] >>> 13;
      this.h[i4] &= 8191;
    }
    this.h[0] += c4 * 5;
    c4 = this.h[0] >>> 13;
    this.h[0] &= 8191;
    this.h[1] += c4;
    c4 = this.h[1] >>> 13;
    this.h[1] &= 8191;
    this.h[2] += c4;
    g4[0] = this.h[0] + 5;
    c4 = g4[0] >>> 13;
    g4[0] &= 8191;
    for (i4 = 1; i4 < 10; i4++) {
      g4[i4] = this.h[i4] + c4;
      c4 = g4[i4] >>> 13;
      g4[i4] &= 8191;
    }
    g4[9] -= 1 << 13;
    mask = (c4 ^ 1) - 1;
    for (i4 = 0; i4 < 10; i4++)
      g4[i4] &= mask;
    mask = ~mask;
    for (i4 = 0; i4 < 10; i4++)
      this.h[i4] = this.h[i4] & mask | g4[i4];
    this.h[0] = (this.h[0] | this.h[1] << 13) & 65535;
    this.h[1] = (this.h[1] >>> 3 | this.h[2] << 10) & 65535;
    this.h[2] = (this.h[2] >>> 6 | this.h[3] << 7) & 65535;
    this.h[3] = (this.h[3] >>> 9 | this.h[4] << 4) & 65535;
    this.h[4] = (this.h[4] >>> 12 | this.h[5] << 1 | this.h[6] << 14) & 65535;
    this.h[5] = (this.h[6] >>> 2 | this.h[7] << 11) & 65535;
    this.h[6] = (this.h[7] >>> 5 | this.h[8] << 8) & 65535;
    this.h[7] = (this.h[8] >>> 8 | this.h[9] << 5) & 65535;
    f4 = this.h[0] + this.pad[0];
    this.h[0] = f4 & 65535;
    for (i4 = 1; i4 < 8; i4++) {
      f4 = (this.h[i4] + this.pad[i4] | 0) + (f4 >>> 16) | 0;
      this.h[i4] = f4 & 65535;
    }
    mac[macpos + 0] = this.h[0] >>> 0 & 255;
    mac[macpos + 1] = this.h[0] >>> 8 & 255;
    mac[macpos + 2] = this.h[1] >>> 0 & 255;
    mac[macpos + 3] = this.h[1] >>> 8 & 255;
    mac[macpos + 4] = this.h[2] >>> 0 & 255;
    mac[macpos + 5] = this.h[2] >>> 8 & 255;
    mac[macpos + 6] = this.h[3] >>> 0 & 255;
    mac[macpos + 7] = this.h[3] >>> 8 & 255;
    mac[macpos + 8] = this.h[4] >>> 0 & 255;
    mac[macpos + 9] = this.h[4] >>> 8 & 255;
    mac[macpos + 10] = this.h[5] >>> 0 & 255;
    mac[macpos + 11] = this.h[5] >>> 8 & 255;
    mac[macpos + 12] = this.h[6] >>> 0 & 255;
    mac[macpos + 13] = this.h[6] >>> 8 & 255;
    mac[macpos + 14] = this.h[7] >>> 0 & 255;
    mac[macpos + 15] = this.h[7] >>> 8 & 255;
  }
  update(m4, mpos, bytes) {
    let i4;
    let want;
    if (this.leftover) {
      want = 16 - this.leftover;
      if (want > bytes)
        want = bytes;
      for (i4 = 0; i4 < want; i4++)
        this.buffer[this.leftover + i4] = m4[mpos + i4];
      bytes -= want;
      mpos += want;
      this.leftover += want;
      if (this.leftover < 16)
        return;
      this.blocks(this.buffer, 0, 16);
      this.leftover = 0;
    }
    if (bytes >= 16) {
      want = bytes - bytes % 16;
      this.blocks(m4, mpos, want);
      mpos += want;
      bytes -= want;
    }
    if (bytes) {
      for (i4 = 0; i4 < bytes; i4++)
        this.buffer[this.leftover + i4] = m4[mpos + i4];
      this.leftover += bytes;
    }
  }
};
function crypto_onetimeauth(out, outpos, m4, mpos, n3, k4) {
  var s4 = new poly1305(k4);
  s4.update(m4, mpos, n3);
  s4.finish(out, outpos);
  return 0;
}
function crypto_onetimeauth_verify(h4, hpos, m4, mpos, n3, k4) {
  var x3 = new Uint8Array(16);
  crypto_onetimeauth(x3, 0, m4, mpos, n3, k4);
  return crypto_verify_16(h4, hpos, x3, 0);
}
function crypto_secretbox(c4, m4, d4, n3, k4) {
  var i4;
  if (d4 < 32)
    return -1;
  crypto_stream_xor(c4, 0, m4, 0, d4, n3, k4);
  crypto_onetimeauth(c4, 16, c4, 32, d4 - 32, c4);
  for (i4 = 0; i4 < 16; i4++)
    c4[i4] = 0;
  return 0;
}
function crypto_secretbox_open(m4, c4, d4, n3, k4) {
  var i4;
  var x3 = new Uint8Array(32);
  if (d4 < 32)
    return -1;
  crypto_stream(x3, 0, 32, n3, k4);
  if (crypto_onetimeauth_verify(c4, 16, c4, 32, d4 - 32, x3) !== 0)
    return -1;
  crypto_stream_xor(m4, 0, c4, 0, d4, n3, k4);
  for (i4 = 0; i4 < 32; i4++)
    m4[i4] = 0;
  return 0;
}
function set25519(r4, a4) {
  let i4;
  for (i4 = 0; i4 < 16; i4++)
    r4[i4] = a4[i4] | 0;
}
function car25519(o4) {
  let i4, v4, c4 = 1;
  for (i4 = 0; i4 < 16; i4++) {
    v4 = o4[i4] + c4 + 65535;
    c4 = Math.floor(v4 / 65536);
    o4[i4] = v4 - c4 * 65536;
  }
  o4[0] += c4 - 1 + 37 * (c4 - 1);
}
function sel25519(p5, q4, b4) {
  let t4;
  const c4 = ~(b4 - 1);
  for (let i4 = 0; i4 < 16; i4++) {
    t4 = c4 & (p5[i4] ^ q4[i4]);
    p5[i4] ^= t4;
    q4[i4] ^= t4;
  }
}
function pack25519(o4, n3) {
  let i4, j4, b4;
  const m4 = gf(), t4 = gf();
  for (i4 = 0; i4 < 16; i4++)
    t4[i4] = n3[i4];
  car25519(t4);
  car25519(t4);
  car25519(t4);
  for (j4 = 0; j4 < 2; j4++) {
    m4[0] = t4[0] - 65517;
    for (i4 = 1; i4 < 15; i4++) {
      m4[i4] = t4[i4] - 65535 - (m4[i4 - 1] >> 16 & 1);
      m4[i4 - 1] &= 65535;
    }
    m4[15] = t4[15] - 32767 - (m4[14] >> 16 & 1);
    b4 = m4[15] >> 16 & 1;
    m4[14] &= 65535;
    sel25519(t4, m4, 1 - b4);
  }
  for (i4 = 0; i4 < 16; i4++) {
    o4[2 * i4] = t4[i4] & 255;
    o4[2 * i4 + 1] = t4[i4] >> 8;
  }
}
function neq25519(a4, b4) {
  const c4 = new Uint8Array(32), d4 = new Uint8Array(32);
  pack25519(c4, a4);
  pack25519(d4, b4);
  return crypto_verify_32(c4, 0, d4, 0);
}
function par25519(a4) {
  const d4 = new Uint8Array(32);
  pack25519(d4, a4);
  return d4[0] & 1;
}
function unpack25519(o4, n3) {
  let i4;
  for (i4 = 0; i4 < 16; i4++)
    o4[i4] = n3[2 * i4] + (n3[2 * i4 + 1] << 8);
  o4[15] &= 32767;
}
function A2(o4, a4, b4) {
  for (let i4 = 0; i4 < 16; i4++)
    o4[i4] = a4[i4] + b4[i4];
}
function Z(o4, a4, b4) {
  for (let i4 = 0; i4 < 16; i4++)
    o4[i4] = a4[i4] - b4[i4];
}
function M2(o4, a4, b4) {
  let v4, c4, t0 = 0, t1 = 0, t22 = 0, t32 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t222 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0;
  const b0 = b4[0], b1 = b4[1], b22 = b4[2], b32 = b4[3], b42 = b4[4], b5 = b4[5], b6 = b4[6], b7 = b4[7], b8 = b4[8], b9 = b4[9], b10 = b4[10], b11 = b4[11], b12 = b4[12], b13 = b4[13], b14 = b4[14], b15 = b4[15];
  v4 = a4[0];
  t0 += v4 * b0;
  t1 += v4 * b1;
  t22 += v4 * b22;
  t32 += v4 * b32;
  t4 += v4 * b42;
  t5 += v4 * b5;
  t6 += v4 * b6;
  t7 += v4 * b7;
  t8 += v4 * b8;
  t9 += v4 * b9;
  t10 += v4 * b10;
  t11 += v4 * b11;
  t12 += v4 * b12;
  t13 += v4 * b13;
  t14 += v4 * b14;
  t15 += v4 * b15;
  v4 = a4[1];
  t1 += v4 * b0;
  t22 += v4 * b1;
  t32 += v4 * b22;
  t4 += v4 * b32;
  t5 += v4 * b42;
  t6 += v4 * b5;
  t7 += v4 * b6;
  t8 += v4 * b7;
  t9 += v4 * b8;
  t10 += v4 * b9;
  t11 += v4 * b10;
  t12 += v4 * b11;
  t13 += v4 * b12;
  t14 += v4 * b13;
  t15 += v4 * b14;
  t16 += v4 * b15;
  v4 = a4[2];
  t22 += v4 * b0;
  t32 += v4 * b1;
  t4 += v4 * b22;
  t5 += v4 * b32;
  t6 += v4 * b42;
  t7 += v4 * b5;
  t8 += v4 * b6;
  t9 += v4 * b7;
  t10 += v4 * b8;
  t11 += v4 * b9;
  t12 += v4 * b10;
  t13 += v4 * b11;
  t14 += v4 * b12;
  t15 += v4 * b13;
  t16 += v4 * b14;
  t17 += v4 * b15;
  v4 = a4[3];
  t32 += v4 * b0;
  t4 += v4 * b1;
  t5 += v4 * b22;
  t6 += v4 * b32;
  t7 += v4 * b42;
  t8 += v4 * b5;
  t9 += v4 * b6;
  t10 += v4 * b7;
  t11 += v4 * b8;
  t12 += v4 * b9;
  t13 += v4 * b10;
  t14 += v4 * b11;
  t15 += v4 * b12;
  t16 += v4 * b13;
  t17 += v4 * b14;
  t18 += v4 * b15;
  v4 = a4[4];
  t4 += v4 * b0;
  t5 += v4 * b1;
  t6 += v4 * b22;
  t7 += v4 * b32;
  t8 += v4 * b42;
  t9 += v4 * b5;
  t10 += v4 * b6;
  t11 += v4 * b7;
  t12 += v4 * b8;
  t13 += v4 * b9;
  t14 += v4 * b10;
  t15 += v4 * b11;
  t16 += v4 * b12;
  t17 += v4 * b13;
  t18 += v4 * b14;
  t19 += v4 * b15;
  v4 = a4[5];
  t5 += v4 * b0;
  t6 += v4 * b1;
  t7 += v4 * b22;
  t8 += v4 * b32;
  t9 += v4 * b42;
  t10 += v4 * b5;
  t11 += v4 * b6;
  t12 += v4 * b7;
  t13 += v4 * b8;
  t14 += v4 * b9;
  t15 += v4 * b10;
  t16 += v4 * b11;
  t17 += v4 * b12;
  t18 += v4 * b13;
  t19 += v4 * b14;
  t20 += v4 * b15;
  v4 = a4[6];
  t6 += v4 * b0;
  t7 += v4 * b1;
  t8 += v4 * b22;
  t9 += v4 * b32;
  t10 += v4 * b42;
  t11 += v4 * b5;
  t12 += v4 * b6;
  t13 += v4 * b7;
  t14 += v4 * b8;
  t15 += v4 * b9;
  t16 += v4 * b10;
  t17 += v4 * b11;
  t18 += v4 * b12;
  t19 += v4 * b13;
  t20 += v4 * b14;
  t21 += v4 * b15;
  v4 = a4[7];
  t7 += v4 * b0;
  t8 += v4 * b1;
  t9 += v4 * b22;
  t10 += v4 * b32;
  t11 += v4 * b42;
  t12 += v4 * b5;
  t13 += v4 * b6;
  t14 += v4 * b7;
  t15 += v4 * b8;
  t16 += v4 * b9;
  t17 += v4 * b10;
  t18 += v4 * b11;
  t19 += v4 * b12;
  t20 += v4 * b13;
  t21 += v4 * b14;
  t222 += v4 * b15;
  v4 = a4[8];
  t8 += v4 * b0;
  t9 += v4 * b1;
  t10 += v4 * b22;
  t11 += v4 * b32;
  t12 += v4 * b42;
  t13 += v4 * b5;
  t14 += v4 * b6;
  t15 += v4 * b7;
  t16 += v4 * b8;
  t17 += v4 * b9;
  t18 += v4 * b10;
  t19 += v4 * b11;
  t20 += v4 * b12;
  t21 += v4 * b13;
  t222 += v4 * b14;
  t23 += v4 * b15;
  v4 = a4[9];
  t9 += v4 * b0;
  t10 += v4 * b1;
  t11 += v4 * b22;
  t12 += v4 * b32;
  t13 += v4 * b42;
  t14 += v4 * b5;
  t15 += v4 * b6;
  t16 += v4 * b7;
  t17 += v4 * b8;
  t18 += v4 * b9;
  t19 += v4 * b10;
  t20 += v4 * b11;
  t21 += v4 * b12;
  t222 += v4 * b13;
  t23 += v4 * b14;
  t24 += v4 * b15;
  v4 = a4[10];
  t10 += v4 * b0;
  t11 += v4 * b1;
  t12 += v4 * b22;
  t13 += v4 * b32;
  t14 += v4 * b42;
  t15 += v4 * b5;
  t16 += v4 * b6;
  t17 += v4 * b7;
  t18 += v4 * b8;
  t19 += v4 * b9;
  t20 += v4 * b10;
  t21 += v4 * b11;
  t222 += v4 * b12;
  t23 += v4 * b13;
  t24 += v4 * b14;
  t25 += v4 * b15;
  v4 = a4[11];
  t11 += v4 * b0;
  t12 += v4 * b1;
  t13 += v4 * b22;
  t14 += v4 * b32;
  t15 += v4 * b42;
  t16 += v4 * b5;
  t17 += v4 * b6;
  t18 += v4 * b7;
  t19 += v4 * b8;
  t20 += v4 * b9;
  t21 += v4 * b10;
  t222 += v4 * b11;
  t23 += v4 * b12;
  t24 += v4 * b13;
  t25 += v4 * b14;
  t26 += v4 * b15;
  v4 = a4[12];
  t12 += v4 * b0;
  t13 += v4 * b1;
  t14 += v4 * b22;
  t15 += v4 * b32;
  t16 += v4 * b42;
  t17 += v4 * b5;
  t18 += v4 * b6;
  t19 += v4 * b7;
  t20 += v4 * b8;
  t21 += v4 * b9;
  t222 += v4 * b10;
  t23 += v4 * b11;
  t24 += v4 * b12;
  t25 += v4 * b13;
  t26 += v4 * b14;
  t27 += v4 * b15;
  v4 = a4[13];
  t13 += v4 * b0;
  t14 += v4 * b1;
  t15 += v4 * b22;
  t16 += v4 * b32;
  t17 += v4 * b42;
  t18 += v4 * b5;
  t19 += v4 * b6;
  t20 += v4 * b7;
  t21 += v4 * b8;
  t222 += v4 * b9;
  t23 += v4 * b10;
  t24 += v4 * b11;
  t25 += v4 * b12;
  t26 += v4 * b13;
  t27 += v4 * b14;
  t28 += v4 * b15;
  v4 = a4[14];
  t14 += v4 * b0;
  t15 += v4 * b1;
  t16 += v4 * b22;
  t17 += v4 * b32;
  t18 += v4 * b42;
  t19 += v4 * b5;
  t20 += v4 * b6;
  t21 += v4 * b7;
  t222 += v4 * b8;
  t23 += v4 * b9;
  t24 += v4 * b10;
  t25 += v4 * b11;
  t26 += v4 * b12;
  t27 += v4 * b13;
  t28 += v4 * b14;
  t29 += v4 * b15;
  v4 = a4[15];
  t15 += v4 * b0;
  t16 += v4 * b1;
  t17 += v4 * b22;
  t18 += v4 * b32;
  t19 += v4 * b42;
  t20 += v4 * b5;
  t21 += v4 * b6;
  t222 += v4 * b7;
  t23 += v4 * b8;
  t24 += v4 * b9;
  t25 += v4 * b10;
  t26 += v4 * b11;
  t27 += v4 * b12;
  t28 += v4 * b13;
  t29 += v4 * b14;
  t30 += v4 * b15;
  t0 += 38 * t16;
  t1 += 38 * t17;
  t22 += 38 * t18;
  t32 += 38 * t19;
  t4 += 38 * t20;
  t5 += 38 * t21;
  t6 += 38 * t222;
  t7 += 38 * t23;
  t8 += 38 * t24;
  t9 += 38 * t25;
  t10 += 38 * t26;
  t11 += 38 * t27;
  t12 += 38 * t28;
  t13 += 38 * t29;
  t14 += 38 * t30;
  c4 = 1;
  v4 = t0 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t0 = v4 - c4 * 65536;
  v4 = t1 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t1 = v4 - c4 * 65536;
  v4 = t22 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t22 = v4 - c4 * 65536;
  v4 = t32 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t32 = v4 - c4 * 65536;
  v4 = t4 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t4 = v4 - c4 * 65536;
  v4 = t5 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t5 = v4 - c4 * 65536;
  v4 = t6 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t6 = v4 - c4 * 65536;
  v4 = t7 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t7 = v4 - c4 * 65536;
  v4 = t8 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t8 = v4 - c4 * 65536;
  v4 = t9 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t9 = v4 - c4 * 65536;
  v4 = t10 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t10 = v4 - c4 * 65536;
  v4 = t11 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t11 = v4 - c4 * 65536;
  v4 = t12 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t12 = v4 - c4 * 65536;
  v4 = t13 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t13 = v4 - c4 * 65536;
  v4 = t14 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t14 = v4 - c4 * 65536;
  v4 = t15 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t15 = v4 - c4 * 65536;
  t0 += c4 - 1 + 37 * (c4 - 1);
  c4 = 1;
  v4 = t0 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t0 = v4 - c4 * 65536;
  v4 = t1 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t1 = v4 - c4 * 65536;
  v4 = t22 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t22 = v4 - c4 * 65536;
  v4 = t32 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t32 = v4 - c4 * 65536;
  v4 = t4 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t4 = v4 - c4 * 65536;
  v4 = t5 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t5 = v4 - c4 * 65536;
  v4 = t6 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t6 = v4 - c4 * 65536;
  v4 = t7 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t7 = v4 - c4 * 65536;
  v4 = t8 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t8 = v4 - c4 * 65536;
  v4 = t9 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t9 = v4 - c4 * 65536;
  v4 = t10 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t10 = v4 - c4 * 65536;
  v4 = t11 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t11 = v4 - c4 * 65536;
  v4 = t12 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t12 = v4 - c4 * 65536;
  v4 = t13 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t13 = v4 - c4 * 65536;
  v4 = t14 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t14 = v4 - c4 * 65536;
  v4 = t15 + c4 + 65535;
  c4 = Math.floor(v4 / 65536);
  t15 = v4 - c4 * 65536;
  t0 += c4 - 1 + 37 * (c4 - 1);
  o4[0] = t0;
  o4[1] = t1;
  o4[2] = t22;
  o4[3] = t32;
  o4[4] = t4;
  o4[5] = t5;
  o4[6] = t6;
  o4[7] = t7;
  o4[8] = t8;
  o4[9] = t9;
  o4[10] = t10;
  o4[11] = t11;
  o4[12] = t12;
  o4[13] = t13;
  o4[14] = t14;
  o4[15] = t15;
}
function S2(o4, a4) {
  M2(o4, a4, a4);
}
function inv25519(o4, i4) {
  const c4 = gf();
  let a4;
  for (a4 = 0; a4 < 16; a4++)
    c4[a4] = i4[a4];
  for (a4 = 253; a4 >= 0; a4--) {
    S2(c4, c4);
    if (a4 !== 2 && a4 !== 4)
      M2(c4, c4, i4);
  }
  for (a4 = 0; a4 < 16; a4++)
    o4[a4] = c4[a4];
}
function pow2523(o4, i4) {
  const c4 = gf();
  let a4;
  for (a4 = 0; a4 < 16; a4++)
    c4[a4] = i4[a4];
  for (a4 = 250; a4 >= 0; a4--) {
    S2(c4, c4);
    if (a4 !== 1)
      M2(c4, c4, i4);
  }
  for (a4 = 0; a4 < 16; a4++)
    o4[a4] = c4[a4];
}
var K = [
  1116352408,
  3609767458,
  1899447441,
  602891725,
  3049323471,
  3964484399,
  3921009573,
  2173295548,
  961987163,
  4081628472,
  1508970993,
  3053834265,
  2453635748,
  2937671579,
  2870763221,
  3664609560,
  3624381080,
  2734883394,
  310598401,
  1164996542,
  607225278,
  1323610764,
  1426881987,
  3590304994,
  1925078388,
  4068182383,
  2162078206,
  991336113,
  2614888103,
  633803317,
  3248222580,
  3479774868,
  3835390401,
  2666613458,
  4022224774,
  944711139,
  264347078,
  2341262773,
  604807628,
  2007800933,
  770255983,
  1495990901,
  1249150122,
  1856431235,
  1555081692,
  3175218132,
  1996064986,
  2198950837,
  2554220882,
  3999719339,
  2821834349,
  766784016,
  2952996808,
  2566594879,
  3210313671,
  3203337956,
  3336571891,
  1034457026,
  3584528711,
  2466948901,
  113926993,
  3758326383,
  338241895,
  168717936,
  666307205,
  1188179964,
  773529912,
  1546045734,
  1294757372,
  1522805485,
  1396182291,
  2643833823,
  1695183700,
  2343527390,
  1986661051,
  1014477480,
  2177026350,
  1206759142,
  2456956037,
  344077627,
  2730485921,
  1290863460,
  2820302411,
  3158454273,
  3259730800,
  3505952657,
  3345764771,
  106217008,
  3516065817,
  3606008344,
  3600352804,
  1432725776,
  4094571909,
  1467031594,
  275423344,
  851169720,
  430227734,
  3100823752,
  506948616,
  1363258195,
  659060556,
  3750685593,
  883997877,
  3785050280,
  958139571,
  3318307427,
  1322822218,
  3812723403,
  1537002063,
  2003034995,
  1747873779,
  3602036899,
  1955562222,
  1575990012,
  2024104815,
  1125592928,
  2227730452,
  2716904306,
  2361852424,
  442776044,
  2428436474,
  593698344,
  2756734187,
  3733110249,
  3204031479,
  2999351573,
  3329325298,
  3815920427,
  3391569614,
  3928383900,
  3515267271,
  566280711,
  3940187606,
  3454069534,
  4118630271,
  4000239992,
  116418474,
  1914138554,
  174292421,
  2731055270,
  289380356,
  3203993006,
  460393269,
  320620315,
  685471733,
  587496836,
  852142971,
  1086792851,
  1017036298,
  365543100,
  1126000580,
  2618297676,
  1288033470,
  3409855158,
  1501505948,
  4234509866,
  1607167915,
  987167468,
  1816402316,
  1246189591
];
function crypto_hashblocks_hl(hh, hl, m4, n3) {
  const wh = new Int32Array(16), wl = new Int32Array(16);
  let bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i4, j4, h4, l4, a4, b4, c4, d4;
  let ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7];
  let pos = 0;
  while (n3 >= 128) {
    for (i4 = 0; i4 < 16; i4++) {
      j4 = 8 * i4 + pos;
      wh[i4] = m4[j4 + 0] << 24 | m4[j4 + 1] << 16 | m4[j4 + 2] << 8 | m4[j4 + 3];
      wl[i4] = m4[j4 + 4] << 24 | m4[j4 + 5] << 16 | m4[j4 + 6] << 8 | m4[j4 + 7];
    }
    for (i4 = 0; i4 < 80; i4++) {
      bh0 = ah0;
      bh1 = ah1;
      bh2 = ah2;
      bh3 = ah3;
      bh4 = ah4;
      bh5 = ah5;
      bh6 = ah6;
      bh7 = ah7;
      bl0 = al0;
      bl1 = al1;
      bl2 = al2;
      bl3 = al3;
      bl4 = al4;
      bl5 = al5;
      bl6 = al6;
      bl7 = al7;
      h4 = ah7;
      l4 = al7;
      a4 = l4 & 65535;
      b4 = l4 >>> 16;
      c4 = h4 & 65535;
      d4 = h4 >>> 16;
      h4 = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32));
      l4 = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32));
      a4 += l4 & 65535;
      b4 += l4 >>> 16;
      c4 += h4 & 65535;
      d4 += h4 >>> 16;
      h4 = ah4 & ah5 ^ ~ah4 & ah6;
      l4 = al4 & al5 ^ ~al4 & al6;
      a4 += l4 & 65535;
      b4 += l4 >>> 16;
      c4 += h4 & 65535;
      d4 += h4 >>> 16;
      h4 = K[i4 * 2];
      l4 = K[i4 * 2 + 1];
      a4 += l4 & 65535;
      b4 += l4 >>> 16;
      c4 += h4 & 65535;
      d4 += h4 >>> 16;
      h4 = wh[i4 % 16];
      l4 = wl[i4 % 16];
      a4 += l4 & 65535;
      b4 += l4 >>> 16;
      c4 += h4 & 65535;
      d4 += h4 >>> 16;
      b4 += a4 >>> 16;
      c4 += b4 >>> 16;
      d4 += c4 >>> 16;
      th = c4 & 65535 | d4 << 16;
      tl = a4 & 65535 | b4 << 16;
      h4 = th;
      l4 = tl;
      a4 = l4 & 65535;
      b4 = l4 >>> 16;
      c4 = h4 & 65535;
      d4 = h4 >>> 16;
      h4 = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32));
      l4 = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32));
      a4 += l4 & 65535;
      b4 += l4 >>> 16;
      c4 += h4 & 65535;
      d4 += h4 >>> 16;
      h4 = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2;
      l4 = al0 & al1 ^ al0 & al2 ^ al1 & al2;
      a4 += l4 & 65535;
      b4 += l4 >>> 16;
      c4 += h4 & 65535;
      d4 += h4 >>> 16;
      b4 += a4 >>> 16;
      c4 += b4 >>> 16;
      d4 += c4 >>> 16;
      bh7 = c4 & 65535 | d4 << 16;
      bl7 = a4 & 65535 | b4 << 16;
      h4 = bh3;
      l4 = bl3;
      a4 = l4 & 65535;
      b4 = l4 >>> 16;
      c4 = h4 & 65535;
      d4 = h4 >>> 16;
      h4 = th;
      l4 = tl;
      a4 += l4 & 65535;
      b4 += l4 >>> 16;
      c4 += h4 & 65535;
      d4 += h4 >>> 16;
      b4 += a4 >>> 16;
      c4 += b4 >>> 16;
      d4 += c4 >>> 16;
      bh3 = c4 & 65535 | d4 << 16;
      bl3 = a4 & 65535 | b4 << 16;
      ah1 = bh0;
      ah2 = bh1;
      ah3 = bh2;
      ah4 = bh3;
      ah5 = bh4;
      ah6 = bh5;
      ah7 = bh6;
      ah0 = bh7;
      al1 = bl0;
      al2 = bl1;
      al3 = bl2;
      al4 = bl3;
      al5 = bl4;
      al6 = bl5;
      al7 = bl6;
      al0 = bl7;
      if (i4 % 16 === 15) {
        for (j4 = 0; j4 < 16; j4++) {
          h4 = wh[j4];
          l4 = wl[j4];
          a4 = l4 & 65535;
          b4 = l4 >>> 16;
          c4 = h4 & 65535;
          d4 = h4 >>> 16;
          h4 = wh[(j4 + 9) % 16];
          l4 = wl[(j4 + 9) % 16];
          a4 += l4 & 65535;
          b4 += l4 >>> 16;
          c4 += h4 & 65535;
          d4 += h4 >>> 16;
          th = wh[(j4 + 1) % 16];
          tl = wl[(j4 + 1) % 16];
          h4 = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7;
          l4 = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7);
          a4 += l4 & 65535;
          b4 += l4 >>> 16;
          c4 += h4 & 65535;
          d4 += h4 >>> 16;
          th = wh[(j4 + 14) % 16];
          tl = wl[(j4 + 14) % 16];
          h4 = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6;
          l4 = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6);
          a4 += l4 & 65535;
          b4 += l4 >>> 16;
          c4 += h4 & 65535;
          d4 += h4 >>> 16;
          b4 += a4 >>> 16;
          c4 += b4 >>> 16;
          d4 += c4 >>> 16;
          wh[j4] = c4 & 65535 | d4 << 16;
          wl[j4] = a4 & 65535 | b4 << 16;
        }
      }
    }
    h4 = ah0;
    l4 = al0;
    a4 = l4 & 65535;
    b4 = l4 >>> 16;
    c4 = h4 & 65535;
    d4 = h4 >>> 16;
    h4 = hh[0];
    l4 = hl[0];
    a4 += l4 & 65535;
    b4 += l4 >>> 16;
    c4 += h4 & 65535;
    d4 += h4 >>> 16;
    b4 += a4 >>> 16;
    c4 += b4 >>> 16;
    d4 += c4 >>> 16;
    hh[0] = ah0 = c4 & 65535 | d4 << 16;
    hl[0] = al0 = a4 & 65535 | b4 << 16;
    h4 = ah1;
    l4 = al1;
    a4 = l4 & 65535;
    b4 = l4 >>> 16;
    c4 = h4 & 65535;
    d4 = h4 >>> 16;
    h4 = hh[1];
    l4 = hl[1];
    a4 += l4 & 65535;
    b4 += l4 >>> 16;
    c4 += h4 & 65535;
    d4 += h4 >>> 16;
    b4 += a4 >>> 16;
    c4 += b4 >>> 16;
    d4 += c4 >>> 16;
    hh[1] = ah1 = c4 & 65535 | d4 << 16;
    hl[1] = al1 = a4 & 65535 | b4 << 16;
    h4 = ah2;
    l4 = al2;
    a4 = l4 & 65535;
    b4 = l4 >>> 16;
    c4 = h4 & 65535;
    d4 = h4 >>> 16;
    h4 = hh[2];
    l4 = hl[2];
    a4 += l4 & 65535;
    b4 += l4 >>> 16;
    c4 += h4 & 65535;
    d4 += h4 >>> 16;
    b4 += a4 >>> 16;
    c4 += b4 >>> 16;
    d4 += c4 >>> 16;
    hh[2] = ah2 = c4 & 65535 | d4 << 16;
    hl[2] = al2 = a4 & 65535 | b4 << 16;
    h4 = ah3;
    l4 = al3;
    a4 = l4 & 65535;
    b4 = l4 >>> 16;
    c4 = h4 & 65535;
    d4 = h4 >>> 16;
    h4 = hh[3];
    l4 = hl[3];
    a4 += l4 & 65535;
    b4 += l4 >>> 16;
    c4 += h4 & 65535;
    d4 += h4 >>> 16;
    b4 += a4 >>> 16;
    c4 += b4 >>> 16;
    d4 += c4 >>> 16;
    hh[3] = ah3 = c4 & 65535 | d4 << 16;
    hl[3] = al3 = a4 & 65535 | b4 << 16;
    h4 = ah4;
    l4 = al4;
    a4 = l4 & 65535;
    b4 = l4 >>> 16;
    c4 = h4 & 65535;
    d4 = h4 >>> 16;
    h4 = hh[4];
    l4 = hl[4];
    a4 += l4 & 65535;
    b4 += l4 >>> 16;
    c4 += h4 & 65535;
    d4 += h4 >>> 16;
    b4 += a4 >>> 16;
    c4 += b4 >>> 16;
    d4 += c4 >>> 16;
    hh[4] = ah4 = c4 & 65535 | d4 << 16;
    hl[4] = al4 = a4 & 65535 | b4 << 16;
    h4 = ah5;
    l4 = al5;
    a4 = l4 & 65535;
    b4 = l4 >>> 16;
    c4 = h4 & 65535;
    d4 = h4 >>> 16;
    h4 = hh[5];
    l4 = hl[5];
    a4 += l4 & 65535;
    b4 += l4 >>> 16;
    c4 += h4 & 65535;
    d4 += h4 >>> 16;
    b4 += a4 >>> 16;
    c4 += b4 >>> 16;
    d4 += c4 >>> 16;
    hh[5] = ah5 = c4 & 65535 | d4 << 16;
    hl[5] = al5 = a4 & 65535 | b4 << 16;
    h4 = ah6;
    l4 = al6;
    a4 = l4 & 65535;
    b4 = l4 >>> 16;
    c4 = h4 & 65535;
    d4 = h4 >>> 16;
    h4 = hh[6];
    l4 = hl[6];
    a4 += l4 & 65535;
    b4 += l4 >>> 16;
    c4 += h4 & 65535;
    d4 += h4 >>> 16;
    b4 += a4 >>> 16;
    c4 += b4 >>> 16;
    d4 += c4 >>> 16;
    hh[6] = ah6 = c4 & 65535 | d4 << 16;
    hl[6] = al6 = a4 & 65535 | b4 << 16;
    h4 = ah7;
    l4 = al7;
    a4 = l4 & 65535;
    b4 = l4 >>> 16;
    c4 = h4 & 65535;
    d4 = h4 >>> 16;
    h4 = hh[7];
    l4 = hl[7];
    a4 += l4 & 65535;
    b4 += l4 >>> 16;
    c4 += h4 & 65535;
    d4 += h4 >>> 16;
    b4 += a4 >>> 16;
    c4 += b4 >>> 16;
    d4 += c4 >>> 16;
    hh[7] = ah7 = c4 & 65535 | d4 << 16;
    hl[7] = al7 = a4 & 65535 | b4 << 16;
    pos += 128;
    n3 -= 128;
  }
  return n3;
}
function crypto_hash(out, m4, n3) {
  const hh = new Int32Array(8);
  const hl = new Int32Array(8);
  const x3 = new Uint8Array(256);
  const b4 = n3;
  hh[0] = 1779033703;
  hh[1] = 3144134277;
  hh[2] = 1013904242;
  hh[3] = 2773480762;
  hh[4] = 1359893119;
  hh[5] = 2600822924;
  hh[6] = 528734635;
  hh[7] = 1541459225;
  hl[0] = 4089235720;
  hl[1] = 2227873595;
  hl[2] = 4271175723;
  hl[3] = 1595750129;
  hl[4] = 2917565137;
  hl[5] = 725511199;
  hl[6] = 4215389547;
  hl[7] = 327033209;
  crypto_hashblocks_hl(hh, hl, m4, n3);
  n3 %= 128;
  for (let i4 = 0; i4 < n3; i4++)
    x3[i4] = m4[b4 - n3 + i4];
  x3[n3] = 128;
  n3 = 256 - 128 * (n3 < 112 ? 1 : 0);
  x3[n3 - 9] = 0;
  ts64(x3, n3 - 8, b4 / 536870912 | 0, b4 << 3);
  crypto_hashblocks_hl(hh, hl, x3, n3);
  for (let i4 = 0; i4 < 8; i4++)
    ts64(out, 8 * i4, hh[i4], hl[i4]);
  return 0;
}
var HashState = class {
  constructor() {
    this.hh = new Int32Array(8);
    this.hl = new Int32Array(8);
    this.next = new Uint8Array(128);
    this.p = 0;
    this.total = 0;
    this.hh[0] = 1779033703;
    this.hh[1] = 3144134277;
    this.hh[2] = 1013904242;
    this.hh[3] = 2773480762;
    this.hh[4] = 1359893119;
    this.hh[5] = 2600822924;
    this.hh[6] = 528734635;
    this.hh[7] = 1541459225;
    this.hl[0] = 4089235720;
    this.hl[1] = 2227873595;
    this.hl[2] = 4271175723;
    this.hl[3] = 1595750129;
    this.hl[4] = 2917565137;
    this.hl[5] = 725511199;
    this.hl[6] = 4215389547;
    this.hl[7] = 327033209;
  }
  update(data) {
    this.total += data.length;
    let i4 = 0;
    while (i4 < data.length) {
      const r4 = 128 - this.p;
      if (r4 > data.length - i4) {
        for (let j4 = 0; i4 + j4 < data.length; j4++) {
          this.next[this.p + j4] = data[i4 + j4];
        }
        this.p += data.length - i4;
        break;
      } else {
        for (let j4 = 0; this.p + j4 < 128; j4++) {
          this.next[this.p + j4] = data[i4 + j4];
        }
        crypto_hashblocks_hl(this.hh, this.hl, this.next, 128);
        i4 += 128 - this.p;
        this.p = 0;
      }
    }
    return this;
  }
  finish() {
    const out = new Uint8Array(64);
    let n3 = this.p;
    const x3 = new Uint8Array(256);
    const b4 = this.total;
    for (let i4 = 0; i4 < n3; i4++)
      x3[i4] = this.next[i4];
    x3[n3] = 128;
    n3 = 256 - 128 * (n3 < 112 ? 1 : 0);
    x3[n3 - 9] = 0;
    ts64(x3, n3 - 8, b4 / 536870912 | 0, b4 << 3);
    crypto_hashblocks_hl(this.hh, this.hl, x3, n3);
    for (let i4 = 0; i4 < 8; i4++)
      ts64(out, 8 * i4, this.hh[i4], this.hl[i4]);
    return out;
  }
};
function add(p5, q4) {
  const a4 = gf(), b4 = gf(), c4 = gf(), d4 = gf(), e4 = gf(), f4 = gf(), g4 = gf(), h4 = gf(), t4 = gf();
  Z(a4, p5[1], p5[0]);
  Z(t4, q4[1], q4[0]);
  M2(a4, a4, t4);
  A2(b4, p5[0], p5[1]);
  A2(t4, q4[0], q4[1]);
  M2(b4, b4, t4);
  M2(c4, p5[3], q4[3]);
  M2(c4, c4, D2);
  M2(d4, p5[2], q4[2]);
  A2(d4, d4, d4);
  Z(e4, b4, a4);
  Z(f4, d4, c4);
  A2(g4, d4, c4);
  A2(h4, b4, a4);
  M2(p5[0], e4, f4);
  M2(p5[1], h4, g4);
  M2(p5[2], g4, f4);
  M2(p5[3], e4, h4);
}
function cswap(p5, q4, b4) {
  let i4;
  for (i4 = 0; i4 < 4; i4++) {
    sel25519(p5[i4], q4[i4], b4);
  }
}
function pack(r4, p5) {
  const tx = gf(), ty = gf(), zi = gf();
  inv25519(zi, p5[2]);
  M2(tx, p5[0], zi);
  M2(ty, p5[1], zi);
  pack25519(r4, ty);
  r4[31] ^= par25519(tx) << 7;
}
function scalarmult(p5, q4, s4) {
  let b4, i4;
  set25519(p5[0], gf0);
  set25519(p5[1], gf1);
  set25519(p5[2], gf1);
  set25519(p5[3], gf0);
  for (i4 = 255; i4 >= 0; --i4) {
    b4 = s4[i4 / 8 | 0] >> (i4 & 7) & 1;
    cswap(p5, q4, b4);
    add(q4, p5);
    add(p5, p5);
    cswap(p5, q4, b4);
  }
}
function scalarbase(p5, s4) {
  const q4 = [gf(), gf(), gf(), gf()];
  set25519(q4[0], X);
  set25519(q4[1], Y);
  set25519(q4[2], gf1);
  M2(q4[3], X, Y);
  scalarmult(p5, q4, s4);
}
function crypto_sign_keypair(pk, sk, seeded) {
  const d4 = new Uint8Array(64);
  const p5 = [gf(), gf(), gf(), gf()];
  if (!seeded)
    randombytes(sk, 32);
  crypto_hash(d4, sk, 32);
  d4[0] &= 248;
  d4[31] &= 127;
  d4[31] |= 64;
  scalarbase(p5, d4);
  pack(pk, p5);
  for (let i4 = 0; i4 < 32; i4++)
    sk[i4 + 32] = pk[i4];
  return 0;
}
var L2 = new Float64Array([
  237,
  211,
  245,
  92,
  26,
  99,
  18,
  88,
  214,
  156,
  247,
  162,
  222,
  249,
  222,
  20,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  16
]);
function modL(r4, x3) {
  let carry, i4, j4, k4;
  for (i4 = 63; i4 >= 32; --i4) {
    carry = 0;
    for (j4 = i4 - 32, k4 = i4 - 12; j4 < k4; ++j4) {
      x3[j4] += carry - 16 * x3[i4] * L2[j4 - (i4 - 32)];
      carry = Math.floor((x3[j4] + 128) / 256);
      x3[j4] -= carry * 256;
    }
    x3[j4] += carry;
    x3[i4] = 0;
  }
  carry = 0;
  for (j4 = 0; j4 < 32; j4++) {
    x3[j4] += carry - (x3[31] >> 4) * L2[j4];
    carry = x3[j4] >> 8;
    x3[j4] &= 255;
  }
  for (j4 = 0; j4 < 32; j4++)
    x3[j4] -= carry * L2[j4];
  for (i4 = 0; i4 < 32; i4++) {
    x3[i4 + 1] += x3[i4] >> 8;
    r4[i4] = x3[i4] & 255;
  }
}
function reduce(r4) {
  const x3 = new Float64Array(64);
  for (let i4 = 0; i4 < 64; i4++)
    x3[i4] = r4[i4];
  for (let i4 = 0; i4 < 64; i4++)
    r4[i4] = 0;
  modL(r4, x3);
}
function crypto_sign(sm, m4, n3, sk) {
  const d4 = new Uint8Array(64), h4 = new Uint8Array(64), r4 = new Uint8Array(64);
  let i4, j4;
  const x3 = new Float64Array(64);
  const p5 = [gf(), gf(), gf(), gf()];
  crypto_hash(d4, sk, 32);
  d4[0] &= 248;
  d4[31] &= 127;
  d4[31] |= 64;
  const smlen = n3 + 64;
  for (i4 = 0; i4 < n3; i4++)
    sm[64 + i4] = m4[i4];
  for (i4 = 0; i4 < 32; i4++)
    sm[32 + i4] = d4[32 + i4];
  crypto_hash(r4, sm.subarray(32), n3 + 32);
  reduce(r4);
  scalarbase(p5, r4);
  pack(sm, p5);
  for (i4 = 32; i4 < 64; i4++)
    sm[i4] = sk[i4];
  crypto_hash(h4, sm, n3 + 64);
  reduce(h4);
  for (i4 = 0; i4 < 64; i4++)
    x3[i4] = 0;
  for (i4 = 0; i4 < 32; i4++)
    x3[i4] = r4[i4];
  for (i4 = 0; i4 < 32; i4++) {
    for (j4 = 0; j4 < 32; j4++) {
      x3[i4 + j4] += h4[i4] * d4[j4];
    }
  }
  modL(sm.subarray(32), x3);
  return smlen;
}
function unpackpos(r4, p5) {
  const q4 = [gf(), gf(), gf(), gf()];
  if (unpackneg(q4, p5))
    return -1;
  const scalar0 = new Uint8Array(32);
  const scalar1 = new Uint8Array(32);
  scalar1[0] = 1;
  const scalarNeg1 = crypto_core_ed25519_scalar_sub(scalar0, scalar1);
  scalarmult(r4, q4, scalarNeg1);
  return 0;
}
function unpackneg(r4, p5) {
  const t4 = gf();
  const chk = gf();
  const num = gf();
  const den = gf();
  const den2 = gf();
  const den4 = gf();
  const den6 = gf();
  set25519(r4[2], gf1);
  unpack25519(r4[1], p5);
  S2(num, r4[1]);
  M2(den, num, D);
  Z(num, num, r4[2]);
  A2(den, r4[2], den);
  S2(den2, den);
  S2(den4, den2);
  M2(den6, den4, den2);
  M2(t4, den6, num);
  M2(t4, t4, den);
  pow2523(t4, t4);
  M2(t4, t4, num);
  M2(t4, t4, den);
  M2(t4, t4, den);
  M2(r4[0], t4, den);
  S2(chk, r4[0]);
  M2(chk, chk, den);
  if (neq25519(chk, num))
    M2(r4[0], r4[0], I2);
  S2(chk, r4[0]);
  M2(chk, chk, den);
  if (neq25519(chk, num))
    return -1;
  if (par25519(r4[0]) === p5[31] >> 7)
    Z(r4[0], gf0, r4[0]);
  M2(r4[3], r4[0], r4[1]);
  return 0;
}
function crypto_scalarmult_ed25519_base_noclamp(s4) {
  const r4 = new Uint8Array(32);
  const p5 = [gf(), gf(), gf(), gf()];
  scalarbase(p5, s4);
  pack(r4, p5);
  return r4;
}
function crypto_scalarmult_ed25519_noclamp(s4, q4) {
  const r4 = new Uint8Array(32);
  const p5 = [gf(), gf(), gf(), gf()];
  const ql = [gf(), gf(), gf(), gf()];
  if (unpackpos(ql, q4))
    throw new Error();
  scalarmult(p5, ql, s4);
  pack(r4, p5);
  return r4;
}
function crypto_sign_open(m4, sm, n3, pk) {
  let i4, mlen;
  const t4 = new Uint8Array(32), h4 = new Uint8Array(64);
  const p5 = [gf(), gf(), gf(), gf()], q4 = [gf(), gf(), gf(), gf()];
  mlen = -1;
  if (n3 < 64)
    return -1;
  if (unpackneg(q4, pk))
    return -1;
  for (i4 = 0; i4 < n3; i4++)
    m4[i4] = sm[i4];
  for (i4 = 0; i4 < 32; i4++)
    m4[i4 + 32] = pk[i4];
  crypto_hash(h4, m4, n3);
  reduce(h4);
  scalarmult(p5, q4, h4);
  scalarbase(q4, sm.subarray(32));
  add(p5, q4);
  pack(t4, p5);
  n3 -= 64;
  if (crypto_verify_32(sm, 0, t4, 0)) {
    for (i4 = 0; i4 < n3; i4++)
      m4[i4] = 0;
    return -1;
  }
  for (i4 = 0; i4 < n3; i4++)
    m4[i4] = sm[i4 + 64];
  mlen = n3;
  return mlen;
}
var crypto_secretbox_KEYBYTES = 32;
var crypto_secretbox_NONCEBYTES = 24;
var crypto_secretbox_ZEROBYTES = 32;
var crypto_secretbox_BOXZEROBYTES = 16;
var crypto_sign_BYTES = 64;
var crypto_sign_PUBLICKEYBYTES = 32;
var crypto_sign_SECRETKEYBYTES = 64;
var crypto_sign_SEEDBYTES = 32;
var crypto_hash_BYTES = 64;
function checkLengths(k4, n3) {
  if (k4.length !== crypto_secretbox_KEYBYTES)
    throw new Error("bad key size");
  if (n3.length !== crypto_secretbox_NONCEBYTES)
    throw new Error("bad nonce size");
}
function checkArrayTypes(...args) {
  for (let i4 = 0; i4 < args.length; i4++) {
    if (!(args[i4] instanceof Uint8Array))
      throw new TypeError("unexpected type, use Uint8Array");
  }
}
function randomBytes(n3) {
  const b4 = new Uint8Array(n3);
  randombytes(b4, n3);
  return b4;
}
function sign(msg, secretKey) {
  checkArrayTypes(msg, secretKey);
  if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
    throw new Error("bad secret key size");
  const signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length);
  crypto_sign(signedMsg, msg, msg.length, secretKey);
  return signedMsg;
}
function sign_detached(msg, secretKey) {
  const signedMsg = sign(msg, secretKey);
  const sig = new Uint8Array(crypto_sign_BYTES);
  for (let i4 = 0; i4 < sig.length; i4++)
    sig[i4] = signedMsg[i4];
  return sig;
}
function crypto_sign_keyPair_fromSeed(seed) {
  checkArrayTypes(seed);
  if (seed.length !== crypto_sign_SEEDBYTES)
    throw new Error(`bad seed size: ${seed.length}`);
  const pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  const sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
  for (let i4 = 0; i4 < 32; i4++)
    sk[i4] = seed[i4];
  crypto_sign_keypair(pk, sk, true);
  return { publicKey: pk, secretKey: sk };
}
function hash(msg) {
  checkArrayTypes(msg);
  const h4 = new Uint8Array(crypto_hash_BYTES);
  crypto_hash(h4, msg, msg.length);
  return h4;
}
function setPRNG(fn) {
  randombytes = fn;
}
function secretbox(msg, nonce, key) {
  checkArrayTypes(msg, nonce, key);
  checkLengths(key, nonce);
  var m4 = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
  var c4 = new Uint8Array(m4.length);
  for (var i4 = 0; i4 < msg.length; i4++)
    m4[i4 + crypto_secretbox_ZEROBYTES] = msg[i4];
  crypto_secretbox(c4, m4, m4.length, nonce, key);
  return c4.subarray(crypto_secretbox_BOXZEROBYTES);
}
function secretbox_open(box, nonce, key) {
  checkArrayTypes(box, nonce, key);
  checkLengths(key, nonce);
  var c4 = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
  var m4 = new Uint8Array(c4.length);
  for (var i4 = 0; i4 < box.length; i4++)
    c4[i4 + crypto_secretbox_BOXZEROBYTES] = box[i4];
  if (c4.length < 32)
    return void 0;
  if (crypto_secretbox_open(m4, c4, c4.length, nonce, key) !== 0)
    return void 0;
  return m4.subarray(crypto_secretbox_ZEROBYTES);
}
function crypto_core_ed25519_scalar_reduce(x3) {
  const len = x3.length;
  const z4 = new Float64Array(64);
  for (let i4 = 0; i4 < len; i4++)
    z4[i4] = x3[i4];
  const o4 = new Uint8Array(32);
  modL(o4, z4);
  return o4;
}
function crypto_core_ed25519_scalar_sub(x3, y4) {
  const z4 = new Float64Array(64);
  for (let i4 = 0; i4 < 32; i4++) {
    z4[i4] = x3[i4] - y4[i4];
  }
  const o4 = new Uint8Array(32);
  modL(o4, z4);
  return o4;
}
function crypto_edx25519_private_key_create() {
  const seed = new Uint8Array(32);
  randombytes(seed, 32);
  return crypto_edx25519_private_key_create_from_seed(seed);
}
function crypto_edx25519_private_key_create_from_seed(seed) {
  const pk = hash(seed);
  pk[0] &= 248;
  pk[31] &= 127;
  pk[31] |= 64;
  return pk;
}
function crypto_edx25519_get_public(priv) {
  return crypto_scalarmult_ed25519_base_noclamp(priv.subarray(0, 32));
}
function crypto_edx25519_sign_detached(m4, skx, pkx) {
  const n3 = m4.length;
  const h4 = new Uint8Array(64);
  const r4 = new Uint8Array(64);
  let i4, j4;
  const x3 = new Float64Array(64);
  const p5 = [gf(), gf(), gf(), gf()];
  const sm = new Uint8Array(n3 + 64);
  for (i4 = 0; i4 < n3; i4++)
    sm[64 + i4] = m4[i4];
  for (i4 = 0; i4 < 32; i4++)
    sm[32 + i4] = skx[32 + i4];
  crypto_hash(r4, sm.subarray(32), n3 + 32);
  reduce(r4);
  scalarbase(p5, r4);
  pack(sm, p5);
  for (i4 = 32; i4 < 64; i4++)
    sm[i4] = pkx[i4 - 32];
  crypto_hash(h4, sm, n3 + 64);
  reduce(h4);
  for (i4 = 0; i4 < 64; i4++)
    x3[i4] = 0;
  for (i4 = 0; i4 < 32; i4++)
    x3[i4] = r4[i4];
  for (i4 = 0; i4 < 32; i4++) {
    for (j4 = 0; j4 < 32; j4++) {
      x3[i4 + j4] += h4[i4] * skx[j4];
    }
  }
  modL(sm.subarray(32), x3);
  return sm.subarray(0, 64);
}
function crypto_edx25519_sign_detached_verify(msg, sig, publicKey) {
  checkArrayTypes(msg, sig, publicKey);
  if (sig.length !== crypto_sign_BYTES)
    throw new Error("bad signature size");
  if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
    throw new Error("bad public key size");
  const sm = new Uint8Array(crypto_sign_BYTES + msg.length);
  const m4 = new Uint8Array(crypto_sign_BYTES + msg.length);
  let i4;
  for (i4 = 0; i4 < crypto_sign_BYTES; i4++)
    sm[i4] = sig[i4];
  for (i4 = 0; i4 < msg.length; i4++)
    sm[i4 + crypto_sign_BYTES] = msg[i4];
  return crypto_sign_open(m4, sm, sm.length, publicKey) >= 0;
}

// ../taler-util/lib/prng-browser.js
function loadBrowserPrng() {
  const cr = typeof self !== "undefined" ? self.crypto || self.msCrypto : null;
  const QUOTA = 65536;
  setPRNG(function(x3, n3) {
    let i4;
    const v4 = new Uint8Array(n3);
    for (i4 = 0; i4 < n3; i4 += QUOTA) {
      cr.getRandomValues(v4.subarray(i4, i4 + Math.min(n3 - i4, QUOTA)));
    }
    for (i4 = 0; i4 < n3; i4++)
      x3[i4] = v4[i4];
    for (i4 = 0; i4 < v4.length; i4++)
      v4[i4] = 0;
  });
}

// ../taler-util/lib/taler-error-codes.js
var TalerErrorCode;
(function(TalerErrorCode2) {
  TalerErrorCode2[TalerErrorCode2["NONE"] = 0] = "NONE";
  TalerErrorCode2[TalerErrorCode2["INVALID"] = 1] = "INVALID";
  TalerErrorCode2[TalerErrorCode2["GENERIC_CLIENT_INTERNAL_ERROR"] = 2] = "GENERIC_CLIENT_INTERNAL_ERROR";
  TalerErrorCode2[TalerErrorCode2["GENERIC_INVALID_RESPONSE"] = 10] = "GENERIC_INVALID_RESPONSE";
  TalerErrorCode2[TalerErrorCode2["GENERIC_TIMEOUT"] = 11] = "GENERIC_TIMEOUT";
  TalerErrorCode2[TalerErrorCode2["GENERIC_VERSION_MALFORMED"] = 12] = "GENERIC_VERSION_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_REPLY_MALFORMED"] = 13] = "GENERIC_REPLY_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_CONFIGURATION_INVALID"] = 14] = "GENERIC_CONFIGURATION_INVALID";
  TalerErrorCode2[TalerErrorCode2["GENERIC_UNEXPECTED_REQUEST_ERROR"] = 15] = "GENERIC_UNEXPECTED_REQUEST_ERROR";
  TalerErrorCode2[TalerErrorCode2["GENERIC_TOKEN_PERMISSION_INSUFFICIENT"] = 16] = "GENERIC_TOKEN_PERMISSION_INSUFFICIENT";
  TalerErrorCode2[TalerErrorCode2["GENERIC_METHOD_INVALID"] = 20] = "GENERIC_METHOD_INVALID";
  TalerErrorCode2[TalerErrorCode2["GENERIC_ENDPOINT_UNKNOWN"] = 21] = "GENERIC_ENDPOINT_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["GENERIC_JSON_INVALID"] = 22] = "GENERIC_JSON_INVALID";
  TalerErrorCode2[TalerErrorCode2["GENERIC_HTTP_HEADERS_MALFORMED"] = 23] = "GENERIC_HTTP_HEADERS_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_PAYTO_URI_MALFORMED"] = 24] = "GENERIC_PAYTO_URI_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_PARAMETER_MISSING"] = 25] = "GENERIC_PARAMETER_MISSING";
  TalerErrorCode2[TalerErrorCode2["GENERIC_PARAMETER_MALFORMED"] = 26] = "GENERIC_PARAMETER_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_RESERVE_PUB_MALFORMED"] = 27] = "GENERIC_RESERVE_PUB_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_COMPRESSION_INVALID"] = 28] = "GENERIC_COMPRESSION_INVALID";
  TalerErrorCode2[TalerErrorCode2["GENERIC_CURRENCY_MISMATCH"] = 30] = "GENERIC_CURRENCY_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["GENERIC_URI_TOO_LONG"] = 31] = "GENERIC_URI_TOO_LONG";
  TalerErrorCode2[TalerErrorCode2["GENERIC_UPLOAD_EXCEEDS_LIMIT"] = 32] = "GENERIC_UPLOAD_EXCEEDS_LIMIT";
  TalerErrorCode2[TalerErrorCode2["GENERIC_UNAUTHORIZED"] = 40] = "GENERIC_UNAUTHORIZED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_TOKEN_UNKNOWN"] = 41] = "GENERIC_TOKEN_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["GENERIC_TOKEN_EXPIRED"] = 42] = "GENERIC_TOKEN_EXPIRED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_TOKEN_MALFORMED"] = 43] = "GENERIC_TOKEN_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_FORBIDDEN"] = 44] = "GENERIC_FORBIDDEN";
  TalerErrorCode2[TalerErrorCode2["GENERIC_DB_SETUP_FAILED"] = 50] = "GENERIC_DB_SETUP_FAILED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_DB_START_FAILED"] = 51] = "GENERIC_DB_START_FAILED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_DB_STORE_FAILED"] = 52] = "GENERIC_DB_STORE_FAILED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_DB_FETCH_FAILED"] = 53] = "GENERIC_DB_FETCH_FAILED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_DB_COMMIT_FAILED"] = 54] = "GENERIC_DB_COMMIT_FAILED";
  TalerErrorCode2[TalerErrorCode2["GENERIC_DB_SOFT_FAILURE"] = 55] = "GENERIC_DB_SOFT_FAILURE";
  TalerErrorCode2[TalerErrorCode2["GENERIC_DB_INVARIANT_FAILURE"] = 56] = "GENERIC_DB_INVARIANT_FAILURE";
  TalerErrorCode2[TalerErrorCode2["GENERIC_INTERNAL_INVARIANT_FAILURE"] = 60] = "GENERIC_INTERNAL_INVARIANT_FAILURE";
  TalerErrorCode2[TalerErrorCode2["GENERIC_FAILED_COMPUTE_JSON_HASH"] = 61] = "GENERIC_FAILED_COMPUTE_JSON_HASH";
  TalerErrorCode2[TalerErrorCode2["GENERIC_FAILED_COMPUTE_AMOUNT"] = 62] = "GENERIC_FAILED_COMPUTE_AMOUNT";
  TalerErrorCode2[TalerErrorCode2["GENERIC_PARSER_OUT_OF_MEMORY"] = 70] = "GENERIC_PARSER_OUT_OF_MEMORY";
  TalerErrorCode2[TalerErrorCode2["GENERIC_ALLOCATION_FAILURE"] = 71] = "GENERIC_ALLOCATION_FAILURE";
  TalerErrorCode2[TalerErrorCode2["GENERIC_JSON_ALLOCATION_FAILURE"] = 72] = "GENERIC_JSON_ALLOCATION_FAILURE";
  TalerErrorCode2[TalerErrorCode2["GENERIC_CURL_ALLOCATION_FAILURE"] = 73] = "GENERIC_CURL_ALLOCATION_FAILURE";
  TalerErrorCode2[TalerErrorCode2["GENERIC_FAILED_TO_LOAD_TEMPLATE"] = 74] = "GENERIC_FAILED_TO_LOAD_TEMPLATE";
  TalerErrorCode2[TalerErrorCode2["GENERIC_FAILED_TO_EXPAND_TEMPLATE"] = 75] = "GENERIC_FAILED_TO_EXPAND_TEMPLATE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_BAD_CONFIGURATION"] = 1e3] = "EXCHANGE_GENERIC_BAD_CONFIGURATION";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_OPERATION_UNKNOWN"] = 1001] = "EXCHANGE_GENERIC_OPERATION_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_WRONG_NUMBER_OF_SEGMENTS"] = 1002] = "EXCHANGE_GENERIC_WRONG_NUMBER_OF_SEGMENTS";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_COIN_CONFLICTING_DENOMINATION_KEY"] = 1003] = "EXCHANGE_GENERIC_COIN_CONFLICTING_DENOMINATION_KEY";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_COINS_INVALID_COIN_PUB"] = 1004] = "EXCHANGE_GENERIC_COINS_INVALID_COIN_PUB";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN"] = 1005] = "EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DENOMINATION_SIGNATURE_INVALID"] = 1006] = "EXCHANGE_DENOMINATION_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_KEYS_MISSING"] = 1007] = "EXCHANGE_GENERIC_KEYS_MISSING";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_DENOMINATION_VALIDITY_IN_FUTURE"] = 1008] = "EXCHANGE_GENERIC_DENOMINATION_VALIDITY_IN_FUTURE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_DENOMINATION_EXPIRED"] = 1009] = "EXCHANGE_GENERIC_DENOMINATION_EXPIRED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_DENOMINATION_REVOKED"] = 1010] = "EXCHANGE_GENERIC_DENOMINATION_REVOKED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_SECMOD_TIMEOUT"] = 1011] = "EXCHANGE_GENERIC_SECMOD_TIMEOUT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_INSUFFICIENT_FUNDS"] = 1012] = "EXCHANGE_GENERIC_INSUFFICIENT_FUNDS";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_COIN_HISTORY_COMPUTATION_FAILED"] = 1013] = "EXCHANGE_GENERIC_COIN_HISTORY_COMPUTATION_FAILED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_HISTORY_DB_ERROR_INSUFFICIENT_FUNDS"] = 1014] = "EXCHANGE_GENERIC_HISTORY_DB_ERROR_INSUFFICIENT_FUNDS";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_COIN_CONFLICTING_AGE_HASH"] = 1015] = "EXCHANGE_GENERIC_COIN_CONFLICTING_AGE_HASH";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_INVALID_DENOMINATION_CIPHER_FOR_OPERATION"] = 1016] = "EXCHANGE_GENERIC_INVALID_DENOMINATION_CIPHER_FOR_OPERATION";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_CIPHER_MISMATCH"] = 1017] = "EXCHANGE_GENERIC_CIPHER_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_NEW_DENOMS_ARRAY_SIZE_EXCESSIVE"] = 1018] = "EXCHANGE_GENERIC_NEW_DENOMS_ARRAY_SIZE_EXCESSIVE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_COIN_UNKNOWN"] = 1019] = "EXCHANGE_GENERIC_COIN_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_CLOCK_SKEW"] = 1020] = "EXCHANGE_GENERIC_CLOCK_SKEW";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_AMOUNT_EXCEEDS_DENOMINATION_VALUE"] = 1021] = "EXCHANGE_GENERIC_AMOUNT_EXCEEDS_DENOMINATION_VALUE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_GLOBAL_FEES_MISSING"] = 1022] = "EXCHANGE_GENERIC_GLOBAL_FEES_MISSING";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_WIRE_FEES_MISSING"] = 1023] = "EXCHANGE_GENERIC_WIRE_FEES_MISSING";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_PURSE_PUB_MALFORMED"] = 1024] = "EXCHANGE_GENERIC_PURSE_PUB_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_PURSE_UNKNOWN"] = 1025] = "EXCHANGE_GENERIC_PURSE_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_PURSE_EXPIRED"] = 1026] = "EXCHANGE_GENERIC_PURSE_EXPIRED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_RESERVE_UNKNOWN"] = 1027] = "EXCHANGE_GENERIC_RESERVE_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_KYC_REQUIRED"] = 1028] = "EXCHANGE_GENERIC_KYC_REQUIRED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_DEPOSIT_COIN_CONFLICTING_ATTEST_VS_AGE_COMMITMENT"] = 1029] = "EXCHANGE_PURSE_DEPOSIT_COIN_CONFLICTING_ATTEST_VS_AGE_COMMITMENT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_DEPOSIT_COIN_AGE_ATTESTATION_FAILURE"] = 1030] = "EXCHANGE_PURSE_DEPOSIT_COIN_AGE_ATTESTATION_FAILURE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_PURSE_DELETED"] = 1031] = "EXCHANGE_GENERIC_PURSE_DELETED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_AML_OFFICER_PUB_MALFORMED"] = 1032] = "EXCHANGE_GENERIC_AML_OFFICER_PUB_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_AML_OFFICER_GET_SIGNATURE_INVALID"] = 1033] = "EXCHANGE_GENERIC_AML_OFFICER_GET_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_AML_OFFICER_ACCESS_DENIED"] = 1034] = "EXCHANGE_GENERIC_AML_OFFICER_ACCESS_DENIED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_AML_PENDING"] = 1035] = "EXCHANGE_GENERIC_AML_PENDING";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_AML_FROZEN"] = 1036] = "EXCHANGE_GENERIC_AML_FROZEN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GENERIC_KYC_CONVERTER_FAILED"] = 1037] = "EXCHANGE_GENERIC_KYC_CONVERTER_FAILED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSITS_GET_NOT_FOUND"] = 1100] = "EXCHANGE_DEPOSITS_GET_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSITS_GET_INVALID_H_WIRE"] = 1101] = "EXCHANGE_DEPOSITS_GET_INVALID_H_WIRE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSITS_GET_INVALID_MERCHANT_PUB"] = 1102] = "EXCHANGE_DEPOSITS_GET_INVALID_MERCHANT_PUB";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSITS_GET_INVALID_H_CONTRACT_TERMS"] = 1103] = "EXCHANGE_DEPOSITS_GET_INVALID_H_CONTRACT_TERMS";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSITS_GET_INVALID_COIN_PUB"] = 1104] = "EXCHANGE_DEPOSITS_GET_INVALID_COIN_PUB";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSITS_GET_INVALID_SIGNATURE_BY_EXCHANGE"] = 1105] = "EXCHANGE_DEPOSITS_GET_INVALID_SIGNATURE_BY_EXCHANGE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSITS_GET_MERCHANT_SIGNATURE_INVALID"] = 1106] = "EXCHANGE_DEPOSITS_GET_MERCHANT_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSITS_POLICY_NOT_ACCEPTED"] = 1107] = "EXCHANGE_DEPOSITS_POLICY_NOT_ACCEPTED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_WITHDRAW_INSUFFICIENT_FUNDS"] = 1150] = "EXCHANGE_WITHDRAW_INSUFFICIENT_FUNDS";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AGE_WITHDRAW_INSUFFICIENT_FUNDS"] = 1151] = "EXCHANGE_AGE_WITHDRAW_INSUFFICIENT_FUNDS";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_WITHDRAW_AMOUNT_FEE_OVERFLOW"] = 1152] = "EXCHANGE_WITHDRAW_AMOUNT_FEE_OVERFLOW";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_WITHDRAW_SIGNATURE_FAILED"] = 1153] = "EXCHANGE_WITHDRAW_SIGNATURE_FAILED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_WITHDRAW_RESERVE_SIGNATURE_INVALID"] = 1154] = "EXCHANGE_WITHDRAW_RESERVE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVE_HISTORY_ERROR_INSUFFICIENT_FUNDS"] = 1155] = "EXCHANGE_RESERVE_HISTORY_ERROR_INSUFFICIENT_FUNDS";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_GET_RESERVE_HISTORY_ERROR_INSUFFICIENT_BALANCE"] = 1156] = "EXCHANGE_GET_RESERVE_HISTORY_ERROR_INSUFFICIENT_BALANCE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_WITHDRAW_DENOMINATION_KEY_LOST"] = 1158] = "EXCHANGE_WITHDRAW_DENOMINATION_KEY_LOST";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_WITHDRAW_UNBLIND_FAILURE"] = 1159] = "EXCHANGE_WITHDRAW_UNBLIND_FAILURE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_WITHDRAW_NONCE_REUSE"] = 1160] = "EXCHANGE_WITHDRAW_NONCE_REUSE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AGE_WITHDRAW_COMMITMENT_UNKNOWN"] = 1161] = "EXCHANGE_AGE_WITHDRAW_COMMITMENT_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AGE_WITHDRAW_AMOUNT_OVERFLOW"] = 1162] = "EXCHANGE_AGE_WITHDRAW_AMOUNT_OVERFLOW";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AGE_WITHDRAW_AMOUNT_INCORRECT"] = 1163] = "EXCHANGE_AGE_WITHDRAW_AMOUNT_INCORRECT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AGE_WITHDRAW_REVEAL_INVALID_HASH"] = 1164] = "EXCHANGE_AGE_WITHDRAW_REVEAL_INVALID_HASH";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AGE_WITHDRAW_MAXIMUM_AGE_TOO_LARGE"] = 1165] = "EXCHANGE_AGE_WITHDRAW_MAXIMUM_AGE_TOO_LARGE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_WITHDRAW_BATCH_IDEMPOTENT_PLANCHET"] = 1175] = "EXCHANGE_WITHDRAW_BATCH_IDEMPOTENT_PLANCHET";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSIT_COIN_SIGNATURE_INVALID"] = 1205] = "EXCHANGE_DEPOSIT_COIN_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSIT_CONFLICTING_CONTRACT"] = 1206] = "EXCHANGE_DEPOSIT_CONFLICTING_CONTRACT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSIT_NEGATIVE_VALUE_AFTER_FEE"] = 1207] = "EXCHANGE_DEPOSIT_NEGATIVE_VALUE_AFTER_FEE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSIT_REFUND_DEADLINE_AFTER_WIRE_DEADLINE"] = 1208] = "EXCHANGE_DEPOSIT_REFUND_DEADLINE_AFTER_WIRE_DEADLINE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSIT_WIRE_DEADLINE_IS_NEVER"] = 1209] = "EXCHANGE_DEPOSIT_WIRE_DEADLINE_IS_NEVER";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSIT_INVALID_WIRE_FORMAT_JSON"] = 1210] = "EXCHANGE_DEPOSIT_INVALID_WIRE_FORMAT_JSON";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSIT_INVALID_WIRE_FORMAT_CONTRACT_HASH_CONFLICT"] = 1211] = "EXCHANGE_DEPOSIT_INVALID_WIRE_FORMAT_CONTRACT_HASH_CONFLICT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSIT_INVALID_SIGNATURE_BY_EXCHANGE"] = 1221] = "EXCHANGE_DEPOSIT_INVALID_SIGNATURE_BY_EXCHANGE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DEPOSIT_FEE_ABOVE_AMOUNT"] = 1222] = "EXCHANGE_DEPOSIT_FEE_ABOVE_AMOUNT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_EXTENSIONS_INVALID_FULFILLMENT"] = 1240] = "EXCHANGE_EXTENSIONS_INVALID_FULFILLMENT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_COIN_HISTORY_BAD_SIGNATURE"] = 1251] = "EXCHANGE_COIN_HISTORY_BAD_SIGNATURE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVE_HISTORY_BAD_SIGNATURE"] = 1252] = "EXCHANGE_RESERVE_HISTORY_BAD_SIGNATURE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MELT_FEES_EXCEED_CONTRIBUTION"] = 1302] = "EXCHANGE_MELT_FEES_EXCEED_CONTRIBUTION";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MELT_COIN_SIGNATURE_INVALID"] = 1303] = "EXCHANGE_MELT_COIN_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MELT_COIN_EXPIRED_NO_ZOMBIE"] = 1305] = "EXCHANGE_MELT_COIN_EXPIRED_NO_ZOMBIE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MELT_INVALID_SIGNATURE_BY_EXCHANGE"] = 1306] = "EXCHANGE_MELT_INVALID_SIGNATURE_BY_EXCHANGE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFRESHES_REVEAL_COMMITMENT_VIOLATION"] = 1353] = "EXCHANGE_REFRESHES_REVEAL_COMMITMENT_VIOLATION";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFRESHES_REVEAL_SIGNING_ERROR"] = 1354] = "EXCHANGE_REFRESHES_REVEAL_SIGNING_ERROR";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFRESHES_REVEAL_SESSION_UNKNOWN"] = 1355] = "EXCHANGE_REFRESHES_REVEAL_SESSION_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFRESHES_REVEAL_CNC_TRANSFER_ARRAY_SIZE_INVALID"] = 1356] = "EXCHANGE_REFRESHES_REVEAL_CNC_TRANSFER_ARRAY_SIZE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFRESHES_REVEAL_NEW_DENOMS_ARRAY_SIZE_MISMATCH"] = 1358] = "EXCHANGE_REFRESHES_REVEAL_NEW_DENOMS_ARRAY_SIZE_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFRESHES_REVEAL_COST_CALCULATION_OVERFLOW"] = 1359] = "EXCHANGE_REFRESHES_REVEAL_COST_CALCULATION_OVERFLOW";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFRESHES_REVEAL_AMOUNT_INSUFFICIENT"] = 1360] = "EXCHANGE_REFRESHES_REVEAL_AMOUNT_INSUFFICIENT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFRESHES_REVEAL_LINK_SIGNATURE_INVALID"] = 1361] = "EXCHANGE_REFRESHES_REVEAL_LINK_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFRESHES_REVEAL_INVALID_RCH"] = 1362] = "EXCHANGE_REFRESHES_REVEAL_INVALID_RCH";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFRESHES_REVEAL_OPERATION_INVALID"] = 1363] = "EXCHANGE_REFRESHES_REVEAL_OPERATION_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFRESHES_REVEAL_AGE_RESTRICTION_NOT_SUPPORTED"] = 1364] = "EXCHANGE_REFRESHES_REVEAL_AGE_RESTRICTION_NOT_SUPPORTED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFRESHES_REVEAL_AGE_RESTRICTION_COMMITMENT_INVALID"] = 1365] = "EXCHANGE_REFRESHES_REVEAL_AGE_RESTRICTION_COMMITMENT_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_LINK_COIN_UNKNOWN"] = 1400] = "EXCHANGE_LINK_COIN_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_TRANSFERS_GET_WTID_MALFORMED"] = 1450] = "EXCHANGE_TRANSFERS_GET_WTID_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_TRANSFERS_GET_WTID_NOT_FOUND"] = 1451] = "EXCHANGE_TRANSFERS_GET_WTID_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_TRANSFERS_GET_WIRE_FEE_NOT_FOUND"] = 1452] = "EXCHANGE_TRANSFERS_GET_WIRE_FEE_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_TRANSFERS_GET_WIRE_FEE_INCONSISTENT"] = 1453] = "EXCHANGE_TRANSFERS_GET_WIRE_FEE_INCONSISTENT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSES_INVALID_WAIT_TARGET"] = 1475] = "EXCHANGE_PURSES_INVALID_WAIT_TARGET";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSES_GET_INVALID_SIGNATURE_BY_EXCHANGE"] = 1476] = "EXCHANGE_PURSES_GET_INVALID_SIGNATURE_BY_EXCHANGE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFUND_COIN_NOT_FOUND"] = 1500] = "EXCHANGE_REFUND_COIN_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFUND_CONFLICT_DEPOSIT_INSUFFICIENT"] = 1501] = "EXCHANGE_REFUND_CONFLICT_DEPOSIT_INSUFFICIENT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFUND_DEPOSIT_NOT_FOUND"] = 1502] = "EXCHANGE_REFUND_DEPOSIT_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFUND_MERCHANT_ALREADY_PAID"] = 1503] = "EXCHANGE_REFUND_MERCHANT_ALREADY_PAID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFUND_FEE_TOO_LOW"] = 1504] = "EXCHANGE_REFUND_FEE_TOO_LOW";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFUND_FEE_ABOVE_AMOUNT"] = 1505] = "EXCHANGE_REFUND_FEE_ABOVE_AMOUNT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFUND_MERCHANT_SIGNATURE_INVALID"] = 1506] = "EXCHANGE_REFUND_MERCHANT_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFUND_MERCHANT_SIGNING_FAILED"] = 1507] = "EXCHANGE_REFUND_MERCHANT_SIGNING_FAILED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFUND_INVALID_SIGNATURE_BY_EXCHANGE"] = 1508] = "EXCHANGE_REFUND_INVALID_SIGNATURE_BY_EXCHANGE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFUND_INVALID_FAILURE_PROOF_BY_EXCHANGE"] = 1509] = "EXCHANGE_REFUND_INVALID_FAILURE_PROOF_BY_EXCHANGE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_REFUND_INCONSISTENT_AMOUNT"] = 1510] = "EXCHANGE_REFUND_INCONSISTENT_AMOUNT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RECOUP_SIGNATURE_INVALID"] = 1550] = "EXCHANGE_RECOUP_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RECOUP_WITHDRAW_NOT_FOUND"] = 1551] = "EXCHANGE_RECOUP_WITHDRAW_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RECOUP_COIN_BALANCE_ZERO"] = 1552] = "EXCHANGE_RECOUP_COIN_BALANCE_ZERO";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RECOUP_BLINDING_FAILED"] = 1553] = "EXCHANGE_RECOUP_BLINDING_FAILED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RECOUP_COIN_BALANCE_NEGATIVE"] = 1554] = "EXCHANGE_RECOUP_COIN_BALANCE_NEGATIVE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RECOUP_NOT_ELIGIBLE"] = 1555] = "EXCHANGE_RECOUP_NOT_ELIGIBLE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RECOUP_REFRESH_SIGNATURE_INVALID"] = 1575] = "EXCHANGE_RECOUP_REFRESH_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RECOUP_REFRESH_MELT_NOT_FOUND"] = 1576] = "EXCHANGE_RECOUP_REFRESH_MELT_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RECOUP_REFRESH_BLINDING_FAILED"] = 1578] = "EXCHANGE_RECOUP_REFRESH_BLINDING_FAILED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RECOUP_REFRESH_NOT_ELIGIBLE"] = 1580] = "EXCHANGE_RECOUP_REFRESH_NOT_ELIGIBLE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KEYS_TIMETRAVEL_FORBIDDEN"] = 1600] = "EXCHANGE_KEYS_TIMETRAVEL_FORBIDDEN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_WIRE_SIGNATURE_INVALID"] = 1650] = "EXCHANGE_WIRE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_WIRE_NO_ACCOUNTS_CONFIGURED"] = 1651] = "EXCHANGE_WIRE_NO_ACCOUNTS_CONFIGURED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_WIRE_INVALID_PAYTO_CONFIGURED"] = 1652] = "EXCHANGE_WIRE_INVALID_PAYTO_CONFIGURED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_WIRE_FEES_NOT_CONFIGURED"] = 1653] = "EXCHANGE_WIRE_FEES_NOT_CONFIGURED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_PURSE_CREATE_CONFLICTING_META_DATA"] = 1675] = "EXCHANGE_RESERVES_PURSE_CREATE_CONFLICTING_META_DATA";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_PURSE_MERGE_CONFLICTING_META_DATA"] = 1676] = "EXCHANGE_RESERVES_PURSE_MERGE_CONFLICTING_META_DATA";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_PURSE_CREATE_INSUFFICIENT_FUNDS"] = 1677] = "EXCHANGE_RESERVES_PURSE_CREATE_INSUFFICIENT_FUNDS";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_PURSE_FEE_TOO_LOW"] = 1678] = "EXCHANGE_RESERVES_PURSE_FEE_TOO_LOW";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_DELETE_ALREADY_DECIDED"] = 1679] = "EXCHANGE_PURSE_DELETE_ALREADY_DECIDED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_DELETE_SIGNATURE_INVALID"] = 1680] = "EXCHANGE_PURSE_DELETE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_AGE_RESTRICTION_REQUIRED"] = 1681] = "EXCHANGE_RESERVES_AGE_RESTRICTION_REQUIRED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE"] = 1700] = "EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DENOMINATION_HELPER_BUG"] = 1701] = "EXCHANGE_DENOMINATION_HELPER_BUG";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_DENOMINATION_HELPER_TOO_EARLY"] = 1702] = "EXCHANGE_DENOMINATION_HELPER_TOO_EARLY";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_DEPOSIT_EXCHANGE_SIGNATURE_INVALID"] = 1725] = "EXCHANGE_PURSE_DEPOSIT_EXCHANGE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_SIGNKEY_HELPER_UNAVAILABLE"] = 1750] = "EXCHANGE_SIGNKEY_HELPER_UNAVAILABLE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_SIGNKEY_HELPER_BUG"] = 1751] = "EXCHANGE_SIGNKEY_HELPER_BUG";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_SIGNKEY_HELPER_TOO_EARLY"] = 1752] = "EXCHANGE_SIGNKEY_HELPER_TOO_EARLY";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_PURSE_EXPIRATION_BEFORE_NOW"] = 1775] = "EXCHANGE_RESERVES_PURSE_EXPIRATION_BEFORE_NOW";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_PURSE_EXPIRATION_IS_NEVER"] = 1776] = "EXCHANGE_RESERVES_PURSE_EXPIRATION_IS_NEVER";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_PURSE_MERGE_SIGNATURE_INVALID"] = 1777] = "EXCHANGE_RESERVES_PURSE_MERGE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_RESERVE_MERGE_SIGNATURE_INVALID"] = 1778] = "EXCHANGE_RESERVES_RESERVE_MERGE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_OPEN_BAD_SIGNATURE"] = 1785] = "EXCHANGE_RESERVES_OPEN_BAD_SIGNATURE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_CLOSE_BAD_SIGNATURE"] = 1786] = "EXCHANGE_RESERVES_CLOSE_BAD_SIGNATURE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_ATTEST_BAD_SIGNATURE"] = 1787] = "EXCHANGE_RESERVES_ATTEST_BAD_SIGNATURE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_CLOSE_NO_TARGET_ACCOUNT"] = 1788] = "EXCHANGE_RESERVES_CLOSE_NO_TARGET_ACCOUNT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_RESERVES_OPEN_INSUFFICIENT_FUNDS"] = 1789] = "EXCHANGE_RESERVES_OPEN_INSUFFICIENT_FUNDS";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_AUDITOR_NOT_FOUND"] = 1800] = "EXCHANGE_MANAGEMENT_AUDITOR_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_AUDITOR_MORE_RECENT_PRESENT"] = 1801] = "EXCHANGE_MANAGEMENT_AUDITOR_MORE_RECENT_PRESENT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_AUDITOR_ADD_SIGNATURE_INVALID"] = 1802] = "EXCHANGE_MANAGEMENT_AUDITOR_ADD_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_AUDITOR_DEL_SIGNATURE_INVALID"] = 1803] = "EXCHANGE_MANAGEMENT_AUDITOR_DEL_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_DENOMINATION_REVOKE_SIGNATURE_INVALID"] = 1804] = "EXCHANGE_MANAGEMENT_DENOMINATION_REVOKE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_SIGNKEY_REVOKE_SIGNATURE_INVALID"] = 1805] = "EXCHANGE_MANAGEMENT_SIGNKEY_REVOKE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_WIRE_MORE_RECENT_PRESENT"] = 1806] = "EXCHANGE_MANAGEMENT_WIRE_MORE_RECENT_PRESENT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_KEYS_SIGNKEY_UNKNOWN"] = 1807] = "EXCHANGE_MANAGEMENT_KEYS_SIGNKEY_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_WIRE_DETAILS_SIGNATURE_INVALID"] = 1808] = "EXCHANGE_MANAGEMENT_WIRE_DETAILS_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_WIRE_ADD_SIGNATURE_INVALID"] = 1809] = "EXCHANGE_MANAGEMENT_WIRE_ADD_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_WIRE_DEL_SIGNATURE_INVALID"] = 1810] = "EXCHANGE_MANAGEMENT_WIRE_DEL_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_WIRE_NOT_FOUND"] = 1811] = "EXCHANGE_MANAGEMENT_WIRE_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_WIRE_FEE_SIGNATURE_INVALID"] = 1812] = "EXCHANGE_MANAGEMENT_WIRE_FEE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_WIRE_FEE_MISMATCH"] = 1813] = "EXCHANGE_MANAGEMENT_WIRE_FEE_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_KEYS_DENOMKEY_ADD_SIGNATURE_INVALID"] = 1814] = "EXCHANGE_MANAGEMENT_KEYS_DENOMKEY_ADD_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_KEYS_SIGNKEY_ADD_SIGNATURE_INVALID"] = 1815] = "EXCHANGE_MANAGEMENT_KEYS_SIGNKEY_ADD_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_GLOBAL_FEE_MISMATCH"] = 1816] = "EXCHANGE_MANAGEMENT_GLOBAL_FEE_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_GLOBAL_FEE_SIGNATURE_INVALID"] = 1817] = "EXCHANGE_MANAGEMENT_GLOBAL_FEE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_DRAIN_PROFITS_SIGNATURE_INVALID"] = 1818] = "EXCHANGE_MANAGEMENT_DRAIN_PROFITS_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AML_DECISION_ADD_SIGNATURE_INVALID"] = 1825] = "EXCHANGE_AML_DECISION_ADD_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AML_DECISION_INVALID_OFFICER"] = 1826] = "EXCHANGE_AML_DECISION_INVALID_OFFICER";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AML_DECISION_MORE_RECENT_PRESENT"] = 1827] = "EXCHANGE_AML_DECISION_MORE_RECENT_PRESENT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AML_DECISION_UNKNOWN_CHECK"] = 1828] = "EXCHANGE_AML_DECISION_UNKNOWN_CHECK";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_UPDATE_AML_OFFICER_SIGNATURE_INVALID"] = 1830] = "EXCHANGE_MANAGEMENT_UPDATE_AML_OFFICER_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_AML_OFFICERS_MORE_RECENT_PRESENT"] = 1831] = "EXCHANGE_MANAGEMENT_AML_OFFICERS_MORE_RECENT_PRESENT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_CREATE_CONFLICTING_META_DATA"] = 1850] = "EXCHANGE_PURSE_CREATE_CONFLICTING_META_DATA";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_CREATE_CONFLICTING_CONTRACT_STORED"] = 1851] = "EXCHANGE_PURSE_CREATE_CONFLICTING_CONTRACT_STORED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_CREATE_COIN_SIGNATURE_INVALID"] = 1852] = "EXCHANGE_PURSE_CREATE_COIN_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_CREATE_EXPIRATION_BEFORE_NOW"] = 1853] = "EXCHANGE_PURSE_CREATE_EXPIRATION_BEFORE_NOW";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_CREATE_EXPIRATION_IS_NEVER"] = 1854] = "EXCHANGE_PURSE_CREATE_EXPIRATION_IS_NEVER";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_CREATE_SIGNATURE_INVALID"] = 1855] = "EXCHANGE_PURSE_CREATE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_ECONTRACT_SIGNATURE_INVALID"] = 1856] = "EXCHANGE_PURSE_ECONTRACT_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_CREATE_EXCHANGE_SIGNATURE_INVALID"] = 1857] = "EXCHANGE_PURSE_CREATE_EXCHANGE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_DEPOSIT_CONFLICTING_META_DATA"] = 1858] = "EXCHANGE_PURSE_DEPOSIT_CONFLICTING_META_DATA";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_ECONTRACT_CONFLICTING_META_DATA"] = 1859] = "EXCHANGE_PURSE_ECONTRACT_CONFLICTING_META_DATA";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_CREATE_PURSE_NEGATIVE_VALUE_AFTER_FEE"] = 1860] = "EXCHANGE_CREATE_PURSE_NEGATIVE_VALUE_AFTER_FEE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_MERGE_INVALID_MERGE_SIGNATURE"] = 1876] = "EXCHANGE_PURSE_MERGE_INVALID_MERGE_SIGNATURE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_MERGE_INVALID_RESERVE_SIGNATURE"] = 1877] = "EXCHANGE_PURSE_MERGE_INVALID_RESERVE_SIGNATURE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_NOT_FULL"] = 1878] = "EXCHANGE_PURSE_NOT_FULL";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_MERGE_EXCHANGE_SIGNATURE_INVALID"] = 1879] = "EXCHANGE_PURSE_MERGE_EXCHANGE_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MERGE_PURSE_PARTNER_UNKNOWN"] = 1880] = "EXCHANGE_MERGE_PURSE_PARTNER_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_ADD_PARTNER_SIGNATURE_INVALID"] = 1890] = "EXCHANGE_MANAGEMENT_ADD_PARTNER_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_MANAGEMENT_ADD_PARTNER_DATA_CONFLICT"] = 1891] = "EXCHANGE_MANAGEMENT_ADD_PARTNER_DATA_CONFLICT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AUDITORS_AUDITOR_SIGNATURE_INVALID"] = 1900] = "EXCHANGE_AUDITORS_AUDITOR_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AUDITORS_AUDITOR_UNKNOWN"] = 1901] = "EXCHANGE_AUDITORS_AUDITOR_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_AUDITORS_AUDITOR_INACTIVE"] = 1902] = "EXCHANGE_AUDITORS_AUDITOR_INACTIVE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_WALLET_SIGNATURE_INVALID"] = 1925] = "EXCHANGE_KYC_WALLET_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_PROOF_BACKEND_INVALID_RESPONSE"] = 1926] = "EXCHANGE_KYC_PROOF_BACKEND_INVALID_RESPONSE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_PROOF_BACKEND_ERROR"] = 1927] = "EXCHANGE_KYC_PROOF_BACKEND_ERROR";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_PROOF_BACKEND_AUTHORIZATION_FAILED"] = 1928] = "EXCHANGE_KYC_PROOF_BACKEND_AUTHORIZATION_FAILED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_PROOF_REQUEST_UNKNOWN"] = 1929] = "EXCHANGE_KYC_PROOF_REQUEST_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_CHECK_AUTHORIZATION_FAILED"] = 1930] = "EXCHANGE_KYC_CHECK_AUTHORIZATION_FAILED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_GENERIC_LOGIC_UNKNOWN"] = 1931] = "EXCHANGE_KYC_GENERIC_LOGIC_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_GENERIC_LOGIC_GONE"] = 1932] = "EXCHANGE_KYC_GENERIC_LOGIC_GONE";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_GENERIC_LOGIC_BUG"] = 1933] = "EXCHANGE_KYC_GENERIC_LOGIC_BUG";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_GENERIC_PROVIDER_ACCESS_REFUSED"] = 1934] = "EXCHANGE_KYC_GENERIC_PROVIDER_ACCESS_REFUSED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_GENERIC_PROVIDER_TIMEOUT"] = 1935] = "EXCHANGE_KYC_GENERIC_PROVIDER_TIMEOUT";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_GENERIC_PROVIDER_UNEXPECTED_REPLY"] = 1936] = "EXCHANGE_KYC_GENERIC_PROVIDER_UNEXPECTED_REPLY";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_GENERIC_PROVIDER_RATE_LIMIT_EXCEEDED"] = 1937] = "EXCHANGE_KYC_GENERIC_PROVIDER_RATE_LIMIT_EXCEEDED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_WEBHOOK_UNAUTHORIZED"] = 1938] = "EXCHANGE_KYC_WEBHOOK_UNAUTHORIZED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_CHECK_REQUEST_UNKNOWN"] = 1939] = "EXCHANGE_KYC_CHECK_REQUEST_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_KYC_CHECK_AUTHORIZATION_KEY_UNKNOWN"] = 1940] = "EXCHANGE_KYC_CHECK_AUTHORIZATION_KEY_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_CONTRACTS_UNKNOWN"] = 1950] = "EXCHANGE_CONTRACTS_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_CONTRACTS_INVALID_CONTRACT_PUB"] = 1951] = "EXCHANGE_CONTRACTS_INVALID_CONTRACT_PUB";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_CONTRACTS_DECRYPTION_FAILED"] = 1952] = "EXCHANGE_CONTRACTS_DECRYPTION_FAILED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_CONTRACTS_SIGNATURE_INVALID"] = 1953] = "EXCHANGE_CONTRACTS_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_CONTRACTS_DECODING_FAILED"] = 1954] = "EXCHANGE_CONTRACTS_DECODING_FAILED";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_DEPOSIT_COIN_SIGNATURE_INVALID"] = 1975] = "EXCHANGE_PURSE_DEPOSIT_COIN_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_PURSE_DEPOSIT_DECIDED_ALREADY"] = 1976] = "EXCHANGE_PURSE_DEPOSIT_DECIDED_ALREADY";
  TalerErrorCode2[TalerErrorCode2["EXCHANGE_TOTP_KEY_INVALID"] = 1980] = "EXCHANGE_TOTP_KEY_INVALID";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_INSTANCE_UNKNOWN"] = 2e3] = "MERCHANT_GENERIC_INSTANCE_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_HOLE_IN_WIRE_FEE_STRUCTURE"] = 2001] = "MERCHANT_GENERIC_HOLE_IN_WIRE_FEE_STRUCTURE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_EXCHANGE_WIRE_REQUEST_FAILED"] = 2002] = "MERCHANT_GENERIC_EXCHANGE_WIRE_REQUEST_FAILED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_CATEGORY_UNKNOWN"] = 2003] = "MERCHANT_GENERIC_CATEGORY_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_ORDER_UNKNOWN"] = 2005] = "MERCHANT_GENERIC_ORDER_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_PRODUCT_UNKNOWN"] = 2006] = "MERCHANT_GENERIC_PRODUCT_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_REWARD_ID_UNKNOWN"] = 2007] = "MERCHANT_GENERIC_REWARD_ID_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_DB_CONTRACT_CONTENT_INVALID"] = 2008] = "MERCHANT_GENERIC_DB_CONTRACT_CONTENT_INVALID";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_CONTRACT_HASH_DOES_NOT_MATCH_ORDER"] = 2009] = "MERCHANT_GENERIC_CONTRACT_HASH_DOES_NOT_MATCH_ORDER";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_EXCHANGE_KEYS_FAILURE"] = 2010] = "MERCHANT_GENERIC_EXCHANGE_KEYS_FAILURE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_EXCHANGE_TIMEOUT"] = 2011] = "MERCHANT_GENERIC_EXCHANGE_TIMEOUT";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_EXCHANGE_CONNECT_FAILURE"] = 2012] = "MERCHANT_GENERIC_EXCHANGE_CONNECT_FAILURE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_EXCHANGE_REPLY_MALFORMED"] = 2013] = "MERCHANT_GENERIC_EXCHANGE_REPLY_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_EXCHANGE_UNEXPECTED_STATUS"] = 2014] = "MERCHANT_GENERIC_EXCHANGE_UNEXPECTED_STATUS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_UNAUTHORIZED"] = 2015] = "MERCHANT_GENERIC_UNAUTHORIZED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_INSTANCE_DELETED"] = 2016] = "MERCHANT_GENERIC_INSTANCE_DELETED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_TRANSFER_UNKNOWN"] = 2017] = "MERCHANT_GENERIC_TRANSFER_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_TEMPLATE_UNKNOWN"] = 2018] = "MERCHANT_GENERIC_TEMPLATE_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_WEBHOOK_UNKNOWN"] = 2019] = "MERCHANT_GENERIC_WEBHOOK_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_PENDING_WEBHOOK_UNKNOWN"] = 2020] = "MERCHANT_GENERIC_PENDING_WEBHOOK_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_OTP_DEVICE_UNKNOWN"] = 2021] = "MERCHANT_GENERIC_OTP_DEVICE_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_ACCOUNT_UNKNOWN"] = 2022] = "MERCHANT_GENERIC_ACCOUNT_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_H_WIRE_MALFORMED"] = 2023] = "MERCHANT_GENERIC_H_WIRE_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GENERIC_CURRENCY_MISMATCH"] = 2024] = "MERCHANT_GENERIC_CURRENCY_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GET_ORDERS_EXCHANGE_TRACKING_FAILURE"] = 2100] = "MERCHANT_GET_ORDERS_EXCHANGE_TRACKING_FAILURE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GET_ORDERS_ID_EXCHANGE_REQUEST_FAILURE"] = 2103] = "MERCHANT_GET_ORDERS_ID_EXCHANGE_REQUEST_FAILURE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GET_ORDERS_ID_EXCHANGE_LOOKUP_START_FAILURE"] = 2104] = "MERCHANT_GET_ORDERS_ID_EXCHANGE_LOOKUP_START_FAILURE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GET_ORDERS_ID_INVALID_TOKEN"] = 2105] = "MERCHANT_GET_ORDERS_ID_INVALID_TOKEN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_GET_ORDERS_ID_INVALID_CONTRACT_HASH"] = 2106] = "MERCHANT_GET_ORDERS_ID_INVALID_CONTRACT_HASH";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_INSUFFICIENT_FUNDS"] = 2150] = "MERCHANT_POST_ORDERS_ID_PAY_INSUFFICIENT_FUNDS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_DENOMINATION_KEY_NOT_FOUND"] = 2151] = "MERCHANT_POST_ORDERS_ID_PAY_DENOMINATION_KEY_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_DENOMINATION_KEY_AUDITOR_FAILURE"] = 2152] = "MERCHANT_POST_ORDERS_ID_PAY_DENOMINATION_KEY_AUDITOR_FAILURE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_AMOUNT_OVERFLOW"] = 2153] = "MERCHANT_POST_ORDERS_ID_PAY_AMOUNT_OVERFLOW";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_FEES_EXCEED_PAYMENT"] = 2154] = "MERCHANT_POST_ORDERS_ID_PAY_FEES_EXCEED_PAYMENT";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_INSUFFICIENT_DUE_TO_FEES"] = 2155] = "MERCHANT_POST_ORDERS_ID_PAY_INSUFFICIENT_DUE_TO_FEES";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_PAYMENT_INSUFFICIENT"] = 2156] = "MERCHANT_POST_ORDERS_ID_PAY_PAYMENT_INSUFFICIENT";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_COIN_SIGNATURE_INVALID"] = 2157] = "MERCHANT_POST_ORDERS_ID_PAY_COIN_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_LOOKUP_FAILED"] = 2158] = "MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_LOOKUP_FAILED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_REFUND_DEADLINE_PAST_WIRE_TRANSFER_DEADLINE"] = 2159] = "MERCHANT_POST_ORDERS_ID_PAY_REFUND_DEADLINE_PAST_WIRE_TRANSFER_DEADLINE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_ALREADY_PAID"] = 2160] = "MERCHANT_POST_ORDERS_ID_PAY_ALREADY_PAID";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_OFFER_EXPIRED"] = 2161] = "MERCHANT_POST_ORDERS_ID_PAY_OFFER_EXPIRED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_MERCHANT_FIELD_MISSING"] = 2162] = "MERCHANT_POST_ORDERS_ID_PAY_MERCHANT_FIELD_MISSING";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_WIRE_HASH_UNKNOWN"] = 2163] = "MERCHANT_POST_ORDERS_ID_PAY_WIRE_HASH_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_DENOMINATION_DEPOSIT_EXPIRED"] = 2165] = "MERCHANT_POST_ORDERS_ID_PAY_DENOMINATION_DEPOSIT_EXPIRED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_WIRE_FEE_ADDITION_FAILED"] = 2166] = "MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_WIRE_FEE_ADDITION_FAILED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_REFUNDED"] = 2167] = "MERCHANT_POST_ORDERS_ID_PAY_REFUNDED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_REFUNDS_EXCEED_PAYMENTS"] = 2168] = "MERCHANT_POST_ORDERS_ID_PAY_REFUNDS_EXCEED_PAYMENTS";
  TalerErrorCode2[TalerErrorCode2["DEAD_QQQ_PAY_MERCHANT_POST_ORDERS_ID_ABORT_REFUND_REFUSED_PAYMENT_COMPLETE"] = 2169] = "DEAD_QQQ_PAY_MERCHANT_POST_ORDERS_ID_ABORT_REFUND_REFUSED_PAYMENT_COMPLETE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_FAILED"] = 2170] = "MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_FAILED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_AGE_COMMITMENT_MISSING"] = 2171] = "MERCHANT_POST_ORDERS_ID_PAY_AGE_COMMITMENT_MISSING";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_AGE_COMMITMENT_SIZE_MISMATCH"] = 2172] = "MERCHANT_POST_ORDERS_ID_PAY_AGE_COMMITMENT_SIZE_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_AGE_VERIFICATION_FAILED"] = 2173] = "MERCHANT_POST_ORDERS_ID_PAY_AGE_VERIFICATION_FAILED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_AGE_COMMITMENT_HASH_MISSING"] = 2174] = "MERCHANT_POST_ORDERS_ID_PAY_AGE_COMMITMENT_HASH_MISSING";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_WIRE_METHOD_UNSUPPORTED"] = 2175] = "MERCHANT_POST_ORDERS_ID_PAY_WIRE_METHOD_UNSUPPORTED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_CHOICE_INDEX_MISSING"] = 2176] = "MERCHANT_POST_ORDERS_ID_PAY_CHOICE_INDEX_MISSING";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_CHOICE_INDEX_OUT_OF_BOUNDS"] = 2177] = "MERCHANT_POST_ORDERS_ID_PAY_CHOICE_INDEX_OUT_OF_BOUNDS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_INPUT_TOKENS_MISMATCH"] = 2178] = "MERCHANT_POST_ORDERS_ID_PAY_INPUT_TOKENS_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_TOKEN_ISSUE_SIG_INVALID"] = 2179] = "MERCHANT_POST_ORDERS_ID_PAY_TOKEN_ISSUE_SIG_INVALID";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_TOKEN_USE_SIG_INVALID"] = 2180] = "MERCHANT_POST_ORDERS_ID_PAY_TOKEN_USE_SIG_INVALID";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_TOKEN_COUNT_MISMATCH"] = 2181] = "MERCHANT_POST_ORDERS_ID_PAY_TOKEN_COUNT_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_TOKEN_ENVELOPE_COUNT_MISMATCH"] = 2182] = "MERCHANT_POST_ORDERS_ID_PAY_TOKEN_ENVELOPE_COUNT_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAY_TOKEN_INVALID"] = 2183] = "MERCHANT_POST_ORDERS_ID_PAY_TOKEN_INVALID";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAID_CONTRACT_HASH_MISMATCH"] = 2200] = "MERCHANT_POST_ORDERS_ID_PAID_CONTRACT_HASH_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_PAID_COIN_SIGNATURE_INVALID"] = 2201] = "MERCHANT_POST_ORDERS_ID_PAID_COIN_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_TOKEN_FAMILY_CONFLICT"] = 2225] = "MERCHANT_POST_TOKEN_FAMILY_CONFLICT";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PATCH_TOKEN_FAMILY_NOT_FOUND"] = 2226] = "MERCHANT_PATCH_TOKEN_FAMILY_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_ABORT_EXCHANGE_REFUND_FAILED"] = 2251] = "MERCHANT_POST_ORDERS_ID_ABORT_EXCHANGE_REFUND_FAILED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_ABORT_EXCHANGE_LOOKUP_FAILED"] = 2252] = "MERCHANT_POST_ORDERS_ID_ABORT_EXCHANGE_LOOKUP_FAILED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_ABORT_CONTRACT_NOT_FOUND"] = 2253] = "MERCHANT_POST_ORDERS_ID_ABORT_CONTRACT_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_ABORT_REFUND_REFUSED_PAYMENT_COMPLETE"] = 2254] = "MERCHANT_POST_ORDERS_ID_ABORT_REFUND_REFUSED_PAYMENT_COMPLETE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_ABORT_CONTRACT_HASH_MISSMATCH"] = 2255] = "MERCHANT_POST_ORDERS_ID_ABORT_CONTRACT_HASH_MISSMATCH";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_ABORT_COINS_ARRAY_EMPTY"] = 2256] = "MERCHANT_POST_ORDERS_ID_ABORT_COINS_ARRAY_EMPTY";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_EXCHANGE_TRANSFERS_AWAITING_KEYS"] = 2258] = "MERCHANT_EXCHANGE_TRANSFERS_AWAITING_KEYS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_EXCHANGE_TRANSFERS_AWAITING_LIST"] = 2259] = "MERCHANT_EXCHANGE_TRANSFERS_AWAITING_LIST";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_EXCHANGE_TRANSFERS_FATAL_NO_EXCHANGE"] = 2260] = "MERCHANT_EXCHANGE_TRANSFERS_FATAL_NO_EXCHANGE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_EXCHANGE_TRANSFERS_FATAL_NOT_FOUND"] = 2261] = "MERCHANT_EXCHANGE_TRANSFERS_FATAL_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_EXCHANGE_TRANSFERS_RATE_LIMITED"] = 2262] = "MERCHANT_EXCHANGE_TRANSFERS_RATE_LIMITED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_EXCHANGE_TRANSFERS_TRANSIENT_FAILURE"] = 2263] = "MERCHANT_EXCHANGE_TRANSFERS_TRANSIENT_FAILURE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_EXCHANGE_TRANSFERS_HARD_FAILURE"] = 2264] = "MERCHANT_EXCHANGE_TRANSFERS_HARD_FAILURE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_CLAIM_NOT_FOUND"] = 2300] = "MERCHANT_POST_ORDERS_ID_CLAIM_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_CLAIM_ALREADY_CLAIMED"] = 2301] = "MERCHANT_POST_ORDERS_ID_CLAIM_ALREADY_CLAIMED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_CLAIM_CLIENT_INTERNAL_FAILURE"] = 2302] = "MERCHANT_POST_ORDERS_ID_CLAIM_CLIENT_INTERNAL_FAILURE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_ORDERS_ID_REFUND_SIGNATURE_FAILED"] = 2350] = "MERCHANT_POST_ORDERS_ID_REFUND_SIGNATURE_FAILED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_REWARD_PICKUP_UNBLIND_FAILURE"] = 2400] = "MERCHANT_REWARD_PICKUP_UNBLIND_FAILURE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_REWARD_PICKUP_EXCHANGE_ERROR"] = 2403] = "MERCHANT_REWARD_PICKUP_EXCHANGE_ERROR";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_REWARD_PICKUP_SUMMATION_FAILED"] = 2404] = "MERCHANT_REWARD_PICKUP_SUMMATION_FAILED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_REWARD_PICKUP_HAS_EXPIRED"] = 2405] = "MERCHANT_REWARD_PICKUP_HAS_EXPIRED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_REWARD_PICKUP_AMOUNT_EXCEEDS_REWARD_REMAINING"] = 2406] = "MERCHANT_REWARD_PICKUP_AMOUNT_EXCEEDS_REWARD_REMAINING";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_REWARD_PICKUP_DENOMINATION_UNKNOWN"] = 2407] = "MERCHANT_REWARD_PICKUP_DENOMINATION_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_INSTANCE_CONFIGURATION_LACKS_WIRE"] = 2500] = "MERCHANT_PRIVATE_POST_ORDERS_INSTANCE_CONFIGURATION_LACKS_WIRE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_NO_LOCALTIME"] = 2501] = "MERCHANT_PRIVATE_POST_ORDERS_NO_LOCALTIME";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_PROPOSAL_PARSE_ERROR"] = 2502] = "MERCHANT_PRIVATE_POST_ORDERS_PROPOSAL_PARSE_ERROR";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_ALREADY_EXISTS"] = 2503] = "MERCHANT_PRIVATE_POST_ORDERS_ALREADY_EXISTS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_REFUND_AFTER_WIRE_DEADLINE"] = 2504] = "MERCHANT_PRIVATE_POST_ORDERS_REFUND_AFTER_WIRE_DEADLINE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_DELIVERY_DATE_IN_PAST"] = 2505] = "MERCHANT_PRIVATE_POST_ORDERS_DELIVERY_DATE_IN_PAST";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_WIRE_DEADLINE_IS_NEVER"] = 2506] = "MERCHANT_PRIVATE_POST_ORDERS_WIRE_DEADLINE_IS_NEVER";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_PAY_DEADLINE_IN_PAST"] = 2507] = "MERCHANT_PRIVATE_POST_ORDERS_PAY_DEADLINE_IN_PAST";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_REFUND_DEADLINE_IN_PAST"] = 2508] = "MERCHANT_PRIVATE_POST_ORDERS_REFUND_DEADLINE_IN_PAST";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_NO_EXCHANGES_FOR_WIRE_METHOD"] = 2509] = "MERCHANT_PRIVATE_POST_ORDERS_NO_EXCHANGES_FOR_WIRE_METHOD";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_PATCH_ORDERS_ID_FORGET_PATH_SYNTAX_INCORRECT"] = 2510] = "MERCHANT_PRIVATE_PATCH_ORDERS_ID_FORGET_PATH_SYNTAX_INCORRECT";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_PATCH_ORDERS_ID_FORGET_PATH_NOT_FORGETTABLE"] = 2511] = "MERCHANT_PRIVATE_PATCH_ORDERS_ID_FORGET_PATH_NOT_FORGETTABLE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_DELETE_ORDERS_AWAITING_PAYMENT"] = 2520] = "MERCHANT_PRIVATE_DELETE_ORDERS_AWAITING_PAYMENT";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_DELETE_ORDERS_ALREADY_PAID"] = 2521] = "MERCHANT_PRIVATE_DELETE_ORDERS_ALREADY_PAID";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_ID_REFUND_INCONSISTENT_AMOUNT"] = 2530] = "MERCHANT_PRIVATE_POST_ORDERS_ID_REFUND_INCONSISTENT_AMOUNT";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_ID_REFUND_ORDER_UNPAID"] = 2531] = "MERCHANT_PRIVATE_POST_ORDERS_ID_REFUND_ORDER_UNPAID";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_ID_REFUND_NOT_ALLOWED_BY_CONTRACT"] = 2532] = "MERCHANT_PRIVATE_POST_ORDERS_ID_REFUND_NOT_ALLOWED_BY_CONTRACT";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_TOKEN_FAMILY_SLUG_UNKNOWN"] = 2533] = "MERCHANT_PRIVATE_POST_ORDERS_TOKEN_FAMILY_SLUG_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_ORDERS_TOKEN_FAMILY_NOT_VALID"] = 2534] = "MERCHANT_PRIVATE_POST_ORDERS_TOKEN_FAMILY_NOT_VALID";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_TRANSFERS_EXCHANGE_UNKNOWN"] = 2550] = "MERCHANT_PRIVATE_POST_TRANSFERS_EXCHANGE_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_TRANSFERS_REQUEST_ERROR"] = 2551] = "MERCHANT_PRIVATE_POST_TRANSFERS_REQUEST_ERROR";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_TRANSFERS_CONFLICTING_TRANSFERS"] = 2552] = "MERCHANT_PRIVATE_POST_TRANSFERS_CONFLICTING_TRANSFERS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_TRANSFERS_CONFLICTING_REPORTS"] = 2553] = "MERCHANT_PRIVATE_POST_TRANSFERS_CONFLICTING_REPORTS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_TRANSFERS_BAD_WIRE_FEE"] = 2554] = "MERCHANT_PRIVATE_POST_TRANSFERS_BAD_WIRE_FEE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_TRANSFERS_ACCOUNT_NOT_FOUND"] = 2555] = "MERCHANT_PRIVATE_POST_TRANSFERS_ACCOUNT_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_DELETE_TRANSFERS_ALREADY_CONFIRMED"] = 2556] = "MERCHANT_PRIVATE_DELETE_TRANSFERS_ALREADY_CONFIRMED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_TRANSFERS_CONFLICTING_SUBMISSION"] = 2557] = "MERCHANT_PRIVATE_POST_TRANSFERS_CONFLICTING_SUBMISSION";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_EXCHANGE_TRANSFERS_CONFLICTING_TRANSFERS"] = 2563] = "MERCHANT_EXCHANGE_TRANSFERS_CONFLICTING_TRANSFERS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_INSTANCES_ALREADY_EXISTS"] = 2600] = "MERCHANT_PRIVATE_POST_INSTANCES_ALREADY_EXISTS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_INSTANCES_BAD_AUTH"] = 2601] = "MERCHANT_PRIVATE_POST_INSTANCES_BAD_AUTH";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_INSTANCE_AUTH_BAD_AUTH"] = 2602] = "MERCHANT_PRIVATE_POST_INSTANCE_AUTH_BAD_AUTH";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_INSTANCES_PURGE_REQUIRED"] = 2603] = "MERCHANT_PRIVATE_POST_INSTANCES_PURGE_REQUIRED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_PATCH_INSTANCES_PURGE_REQUIRED"] = 2625] = "MERCHANT_PRIVATE_PATCH_INSTANCES_PURGE_REQUIRED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_ACCOUNT_DELETE_UNKNOWN_ACCOUNT"] = 2626] = "MERCHANT_PRIVATE_ACCOUNT_DELETE_UNKNOWN_ACCOUNT";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_ACCOUNT_EXISTS"] = 2627] = "MERCHANT_PRIVATE_ACCOUNT_EXISTS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_PRODUCTS_CONFLICT_PRODUCT_EXISTS"] = 2650] = "MERCHANT_PRIVATE_POST_PRODUCTS_CONFLICT_PRODUCT_EXISTS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_CATEGORIES_CONFLICT_CATEGORY_EXISTS"] = 2651] = "MERCHANT_PRIVATE_POST_CATEGORIES_CONFLICT_CATEGORY_EXISTS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_PATCH_PRODUCTS_TOTAL_LOST_REDUCED"] = 2660] = "MERCHANT_PRIVATE_PATCH_PRODUCTS_TOTAL_LOST_REDUCED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_PATCH_PRODUCTS_TOTAL_LOST_EXCEEDS_STOCKS"] = 2661] = "MERCHANT_PRIVATE_PATCH_PRODUCTS_TOTAL_LOST_EXCEEDS_STOCKS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_PATCH_PRODUCTS_TOTAL_STOCKED_REDUCED"] = 2662] = "MERCHANT_PRIVATE_PATCH_PRODUCTS_TOTAL_STOCKED_REDUCED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_PATCH_PRODUCTS_TOTAL_SOLD_REDUCED"] = 2663] = "MERCHANT_PRIVATE_PATCH_PRODUCTS_TOTAL_SOLD_REDUCED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_PRODUCTS_LOCK_INSUFFICIENT_STOCKS"] = 2670] = "MERCHANT_PRIVATE_POST_PRODUCTS_LOCK_INSUFFICIENT_STOCKS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_DELETE_PRODUCTS_CONFLICTING_LOCK"] = 2680] = "MERCHANT_PRIVATE_DELETE_PRODUCTS_CONFLICTING_LOCK";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_RESERVES_UNSUPPORTED_WIRE_METHOD"] = 2700] = "MERCHANT_PRIVATE_POST_RESERVES_UNSUPPORTED_WIRE_METHOD";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_RESERVES_REWARDS_NOT_ALLOWED"] = 2701] = "MERCHANT_PRIVATE_POST_RESERVES_REWARDS_NOT_ALLOWED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_DELETE_RESERVES_NO_SUCH_RESERVE"] = 2710] = "MERCHANT_PRIVATE_DELETE_RESERVES_NO_SUCH_RESERVE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_REWARD_AUTHORIZE_RESERVE_EXPIRED"] = 2750] = "MERCHANT_PRIVATE_POST_REWARD_AUTHORIZE_RESERVE_EXPIRED";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_REWARD_AUTHORIZE_RESERVE_UNKNOWN"] = 2751] = "MERCHANT_PRIVATE_POST_REWARD_AUTHORIZE_RESERVE_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_REWARD_AUTHORIZE_INSUFFICIENT_FUNDS"] = 2752] = "MERCHANT_PRIVATE_POST_REWARD_AUTHORIZE_INSUFFICIENT_FUNDS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_REWARD_AUTHORIZE_RESERVE_NOT_FOUND"] = 2753] = "MERCHANT_PRIVATE_POST_REWARD_AUTHORIZE_RESERVE_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_GET_ORDERS_ID_AMOUNT_ARITHMETIC_FAILURE"] = 2800] = "MERCHANT_PRIVATE_GET_ORDERS_ID_AMOUNT_ARITHMETIC_FAILURE";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_TEMPLATES_CONFLICT_TEMPLATE_EXISTS"] = 2850] = "MERCHANT_PRIVATE_POST_TEMPLATES_CONFLICT_TEMPLATE_EXISTS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_OTP_DEVICES_CONFLICT_OTP_DEVICE_EXISTS"] = 2851] = "MERCHANT_PRIVATE_POST_OTP_DEVICES_CONFLICT_OTP_DEVICE_EXISTS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_USING_TEMPLATES_AMOUNT_CONFLICT_TEMPLATES_CONTRACT_AMOUNT"] = 2860] = "MERCHANT_POST_USING_TEMPLATES_AMOUNT_CONFLICT_TEMPLATES_CONTRACT_AMOUNT";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_USING_TEMPLATES_SUMMARY_CONFLICT_TEMPLATES_CONTRACT_SUBJECT"] = 2861] = "MERCHANT_POST_USING_TEMPLATES_SUMMARY_CONFLICT_TEMPLATES_CONTRACT_SUBJECT";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_USING_TEMPLATES_NO_AMOUNT"] = 2862] = "MERCHANT_POST_USING_TEMPLATES_NO_AMOUNT";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_POST_USING_TEMPLATES_NO_SUMMARY"] = 2863] = "MERCHANT_POST_USING_TEMPLATES_NO_SUMMARY";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_WEBHOOKS_CONFLICT_WEBHOOK_EXISTS"] = 2900] = "MERCHANT_PRIVATE_POST_WEBHOOKS_CONFLICT_WEBHOOK_EXISTS";
  TalerErrorCode2[TalerErrorCode2["MERCHANT_PRIVATE_POST_PENDING_WEBHOOKS_CONFLICT_PENDING_WEBHOOK_EXISTS"] = 2910] = "MERCHANT_PRIVATE_POST_PENDING_WEBHOOKS_CONFLICT_PENDING_WEBHOOK_EXISTS";
  TalerErrorCode2[TalerErrorCode2["AUDITOR_GENERIC_UNAUTHORIZED"] = 3001] = "AUDITOR_GENERIC_UNAUTHORIZED";
  TalerErrorCode2[TalerErrorCode2["AUDITOR_GENERIC_METHOD_NOT_ALLOWED"] = 3002] = "AUDITOR_GENERIC_METHOD_NOT_ALLOWED";
  TalerErrorCode2[TalerErrorCode2["AUDITOR_DEPOSIT_CONFIRMATION_SIGNATURE_INVALID"] = 3100] = "AUDITOR_DEPOSIT_CONFIRMATION_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["AUDITOR_EXCHANGE_SIGNING_KEY_REVOKED"] = 3101] = "AUDITOR_EXCHANGE_SIGNING_KEY_REVOKED";
  TalerErrorCode2[TalerErrorCode2["AUDITOR_RESOURCE_NOT_FOUND"] = 3102] = "AUDITOR_RESOURCE_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["AUDITOR_URI_MISSING_PATH_COMPONENT"] = 3103] = "AUDITOR_URI_MISSING_PATH_COMPONENT";
  TalerErrorCode2[TalerErrorCode2["BANK_SAME_ACCOUNT"] = 5101] = "BANK_SAME_ACCOUNT";
  TalerErrorCode2[TalerErrorCode2["BANK_UNALLOWED_DEBIT"] = 5102] = "BANK_UNALLOWED_DEBIT";
  TalerErrorCode2[TalerErrorCode2["BANK_NEGATIVE_NUMBER_AMOUNT"] = 5103] = "BANK_NEGATIVE_NUMBER_AMOUNT";
  TalerErrorCode2[TalerErrorCode2["BANK_NUMBER_TOO_BIG"] = 5104] = "BANK_NUMBER_TOO_BIG";
  TalerErrorCode2[TalerErrorCode2["BANK_UNKNOWN_ACCOUNT"] = 5106] = "BANK_UNKNOWN_ACCOUNT";
  TalerErrorCode2[TalerErrorCode2["BANK_TRANSACTION_NOT_FOUND"] = 5107] = "BANK_TRANSACTION_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["BANK_BAD_FORMAT_AMOUNT"] = 5108] = "BANK_BAD_FORMAT_AMOUNT";
  TalerErrorCode2[TalerErrorCode2["BANK_REJECT_NO_RIGHTS"] = 5109] = "BANK_REJECT_NO_RIGHTS";
  TalerErrorCode2[TalerErrorCode2["BANK_UNMANAGED_EXCEPTION"] = 5110] = "BANK_UNMANAGED_EXCEPTION";
  TalerErrorCode2[TalerErrorCode2["BANK_SOFT_EXCEPTION"] = 5111] = "BANK_SOFT_EXCEPTION";
  TalerErrorCode2[TalerErrorCode2["BANK_TRANSFER_REQUEST_UID_REUSED"] = 5112] = "BANK_TRANSFER_REQUEST_UID_REUSED";
  TalerErrorCode2[TalerErrorCode2["BANK_WITHDRAWAL_OPERATION_RESERVE_SELECTION_CONFLICT"] = 5113] = "BANK_WITHDRAWAL_OPERATION_RESERVE_SELECTION_CONFLICT";
  TalerErrorCode2[TalerErrorCode2["BANK_DUPLICATE_RESERVE_PUB_SUBJECT"] = 5114] = "BANK_DUPLICATE_RESERVE_PUB_SUBJECT";
  TalerErrorCode2[TalerErrorCode2["BANK_ANCIENT_TRANSACTION_GONE"] = 5115] = "BANK_ANCIENT_TRANSACTION_GONE";
  TalerErrorCode2[TalerErrorCode2["BANK_ABORT_CONFIRM_CONFLICT"] = 5116] = "BANK_ABORT_CONFIRM_CONFLICT";
  TalerErrorCode2[TalerErrorCode2["BANK_CONFIRM_ABORT_CONFLICT"] = 5117] = "BANK_CONFIRM_ABORT_CONFLICT";
  TalerErrorCode2[TalerErrorCode2["BANK_REGISTER_CONFLICT"] = 5118] = "BANK_REGISTER_CONFLICT";
  TalerErrorCode2[TalerErrorCode2["BANK_POST_WITHDRAWAL_OPERATION_REQUIRED"] = 5119] = "BANK_POST_WITHDRAWAL_OPERATION_REQUIRED";
  TalerErrorCode2[TalerErrorCode2["BANK_RESERVED_USERNAME_CONFLICT"] = 5120] = "BANK_RESERVED_USERNAME_CONFLICT";
  TalerErrorCode2[TalerErrorCode2["BANK_REGISTER_USERNAME_REUSE"] = 5121] = "BANK_REGISTER_USERNAME_REUSE";
  TalerErrorCode2[TalerErrorCode2["BANK_REGISTER_PAYTO_URI_REUSE"] = 5122] = "BANK_REGISTER_PAYTO_URI_REUSE";
  TalerErrorCode2[TalerErrorCode2["BANK_ACCOUNT_BALANCE_NOT_ZERO"] = 5123] = "BANK_ACCOUNT_BALANCE_NOT_ZERO";
  TalerErrorCode2[TalerErrorCode2["BANK_UNKNOWN_CREDITOR"] = 5124] = "BANK_UNKNOWN_CREDITOR";
  TalerErrorCode2[TalerErrorCode2["BANK_UNKNOWN_DEBTOR"] = 5125] = "BANK_UNKNOWN_DEBTOR";
  TalerErrorCode2[TalerErrorCode2["BANK_ACCOUNT_IS_EXCHANGE"] = 5126] = "BANK_ACCOUNT_IS_EXCHANGE";
  TalerErrorCode2[TalerErrorCode2["BANK_ACCOUNT_IS_NOT_EXCHANGE"] = 5127] = "BANK_ACCOUNT_IS_NOT_EXCHANGE";
  TalerErrorCode2[TalerErrorCode2["BANK_BAD_CONVERSION"] = 5128] = "BANK_BAD_CONVERSION";
  TalerErrorCode2[TalerErrorCode2["BANK_MISSING_TAN_INFO"] = 5129] = "BANK_MISSING_TAN_INFO";
  TalerErrorCode2[TalerErrorCode2["BANK_CONFIRM_INCOMPLETE"] = 5130] = "BANK_CONFIRM_INCOMPLETE";
  TalerErrorCode2[TalerErrorCode2["BANK_TAN_RATE_LIMITED"] = 5131] = "BANK_TAN_RATE_LIMITED";
  TalerErrorCode2[TalerErrorCode2["BANK_TAN_CHANNEL_NOT_SUPPORTED"] = 5132] = "BANK_TAN_CHANNEL_NOT_SUPPORTED";
  TalerErrorCode2[TalerErrorCode2["BANK_TAN_CHANNEL_SCRIPT_FAILED"] = 5133] = "BANK_TAN_CHANNEL_SCRIPT_FAILED";
  TalerErrorCode2[TalerErrorCode2["BANK_TAN_CHALLENGE_FAILED"] = 5134] = "BANK_TAN_CHALLENGE_FAILED";
  TalerErrorCode2[TalerErrorCode2["BANK_NON_ADMIN_PATCH_LEGAL_NAME"] = 5135] = "BANK_NON_ADMIN_PATCH_LEGAL_NAME";
  TalerErrorCode2[TalerErrorCode2["BANK_NON_ADMIN_PATCH_DEBT_LIMIT"] = 5136] = "BANK_NON_ADMIN_PATCH_DEBT_LIMIT";
  TalerErrorCode2[TalerErrorCode2["BANK_NON_ADMIN_PATCH_MISSING_OLD_PASSWORD"] = 5137] = "BANK_NON_ADMIN_PATCH_MISSING_OLD_PASSWORD";
  TalerErrorCode2[TalerErrorCode2["BANK_PATCH_BAD_OLD_PASSWORD"] = 5138] = "BANK_PATCH_BAD_OLD_PASSWORD";
  TalerErrorCode2[TalerErrorCode2["BANK_PATCH_ADMIN_EXCHANGE"] = 5139] = "BANK_PATCH_ADMIN_EXCHANGE";
  TalerErrorCode2[TalerErrorCode2["BANK_NON_ADMIN_PATCH_CASHOUT"] = 5140] = "BANK_NON_ADMIN_PATCH_CASHOUT";
  TalerErrorCode2[TalerErrorCode2["BANK_NON_ADMIN_PATCH_CONTACT"] = 5141] = "BANK_NON_ADMIN_PATCH_CONTACT";
  TalerErrorCode2[TalerErrorCode2["BANK_ADMIN_CREDITOR"] = 5142] = "BANK_ADMIN_CREDITOR";
  TalerErrorCode2[TalerErrorCode2["BANK_CHALLENGE_NOT_FOUND"] = 5143] = "BANK_CHALLENGE_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["BANK_TAN_CHALLENGE_EXPIRED"] = 5144] = "BANK_TAN_CHALLENGE_EXPIRED";
  TalerErrorCode2[TalerErrorCode2["BANK_NON_ADMIN_SET_TAN_CHANNEL"] = 5145] = "BANK_NON_ADMIN_SET_TAN_CHANNEL";
  TalerErrorCode2[TalerErrorCode2["BANK_NON_ADMIN_SET_MIN_CASHOUT"] = 5146] = "BANK_NON_ADMIN_SET_MIN_CASHOUT";
  TalerErrorCode2[TalerErrorCode2["BANK_CONVERSION_AMOUNT_TO_SMALL"] = 5147] = "BANK_CONVERSION_AMOUNT_TO_SMALL";
  TalerErrorCode2[TalerErrorCode2["BANK_AMOUNT_DIFFERS"] = 5148] = "BANK_AMOUNT_DIFFERS";
  TalerErrorCode2[TalerErrorCode2["BANK_AMOUNT_REQUIRED"] = 5149] = "BANK_AMOUNT_REQUIRED";
  TalerErrorCode2[TalerErrorCode2["SYNC_ACCOUNT_UNKNOWN"] = 6100] = "SYNC_ACCOUNT_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["SYNC_BAD_IF_NONE_MATCH"] = 6101] = "SYNC_BAD_IF_NONE_MATCH";
  TalerErrorCode2[TalerErrorCode2["SYNC_BAD_IF_MATCH"] = 6102] = "SYNC_BAD_IF_MATCH";
  TalerErrorCode2[TalerErrorCode2["SYNC_BAD_SYNC_SIGNATURE"] = 6103] = "SYNC_BAD_SYNC_SIGNATURE";
  TalerErrorCode2[TalerErrorCode2["SYNC_INVALID_SIGNATURE"] = 6104] = "SYNC_INVALID_SIGNATURE";
  TalerErrorCode2[TalerErrorCode2["SYNC_MALFORMED_CONTENT_LENGTH"] = 6105] = "SYNC_MALFORMED_CONTENT_LENGTH";
  TalerErrorCode2[TalerErrorCode2["SYNC_EXCESSIVE_CONTENT_LENGTH"] = 6106] = "SYNC_EXCESSIVE_CONTENT_LENGTH";
  TalerErrorCode2[TalerErrorCode2["SYNC_OUT_OF_MEMORY_ON_CONTENT_LENGTH"] = 6107] = "SYNC_OUT_OF_MEMORY_ON_CONTENT_LENGTH";
  TalerErrorCode2[TalerErrorCode2["SYNC_INVALID_UPLOAD"] = 6108] = "SYNC_INVALID_UPLOAD";
  TalerErrorCode2[TalerErrorCode2["SYNC_PAYMENT_GENERIC_TIMEOUT"] = 6109] = "SYNC_PAYMENT_GENERIC_TIMEOUT";
  TalerErrorCode2[TalerErrorCode2["SYNC_PAYMENT_CREATE_BACKEND_ERROR"] = 6110] = "SYNC_PAYMENT_CREATE_BACKEND_ERROR";
  TalerErrorCode2[TalerErrorCode2["SYNC_PREVIOUS_BACKUP_UNKNOWN"] = 6111] = "SYNC_PREVIOUS_BACKUP_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["SYNC_MISSING_CONTENT_LENGTH"] = 6112] = "SYNC_MISSING_CONTENT_LENGTH";
  TalerErrorCode2[TalerErrorCode2["SYNC_GENERIC_BACKEND_ERROR"] = 6113] = "SYNC_GENERIC_BACKEND_ERROR";
  TalerErrorCode2[TalerErrorCode2["SYNC_GENERIC_BACKEND_TIMEOUT"] = 6114] = "SYNC_GENERIC_BACKEND_TIMEOUT";
  TalerErrorCode2[TalerErrorCode2["WALLET_EXCHANGE_PROTOCOL_VERSION_INCOMPATIBLE"] = 7e3] = "WALLET_EXCHANGE_PROTOCOL_VERSION_INCOMPATIBLE";
  TalerErrorCode2[TalerErrorCode2["WALLET_UNEXPECTED_EXCEPTION"] = 7001] = "WALLET_UNEXPECTED_EXCEPTION";
  TalerErrorCode2[TalerErrorCode2["WALLET_RECEIVED_MALFORMED_RESPONSE"] = 7002] = "WALLET_RECEIVED_MALFORMED_RESPONSE";
  TalerErrorCode2[TalerErrorCode2["WALLET_NETWORK_ERROR"] = 7003] = "WALLET_NETWORK_ERROR";
  TalerErrorCode2[TalerErrorCode2["WALLET_HTTP_REQUEST_THROTTLED"] = 7004] = "WALLET_HTTP_REQUEST_THROTTLED";
  TalerErrorCode2[TalerErrorCode2["WALLET_UNEXPECTED_REQUEST_ERROR"] = 7005] = "WALLET_UNEXPECTED_REQUEST_ERROR";
  TalerErrorCode2[TalerErrorCode2["WALLET_EXCHANGE_DENOMINATIONS_INSUFFICIENT"] = 7006] = "WALLET_EXCHANGE_DENOMINATIONS_INSUFFICIENT";
  TalerErrorCode2[TalerErrorCode2["WALLET_CORE_API_OPERATION_UNKNOWN"] = 7007] = "WALLET_CORE_API_OPERATION_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["WALLET_INVALID_TALER_PAY_URI"] = 7008] = "WALLET_INVALID_TALER_PAY_URI";
  TalerErrorCode2[TalerErrorCode2["WALLET_EXCHANGE_COIN_SIGNATURE_INVALID"] = 7009] = "WALLET_EXCHANGE_COIN_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["WALLET_EXCHANGE_WITHDRAW_RESERVE_UNKNOWN_AT_EXCHANGE"] = 7010] = "WALLET_EXCHANGE_WITHDRAW_RESERVE_UNKNOWN_AT_EXCHANGE";
  TalerErrorCode2[TalerErrorCode2["WALLET_CORE_NOT_AVAILABLE"] = 7011] = "WALLET_CORE_NOT_AVAILABLE";
  TalerErrorCode2[TalerErrorCode2["WALLET_WITHDRAWAL_OPERATION_ABORTED_BY_BANK"] = 7012] = "WALLET_WITHDRAWAL_OPERATION_ABORTED_BY_BANK";
  TalerErrorCode2[TalerErrorCode2["WALLET_HTTP_REQUEST_GENERIC_TIMEOUT"] = 7013] = "WALLET_HTTP_REQUEST_GENERIC_TIMEOUT";
  TalerErrorCode2[TalerErrorCode2["WALLET_ORDER_ALREADY_CLAIMED"] = 7014] = "WALLET_ORDER_ALREADY_CLAIMED";
  TalerErrorCode2[TalerErrorCode2["WALLET_WITHDRAWAL_GROUP_INCOMPLETE"] = 7015] = "WALLET_WITHDRAWAL_GROUP_INCOMPLETE";
  TalerErrorCode2[TalerErrorCode2["WALLET_REWARD_COIN_SIGNATURE_INVALID"] = 7016] = "WALLET_REWARD_COIN_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["WALLET_BANK_INTEGRATION_PROTOCOL_VERSION_INCOMPATIBLE"] = 7017] = "WALLET_BANK_INTEGRATION_PROTOCOL_VERSION_INCOMPATIBLE";
  TalerErrorCode2[TalerErrorCode2["WALLET_CONTRACT_TERMS_BASE_URL_MISMATCH"] = 7018] = "WALLET_CONTRACT_TERMS_BASE_URL_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["WALLET_CONTRACT_TERMS_SIGNATURE_INVALID"] = 7019] = "WALLET_CONTRACT_TERMS_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["WALLET_CONTRACT_TERMS_MALFORMED"] = 7020] = "WALLET_CONTRACT_TERMS_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["WALLET_PENDING_OPERATION_FAILED"] = 7021] = "WALLET_PENDING_OPERATION_FAILED";
  TalerErrorCode2[TalerErrorCode2["WALLET_PAY_MERCHANT_SERVER_ERROR"] = 7022] = "WALLET_PAY_MERCHANT_SERVER_ERROR";
  TalerErrorCode2[TalerErrorCode2["WALLET_CRYPTO_WORKER_ERROR"] = 7023] = "WALLET_CRYPTO_WORKER_ERROR";
  TalerErrorCode2[TalerErrorCode2["WALLET_CRYPTO_WORKER_BAD_REQUEST"] = 7024] = "WALLET_CRYPTO_WORKER_BAD_REQUEST";
  TalerErrorCode2[TalerErrorCode2["WALLET_WITHDRAWAL_KYC_REQUIRED"] = 7025] = "WALLET_WITHDRAWAL_KYC_REQUIRED";
  TalerErrorCode2[TalerErrorCode2["WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE"] = 7026] = "WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE";
  TalerErrorCode2[TalerErrorCode2["WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE"] = 7027] = "WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE";
  TalerErrorCode2[TalerErrorCode2["WALLET_PEER_PULL_PAYMENT_INSUFFICIENT_BALANCE"] = 7028] = "WALLET_PEER_PULL_PAYMENT_INSUFFICIENT_BALANCE";
  TalerErrorCode2[TalerErrorCode2["WALLET_REFRESH_GROUP_INCOMPLETE"] = 7029] = "WALLET_REFRESH_GROUP_INCOMPLETE";
  TalerErrorCode2[TalerErrorCode2["WALLET_EXCHANGE_BASE_URL_MISMATCH"] = 7030] = "WALLET_EXCHANGE_BASE_URL_MISMATCH";
  TalerErrorCode2[TalerErrorCode2["WALLET_ORDER_ALREADY_PAID"] = 7031] = "WALLET_ORDER_ALREADY_PAID";
  TalerErrorCode2[TalerErrorCode2["WALLET_EXCHANGE_UNAVAILABLE"] = 7032] = "WALLET_EXCHANGE_UNAVAILABLE";
  TalerErrorCode2[TalerErrorCode2["WALLET_EXCHANGE_ENTRY_USED"] = 7033] = "WALLET_EXCHANGE_ENTRY_USED";
  TalerErrorCode2[TalerErrorCode2["WALLET_DB_UNAVAILABLE"] = 7034] = "WALLET_DB_UNAVAILABLE";
  TalerErrorCode2[TalerErrorCode2["WALLET_TALER_URI_MALFORMED"] = 7035] = "WALLET_TALER_URI_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["WALLET_CORE_REQUEST_CANCELLED"] = 7036] = "WALLET_CORE_REQUEST_CANCELLED";
  TalerErrorCode2[TalerErrorCode2["WALLET_EXCHANGE_TOS_NOT_ACCEPTED"] = 7037] = "WALLET_EXCHANGE_TOS_NOT_ACCEPTED";
  TalerErrorCode2[TalerErrorCode2["WALLET_EXCHANGE_ENTRY_UPDATE_CONFLICT"] = 7038] = "WALLET_EXCHANGE_ENTRY_UPDATE_CONFLICT";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_GENERIC_BACKEND_TIMEOUT"] = 8e3] = "ANASTASIS_GENERIC_BACKEND_TIMEOUT";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_GENERIC_INVALID_PAYMENT_REQUEST"] = 8001] = "ANASTASIS_GENERIC_INVALID_PAYMENT_REQUEST";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_GENERIC_BACKEND_ERROR"] = 8002] = "ANASTASIS_GENERIC_BACKEND_ERROR";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_GENERIC_MISSING_CONTENT_LENGTH"] = 8003] = "ANASTASIS_GENERIC_MISSING_CONTENT_LENGTH";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_GENERIC_MALFORMED_CONTENT_LENGTH"] = 8004] = "ANASTASIS_GENERIC_MALFORMED_CONTENT_LENGTH";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_GENERIC_ORDER_CREATE_BACKEND_ERROR"] = 8005] = "ANASTASIS_GENERIC_ORDER_CREATE_BACKEND_ERROR";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_GENERIC_PAYMENT_CHECK_UNAUTHORIZED"] = 8006] = "ANASTASIS_GENERIC_PAYMENT_CHECK_UNAUTHORIZED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_GENERIC_PAYMENT_CHECK_START_FAILED"] = 8007] = "ANASTASIS_GENERIC_PAYMENT_CHECK_START_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_GENERIC_PROVIDER_UNREACHABLE"] = 8008] = "ANASTASIS_GENERIC_PROVIDER_UNREACHABLE";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_PAYMENT_GENERIC_TIMEOUT"] = 8009] = "ANASTASIS_PAYMENT_GENERIC_TIMEOUT";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_UNKNOWN"] = 8108] = "ANASTASIS_TRUTH_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_AUTHORIZATION_METHOD_NO_LONGER_SUPPORTED"] = 8109] = "ANASTASIS_TRUTH_AUTHORIZATION_METHOD_NO_LONGER_SUPPORTED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_CHALLENGE_RESPONSE_REQUIRED"] = 8110] = "ANASTASIS_TRUTH_CHALLENGE_RESPONSE_REQUIRED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_CHALLENGE_FAILED"] = 8111] = "ANASTASIS_TRUTH_CHALLENGE_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_CHALLENGE_UNKNOWN"] = 8112] = "ANASTASIS_TRUTH_CHALLENGE_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_AUTHORIZATION_START_FAILED"] = 8114] = "ANASTASIS_TRUTH_AUTHORIZATION_START_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_KEY_SHARE_GONE"] = 8115] = "ANASTASIS_TRUTH_KEY_SHARE_GONE";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_ORDER_DISAPPEARED"] = 8116] = "ANASTASIS_TRUTH_ORDER_DISAPPEARED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_BACKEND_EXCHANGE_BAD"] = 8117] = "ANASTASIS_TRUTH_BACKEND_EXCHANGE_BAD";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_UNEXPECTED_PAYMENT_STATUS"] = 8118] = "ANASTASIS_TRUTH_UNEXPECTED_PAYMENT_STATUS";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_PAYMENT_CREATE_BACKEND_ERROR"] = 8119] = "ANASTASIS_TRUTH_PAYMENT_CREATE_BACKEND_ERROR";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_DECRYPTION_FAILED"] = 8120] = "ANASTASIS_TRUTH_DECRYPTION_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_RATE_LIMITED"] = 8121] = "ANASTASIS_TRUTH_RATE_LIMITED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_CHALLENGE_WRONG_METHOD"] = 8123] = "ANASTASIS_TRUTH_CHALLENGE_WRONG_METHOD";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_UPLOAD_UUID_EXISTS"] = 8150] = "ANASTASIS_TRUTH_UPLOAD_UUID_EXISTS";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TRUTH_UPLOAD_METHOD_NOT_SUPPORTED"] = 8151] = "ANASTASIS_TRUTH_UPLOAD_METHOD_NOT_SUPPORTED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_SMS_PHONE_INVALID"] = 8200] = "ANASTASIS_SMS_PHONE_INVALID";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_SMS_HELPER_EXEC_FAILED"] = 8201] = "ANASTASIS_SMS_HELPER_EXEC_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_SMS_HELPER_COMMAND_FAILED"] = 8202] = "ANASTASIS_SMS_HELPER_COMMAND_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_EMAIL_INVALID"] = 8210] = "ANASTASIS_EMAIL_INVALID";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_EMAIL_HELPER_EXEC_FAILED"] = 8211] = "ANASTASIS_EMAIL_HELPER_EXEC_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_EMAIL_HELPER_COMMAND_FAILED"] = 8212] = "ANASTASIS_EMAIL_HELPER_COMMAND_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_POST_INVALID"] = 8220] = "ANASTASIS_POST_INVALID";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_POST_HELPER_EXEC_FAILED"] = 8221] = "ANASTASIS_POST_HELPER_EXEC_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_POST_HELPER_COMMAND_FAILED"] = 8222] = "ANASTASIS_POST_HELPER_COMMAND_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_IBAN_INVALID"] = 8230] = "ANASTASIS_IBAN_INVALID";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_IBAN_MISSING_TRANSFER"] = 8231] = "ANASTASIS_IBAN_MISSING_TRANSFER";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TOTP_KEY_MISSING"] = 8240] = "ANASTASIS_TOTP_KEY_MISSING";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_TOTP_KEY_INVALID"] = 8241] = "ANASTASIS_TOTP_KEY_INVALID";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_POLICY_BAD_IF_NONE_MATCH"] = 8301] = "ANASTASIS_POLICY_BAD_IF_NONE_MATCH";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_POLICY_OUT_OF_MEMORY_ON_CONTENT_LENGTH"] = 8304] = "ANASTASIS_POLICY_OUT_OF_MEMORY_ON_CONTENT_LENGTH";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_POLICY_BAD_SIGNATURE"] = 8305] = "ANASTASIS_POLICY_BAD_SIGNATURE";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_POLICY_BAD_IF_MATCH"] = 8306] = "ANASTASIS_POLICY_BAD_IF_MATCH";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_POLICY_INVALID_UPLOAD"] = 8307] = "ANASTASIS_POLICY_INVALID_UPLOAD";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_POLICY_NOT_FOUND"] = 8350] = "ANASTASIS_POLICY_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_ACTION_INVALID"] = 8400] = "ANASTASIS_REDUCER_ACTION_INVALID";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_STATE_INVALID"] = 8401] = "ANASTASIS_REDUCER_STATE_INVALID";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_INPUT_INVALID"] = 8402] = "ANASTASIS_REDUCER_INPUT_INVALID";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_AUTHENTICATION_METHOD_NOT_SUPPORTED"] = 8403] = "ANASTASIS_REDUCER_AUTHENTICATION_METHOD_NOT_SUPPORTED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_INPUT_INVALID_FOR_STATE"] = 8404] = "ANASTASIS_REDUCER_INPUT_INVALID_FOR_STATE";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_BACKEND_FAILURE"] = 8405] = "ANASTASIS_REDUCER_BACKEND_FAILURE";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_RESOURCE_MALFORMED"] = 8406] = "ANASTASIS_REDUCER_RESOURCE_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_RESOURCE_MISSING"] = 8407] = "ANASTASIS_REDUCER_RESOURCE_MISSING";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_INPUT_REGEX_FAILED"] = 8408] = "ANASTASIS_REDUCER_INPUT_REGEX_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_INPUT_VALIDATION_FAILED"] = 8409] = "ANASTASIS_REDUCER_INPUT_VALIDATION_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_POLICY_LOOKUP_FAILED"] = 8410] = "ANASTASIS_REDUCER_POLICY_LOOKUP_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_BACKUP_PROVIDER_FAILED"] = 8411] = "ANASTASIS_REDUCER_BACKUP_PROVIDER_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_PROVIDER_CONFIG_FAILED"] = 8412] = "ANASTASIS_REDUCER_PROVIDER_CONFIG_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_POLICY_MALFORMED"] = 8413] = "ANASTASIS_REDUCER_POLICY_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_NETWORK_FAILED"] = 8414] = "ANASTASIS_REDUCER_NETWORK_FAILED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_SECRET_MALFORMED"] = 8415] = "ANASTASIS_REDUCER_SECRET_MALFORMED";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_CHALLENGE_DATA_TOO_BIG"] = 8416] = "ANASTASIS_REDUCER_CHALLENGE_DATA_TOO_BIG";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_SECRET_TOO_BIG"] = 8417] = "ANASTASIS_REDUCER_SECRET_TOO_BIG";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_PROVIDER_INVALID_CONFIG"] = 8418] = "ANASTASIS_REDUCER_PROVIDER_INVALID_CONFIG";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_INTERNAL_ERROR"] = 8419] = "ANASTASIS_REDUCER_INTERNAL_ERROR";
  TalerErrorCode2[TalerErrorCode2["ANASTASIS_REDUCER_PROVIDERS_ALREADY_SYNCED"] = 8420] = "ANASTASIS_REDUCER_PROVIDERS_ALREADY_SYNCED";
  TalerErrorCode2[TalerErrorCode2["DONAU_GENERIC_KEYS_MISSING"] = 8607] = "DONAU_GENERIC_KEYS_MISSING";
  TalerErrorCode2[TalerErrorCode2["DONAU_CHARITY_SIGNATURE_INVALID"] = 8608] = "DONAU_CHARITY_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["DONAU_CHARITY_NOT_FOUND"] = 8609] = "DONAU_CHARITY_NOT_FOUND";
  TalerErrorCode2[TalerErrorCode2["DONAU_EXCEEDING_DONATION_LIMIT"] = 8610] = "DONAU_EXCEEDING_DONATION_LIMIT";
  TalerErrorCode2[TalerErrorCode2["DONAU_GENERIC_DONATION_UNIT_UNKNOWN"] = 8611] = "DONAU_GENERIC_DONATION_UNIT_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["DONAU_DONATION_UNIT_HELPER_UNAVAILABLE"] = 8612] = "DONAU_DONATION_UNIT_HELPER_UNAVAILABLE";
  TalerErrorCode2[TalerErrorCode2["DONAU_SIGNKEY_HELPER_UNAVAILABLE"] = 8613] = "DONAU_SIGNKEY_HELPER_UNAVAILABLE";
  TalerErrorCode2[TalerErrorCode2["DONAU_SIGNKEY_HELPER_BUG"] = 8614] = "DONAU_SIGNKEY_HELPER_BUG";
  TalerErrorCode2[TalerErrorCode2["DONAU_GENERIC_WRONG_NUMBER_OF_SEGMENTS"] = 8615] = "DONAU_GENERIC_WRONG_NUMBER_OF_SEGMENTS";
  TalerErrorCode2[TalerErrorCode2["DONAU_DONATION_RECEIPT_SIGNATURE_INVALID"] = 8616] = "DONAU_DONATION_RECEIPT_SIGNATURE_INVALID";
  TalerErrorCode2[TalerErrorCode2["DONAU_DONOR_IDENTIFIER_NONCE_REUSE"] = 8617] = "DONAU_DONOR_IDENTIFIER_NONCE_REUSE";
  TalerErrorCode2[TalerErrorCode2["LIBEUFIN_NEXUS_GENERIC_ERROR"] = 9e3] = "LIBEUFIN_NEXUS_GENERIC_ERROR";
  TalerErrorCode2[TalerErrorCode2["LIBEUFIN_NEXUS_UNCAUGHT_EXCEPTION"] = 9001] = "LIBEUFIN_NEXUS_UNCAUGHT_EXCEPTION";
  TalerErrorCode2[TalerErrorCode2["LIBEUFIN_SANDBOX_GENERIC_ERROR"] = 9500] = "LIBEUFIN_SANDBOX_GENERIC_ERROR";
  TalerErrorCode2[TalerErrorCode2["LIBEUFIN_SANDBOX_UNCAUGHT_EXCEPTION"] = 9501] = "LIBEUFIN_SANDBOX_UNCAUGHT_EXCEPTION";
  TalerErrorCode2[TalerErrorCode2["TALDIR_METHOD_NOT_SUPPORTED"] = 9600] = "TALDIR_METHOD_NOT_SUPPORTED";
  TalerErrorCode2[TalerErrorCode2["TALDIR_REGISTER_RATE_LIMITED"] = 9601] = "TALDIR_REGISTER_RATE_LIMITED";
  TalerErrorCode2[TalerErrorCode2["CHALLENGER_GENERIC_CLIENT_UNKNOWN"] = 9750] = "CHALLENGER_GENERIC_CLIENT_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["CHALLENGER_GENERIC_CLIENT_FORBIDDEN_BAD_REDIRECT_URI"] = 9751] = "CHALLENGER_GENERIC_CLIENT_FORBIDDEN_BAD_REDIRECT_URI";
  TalerErrorCode2[TalerErrorCode2["CHALLENGER_HELPER_EXEC_FAILED"] = 9752] = "CHALLENGER_HELPER_EXEC_FAILED";
  TalerErrorCode2[TalerErrorCode2["CHALLENGER_GRANT_UNKNOWN"] = 9753] = "CHALLENGER_GRANT_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["CHALLENGER_CLIENT_FORBIDDEN_BAD_CODE"] = 9754] = "CHALLENGER_CLIENT_FORBIDDEN_BAD_CODE";
  TalerErrorCode2[TalerErrorCode2["CHALLENGER_GENERIC_VALIDATION_UNKNOWN"] = 9755] = "CHALLENGER_GENERIC_VALIDATION_UNKNOWN";
  TalerErrorCode2[TalerErrorCode2["CHALLENGER_CLIENT_FORBIDDEN_INVALID_CODE"] = 9756] = "CHALLENGER_CLIENT_FORBIDDEN_INVALID_CODE";
  TalerErrorCode2[TalerErrorCode2["CHALLENGER_TOO_MANY_ATTEMPTS"] = 9757] = "CHALLENGER_TOO_MANY_ATTEMPTS";
  TalerErrorCode2[TalerErrorCode2["CHALLENGER_INVALID_PIN"] = 9758] = "CHALLENGER_INVALID_PIN";
  TalerErrorCode2[TalerErrorCode2["CHALLENGER_MISSING_ADDRESS"] = 9759] = "CHALLENGER_MISSING_ADDRESS";
  TalerErrorCode2[TalerErrorCode2["END"] = 9999] = "END";
})(TalerErrorCode || (TalerErrorCode = {}));

// ../taler-util/lib/CancellationToken.js
var NOOP = () => {
};
var CancellationToken = class _CancellationToken {
  /**
   * Whether the token has been cancelled.
   */
  get isCancelled() {
    return this._isCancelled;
  }
  /**
   * Whether the token can be cancelled.
   */
  get canBeCancelled() {
    return this._canBeCancelled;
  }
  /**
   * Why this token has been cancelled.
   */
  get reason() {
    if (this.isCancelled) {
      return this._reason;
    } else {
      throw new Error("This token is not cancelled.");
    }
  }
  /**
   * Make a promise that resolves when the async operation resolves,
   * or rejects when the operation is rejected or this token is cancelled.
   */
  racePromise(asyncOperation) {
    if (!this.canBeCancelled) {
      return asyncOperation;
    }
    return new Promise((resolve, reject) => {
      const unregister = this.onCancelled((reason) => reject(new _CancellationToken.CancellationError(reason)));
      asyncOperation.then((value) => {
        resolve(value);
        unregister();
      }, (err2) => {
        reject(err2);
        unregister();
      });
    });
  }
  /**
   * Throw a {CancellationToken.CancellationError} if this token is cancelled.
   */
  throwIfCancelled() {
    if (this._isCancelled) {
      throw new _CancellationToken.CancellationError(this._reason);
    }
  }
  /**
   * Invoke the callback when this token is cancelled.
   * If this token is already cancelled, the callback is invoked immediately.
   * Returns a function that unregisters the cancellation callback.
   */
  onCancelled(cb) {
    if (!this.canBeCancelled) {
      return NOOP;
    }
    if (this.isCancelled) {
      cb(this.reason);
      return NOOP;
    }
    this._callbacks?.add(cb);
    return () => this._callbacks?.delete(cb);
  }
  constructor(_isCancelled, _canBeCancelled) {
    this._isCancelled = _isCancelled;
    this._canBeCancelled = _canBeCancelled;
    this._callbacks = /* @__PURE__ */ new Set();
  }
  /**
   * Create a {CancellationTokenSource}.
   */
  static create() {
    const token = new _CancellationToken(false, true);
    const cancel = (reason) => {
      if (token._isCancelled)
        return;
      token._isCancelled = true;
      token._reason = reason;
      token._callbacks?.forEach((cb) => cb(reason));
      dispose();
    };
    const dispose = () => {
      token._canBeCancelled = token.isCancelled;
      delete token._callbacks;
    };
    return { token, cancel, dispose };
  }
  /**
   * Create a {CancellationTokenSource}.
   * The token will be cancelled automatically after the specified timeout in milliseconds.
   */
  static timeout(ms) {
    const { token, cancel: originalCancel, dispose: originalDispose } = _CancellationToken.create();
    let timer2;
    timer2 = setTimeout(() => originalCancel(`CancellationToken.timeout ${ms}`), ms);
    const disposeTimer = () => {
      if (timer2 == null)
        return;
      clearTimeout(timer2);
      timer2 = null;
    };
    const cancel = (reason) => {
      disposeTimer();
      originalCancel(reason);
    };
    const dispose = () => {
      disposeTimer();
      originalDispose();
    };
    return { token, cancel, dispose };
  }
  /**
   * Create a {CancellationToken} that is cancelled when all of the given tokens are cancelled.
   *
   * This is like {Promise<T>.all} for {CancellationToken}s.
   */
  static all(...tokens) {
    if (tokens.some((token) => !token.canBeCancelled)) {
      return _CancellationToken.CONTINUE;
    }
    const combined = _CancellationToken.create();
    let countdown = tokens.length;
    const handleNextTokenCancelled = () => {
      if (--countdown === 0) {
        const reasons = tokens.map((token) => token._reason);
        combined.cancel(reasons);
      }
    };
    tokens.forEach((token) => token.onCancelled(handleNextTokenCancelled));
    return combined.token;
  }
  /**
   * Create a {CancellationToken} that is cancelled when at least one of the given tokens is cancelled.
   *
   * This is like {Promise<T>.race} for {CancellationToken}s.
   */
  static race(...tokens) {
    for (const token of tokens) {
      if (token._isCancelled) {
        return token;
      }
    }
    const combined = _CancellationToken.create();
    let unregistrations;
    const handleAnyTokenCancelled = (reason) => {
      unregistrations.forEach((unregister) => unregister());
      combined.cancel(reason);
    };
    unregistrations = tokens.map((token) => token.onCancelled(handleAnyTokenCancelled));
    return combined.token;
  }
};
CancellationToken.CANCELLED = new CancellationToken(true, true);
CancellationToken.CONTINUE = new CancellationToken(false, false);
(function(CancellationToken2) {
  class CancellationError extends Error {
    constructor(reason) {
      super("Operation cancelled");
      this.reason = reason;
      Object.setPrototypeOf(this, CancellationError.prototype);
    }
  }
  CancellationToken2.CancellationError = CancellationError;
})(CancellationToken || (CancellationToken = {}));

// ../taler-util/lib/amounts.js
var amountFractionalBase = 1e8;
var amountFractionalLength = 8;
var amountMaxValue = 2 ** 52;
var FRAC_SEPARATOR = ".";
var Amount = class _Amount {
  static from(a4) {
    return new _Amount(Amounts.parseOrThrow(a4), 0);
  }
  static zeroOfCurrency(currency) {
    return new _Amount(Amounts.zeroOfCurrency(currency), 0);
  }
  add(...a4) {
    if (this.saturated) {
      return this;
    }
    const r4 = Amounts.add(this.val, ...a4);
    return new _Amount(r4.amount, r4.saturated ? 1 : 0);
  }
  mult(n3) {
    if (this.saturated) {
      return this;
    }
    const r4 = Amounts.mult(this, n3);
    return new _Amount(r4.amount, r4.saturated ? 1 : 0);
  }
  toJson() {
    return { ...this.val };
  }
  toString() {
    return Amounts.stringify(this.val);
  }
  constructor(val, saturated) {
    this.val = val;
    this.saturated = saturated;
  }
};
function codecForAmountString() {
  return {
    decode(x3, c4) {
      if (typeof x3 !== "string") {
        throw new DecodingError(`expected string at ${renderContext(c4)} but got ${typeof x3}`);
      }
      if (Amounts.parse(x3) === void 0) {
        throw new DecodingError(`invalid amount at ${renderContext(c4)} got "${x3}"`);
      }
      return x3;
    }
  };
}
var Amounts = class _Amounts {
  constructor() {
    throw Error("not instantiable");
  }
  static currencyOf(amount) {
    const amt = _Amounts.parseOrThrow(amount);
    return amt.currency;
  }
  static zeroOfAmount(amount) {
    const amt = _Amounts.parseOrThrow(amount);
    return {
      currency: amt.currency,
      fraction: 0,
      value: 0
    };
  }
  /**
   * Get an amount that represents zero units of a currency.
   */
  static zeroOfCurrency(currency) {
    return {
      currency,
      fraction: 0,
      value: 0
    };
  }
  static jsonifyAmount(amt) {
    if (typeof amt === "string") {
      return _Amounts.parseOrThrow(amt);
    }
    if (amt instanceof Amount) {
      return amt.toJson();
    }
    return amt;
  }
  static divmod(a1, a22) {
    const am1 = _Amounts.jsonifyAmount(a1);
    const am2 = _Amounts.jsonifyAmount(a22);
    if (am1.currency != am2.currency) {
      throw Error(`incompatible currency (${am1.currency} vs${am2.currency})`);
    }
    const x1 = BigInt(am1.value) * BigInt(amountFractionalBase) + BigInt(am1.fraction);
    const x22 = BigInt(am2.value) * BigInt(amountFractionalBase) + BigInt(am2.fraction);
    const quotient = x1 / x22;
    const remainderScaled = x1 % x22;
    return {
      quotient: Number(quotient),
      remainder: {
        currency: am1.currency,
        value: Number(remainderScaled / BigInt(amountFractionalBase)),
        fraction: Number(remainderScaled % BigInt(amountFractionalBase))
      }
    };
  }
  static sum(amounts) {
    if (amounts.length <= 0) {
      throw Error("can't sum zero amounts");
    }
    const jsonAmounts = amounts.map((x3) => _Amounts.jsonifyAmount(x3));
    return _Amounts.add(jsonAmounts[0], ...jsonAmounts.slice(1));
  }
  static sumOrZero(currency, amounts) {
    if (amounts.length <= 0) {
      return {
        amount: _Amounts.zeroOfCurrency(currency),
        saturated: false
      };
    }
    const jsonAmounts = amounts.map((x3) => _Amounts.jsonifyAmount(x3));
    return _Amounts.add(jsonAmounts[0], ...jsonAmounts.slice(1));
  }
  /**
   * Add two amounts.  Return the result and whether
   * the addition overflowed.  The overflow is always handled
   * by saturating and never by wrapping.
   *
   * Throws when currencies don't match.
   */
  static add(first, ...rest) {
    const firstJ = _Amounts.jsonifyAmount(first);
    const currency = firstJ.currency;
    let value = firstJ.value + Math.floor(firstJ.fraction / amountFractionalBase);
    if (value > amountMaxValue) {
      return {
        amount: {
          currency,
          value: amountMaxValue,
          fraction: amountFractionalBase - 1
        },
        saturated: true
      };
    }
    let fraction = firstJ.fraction % amountFractionalBase;
    for (const x3 of rest) {
      const xJ = _Amounts.jsonifyAmount(x3);
      if (xJ.currency.toUpperCase() !== currency.toUpperCase()) {
        throw Error(`Mismatched currency: ${xJ.currency} and ${currency}`);
      }
      value = value + xJ.value + Math.floor((fraction + xJ.fraction) / amountFractionalBase);
      fraction = Math.floor((fraction + xJ.fraction) % amountFractionalBase);
      if (value > amountMaxValue) {
        return {
          amount: {
            currency,
            value: amountMaxValue,
            fraction: amountFractionalBase - 1
          },
          saturated: true
        };
      }
    }
    return { amount: { currency, value, fraction }, saturated: false };
  }
  /**
   * Subtract two amounts.  Return the result and whether
   * the subtraction overflowed.  The overflow is always handled
   * by saturating and never by wrapping.
   *
   * Throws when currencies don't match.
   */
  static sub(a4, ...rest) {
    const aJ = _Amounts.jsonifyAmount(a4);
    const currency = aJ.currency;
    let value = aJ.value;
    let fraction = aJ.fraction;
    for (const b4 of rest) {
      const bJ = _Amounts.jsonifyAmount(b4);
      if (bJ.currency.toUpperCase() !== aJ.currency.toUpperCase()) {
        throw Error(`Mismatched currency: ${bJ.currency} and ${currency}`);
      }
      if (fraction < bJ.fraction) {
        if (value < 1) {
          return {
            amount: { currency, value: 0, fraction: 0 },
            saturated: true
          };
        }
        value--;
        fraction += amountFractionalBase;
      }
      console.assert(fraction >= bJ.fraction);
      fraction -= bJ.fraction;
      if (value < bJ.value) {
        return { amount: { currency, value: 0, fraction: 0 }, saturated: true };
      }
      value -= bJ.value;
    }
    return { amount: { currency, value, fraction }, saturated: false };
  }
  /**
   * Compare two amounts.  Returns 0 when equal, -1 when a < b
   * and +1 when a > b.  Throws when currencies don't match.
   */
  static cmp(a4, b4) {
    a4 = _Amounts.jsonifyAmount(a4);
    b4 = _Amounts.jsonifyAmount(b4);
    if (a4.currency !== b4.currency) {
      throw Error(`Mismatched currency: ${a4.currency} and ${b4.currency}`);
    }
    const av = a4.value + Math.floor(a4.fraction / amountFractionalBase);
    const af = a4.fraction % amountFractionalBase;
    const bv = b4.value + Math.floor(b4.fraction / amountFractionalBase);
    const bf = b4.fraction % amountFractionalBase;
    switch (true) {
      case av < bv:
        return -1;
      case av > bv:
        return 1;
      case af < bf:
        return -1;
      case af > bf:
        return 1;
      case af === bf:
        return 0;
      default:
        throw Error("assertion failed");
    }
  }
  /**
   * Create a copy of an amount.
   */
  static copy(a4) {
    return {
      currency: a4.currency,
      fraction: a4.fraction,
      value: a4.value
    };
  }
  /**
   * Divide an amount.  Throws on division by zero.
   */
  static divide(a4, n3) {
    if (n3 === 0) {
      throw Error(`Division by 0`);
    }
    if (n3 === 1) {
      return { value: a4.value, fraction: a4.fraction, currency: a4.currency };
    }
    const r4 = a4.value % n3;
    return {
      currency: a4.currency,
      fraction: Math.floor((r4 * amountFractionalBase + a4.fraction) / n3),
      value: Math.floor(a4.value / n3)
    };
  }
  /**
   * Check if an amount is non-zero.
   */
  static isNonZero(a4) {
    a4 = _Amounts.jsonifyAmount(a4);
    return a4.value > 0 || a4.fraction > 0;
  }
  static isZero(a4) {
    a4 = _Amounts.jsonifyAmount(a4);
    return a4.value === 0 && a4.fraction === 0;
  }
  /**
   * Check whether a string is a valid currency for a Taler amount.
   */
  static isCurrency(s4) {
    return /^[a-zA-Z]{1,11}$/.test(s4);
  }
  /**
   * Parse an amount like 'EUR:20.5' for 20 Euros and 50 ct.
   *
   * Currency name size limit is 11 of ASCII letters
   * Fraction size limit is 8
   */
  static parse(s4) {
    const res = s4.match(/^([a-zA-Z]{1,11}):([0-9]+)([.][0-9]{1,8})?$/);
    if (!res) {
      return void 0;
    }
    const tail = res[3] || FRAC_SEPARATOR + "0";
    if (tail.length > amountFractionalLength + 1) {
      return void 0;
    }
    const value = Number.parseInt(res[2]);
    if (value > amountMaxValue) {
      return void 0;
    }
    return {
      currency: res[1].toUpperCase(),
      fraction: Math.round(amountFractionalBase * Number.parseFloat(tail)),
      value
    };
  }
  /**
   * Parse amount in standard string form (like 'EUR:20.5'),
   * throw if the input is not a valid amount.
   */
  static parseOrThrow(s4) {
    if (s4 instanceof Amount) {
      return s4.toJson();
    }
    if (typeof s4 === "object") {
      if (typeof s4.currency !== "string") {
        throw Error("invalid amount object");
      }
      if (typeof s4.value !== "number") {
        throw Error("invalid amount object");
      }
      if (typeof s4.fraction !== "number") {
        throw Error("invalid amount object");
      }
      return { currency: s4.currency, value: s4.value, fraction: s4.fraction };
    } else if (typeof s4 === "string") {
      const res = _Amounts.parse(s4);
      if (!res) {
        throw Error(`Can't parse amount: "${s4}"`);
      }
      return res;
    } else {
      throw Error("invalid amount (illegal type)");
    }
  }
  static min(a4, b4) {
    const cr = _Amounts.cmp(a4, b4);
    if (cr >= 0) {
      return _Amounts.jsonifyAmount(b4);
    } else {
      return _Amounts.jsonifyAmount(a4);
    }
  }
  static max(a4, b4) {
    const cr = _Amounts.cmp(a4, b4);
    if (cr >= 0) {
      return _Amounts.jsonifyAmount(a4);
    } else {
      return _Amounts.jsonifyAmount(b4);
    }
  }
  static mult(a4, n3) {
    a4 = this.jsonifyAmount(a4);
    if (!Number.isInteger(n3)) {
      throw Error("amount can only be multiplied by an integer");
    }
    if (n3 < 0) {
      throw Error("amount can only be multiplied by a positive integer");
    }
    if (n3 == 0) {
      return {
        amount: _Amounts.zeroOfCurrency(a4.currency),
        saturated: false
      };
    }
    let x3 = a4;
    let acc = _Amounts.zeroOfCurrency(a4.currency);
    while (n3 > 1) {
      if (n3 % 2 == 0) {
        n3 = n3 / 2;
      } else {
        n3 = (n3 - 1) / 2;
        const r23 = _Amounts.add(acc, x3);
        if (r23.saturated) {
          return r23;
        }
        acc = r23.amount;
      }
      const r22 = _Amounts.add(x3, x3);
      if (r22.saturated) {
        return r22;
      }
      x3 = r22.amount;
    }
    return _Amounts.add(acc, x3);
  }
  /**
   * Check if the argument is a valid amount in string form.
   */
  static check(a4) {
    if (typeof a4 !== "string") {
      return false;
    }
    try {
      const parsedAmount = _Amounts.parse(a4);
      return !!parsedAmount;
    } catch {
      return false;
    }
  }
  /**
   * Convert to standard human-readable string representation that's
   * also used in JSON formats.
   */
  static stringify(a4) {
    a4 = _Amounts.jsonifyAmount(a4);
    const s4 = this.stringifyValue(a4);
    return `${a4.currency}:${s4}`;
  }
  static amountHasSameCurrency(a1, a22) {
    const x1 = this.jsonifyAmount(a1);
    const x22 = this.jsonifyAmount(a22);
    return x1.currency.toUpperCase() === x22.currency.toUpperCase();
  }
  static isSameCurrency(curr1, curr2) {
    return curr1.toLowerCase() === curr2.toLowerCase();
  }
  static stringifyValue(a4, minFractional = 0) {
    const aJ = _Amounts.jsonifyAmount(a4);
    const av = aJ.value + Math.floor(aJ.fraction / amountFractionalBase);
    const af = aJ.fraction % amountFractionalBase;
    let s4 = av.toString();
    if (af || minFractional) {
      s4 = s4 + FRAC_SEPARATOR;
      let n3 = af;
      for (let i4 = 0; i4 < amountFractionalLength; i4++) {
        if (!n3 && i4 >= minFractional) {
          break;
        }
        s4 = s4 + Math.floor(n3 / amountFractionalBase * 10).toString();
        n3 = n3 * 10 % amountFractionalBase;
      }
    }
    return s4;
  }
  /**
   * Number of fractional digits needed to fully represent the amount
   * @param a amount
   * @returns
   */
  static maxFractionalDigits(a4) {
    if (a4.fraction === 0)
      return 0;
    if (a4.fraction < 0) {
      console.error("amount fraction can not be negative", a4);
      return 0;
    }
    let i4 = 0;
    let check = true;
    let rest = a4.fraction;
    while (rest > 0 && check) {
      check = rest % 10 === 0;
      rest = rest / 10;
      i4++;
    }
    return amountFractionalLength - i4 + 1;
  }
  static stringifyValueWithSpec(value, spec) {
    const strValue = _Amounts.stringifyValue(value);
    const pos = strValue.indexOf(FRAC_SEPARATOR);
    const originalPosition = pos < 0 ? strValue.length : pos;
    let currency = value.currency;
    const names = Object.keys(spec.alt_unit_names);
    let FRAC_POS_NEW_POSITION = originalPosition;
    if (names.length > 0) {
      let unitIndex = "0";
      names.forEach((index) => {
        const i4 = Number.parseInt(index, 10);
        if (Number.isNaN(i4))
          return;
        if (originalPosition - i4 <= 0)
          return;
        if (originalPosition - i4 < FRAC_POS_NEW_POSITION) {
          FRAC_POS_NEW_POSITION = originalPosition - i4;
          unitIndex = index;
        }
      });
      currency = spec.alt_unit_names[unitIndex];
    }
    if (originalPosition === FRAC_POS_NEW_POSITION) {
      const { normal: normal2, small: small2 } = splitNormalAndSmall(strValue, originalPosition, spec);
      return { currency, normal: normal2, small: small2 };
    }
    const intPart = strValue.substring(0, originalPosition);
    const fracPArt = strValue.substring(originalPosition + 1);
    const newValue = intPart.substring(0, FRAC_POS_NEW_POSITION) + FRAC_SEPARATOR + intPart.substring(FRAC_POS_NEW_POSITION) + fracPArt;
    const { normal, small } = splitNormalAndSmall(newValue, FRAC_POS_NEW_POSITION, spec);
    return { currency, normal, small };
  }
};
function splitNormalAndSmall(decimal, fracSeparatorIndex, spec) {
  let normal;
  let small;
  if (decimal.length - fracSeparatorIndex - 1 > spec.num_fractional_normal_digits) {
    const limit = fracSeparatorIndex + spec.num_fractional_normal_digits + 1;
    normal = decimal.substring(0, limit);
    small = decimal.substring(limit);
  } else {
    normal = decimal;
    small = void 0;
  }
  return { normal, small };
}

// ../taler-util/lib/punycode.js
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 errors = {
  overflow: "Overflow: input needs wider integers to process",
  "not-basic": "Illegal input >= 0x80 (not a basic code point)",
  "invalid-input": "Invalid input"
};
var baseMinusTMin = base - tMin;
var floor = Math.floor;
var stringFromCharCode = String.fromCharCode;
function error(type) {
  throw new RangeError(errors[type]);
}
function map(array, fn) {
  const result = [];
  let length = array.length;
  while (length--) {
    result[length] = fn(array[length]);
  }
  return result;
}
function mapDomain(string, fn) {
  const parts = string.split("@");
  let result = "";
  if (parts.length > 1) {
    result = parts[0] + "@";
    string = parts[1];
  }
  string = string.replace(regexSeparators, ".");
  const labels = string.split(".");
  const encoded = map(labels, fn).join(".");
  return result + encoded;
}
function ucs2decode(string) {
  const output = [];
  let counter = 0;
  const length = string.length;
  while (counter < length) {
    const value = string.charCodeAt(counter++);
    if (value >= 55296 && value <= 56319 && counter < length) {
      const extra = string.charCodeAt(counter++);
      if ((extra & 64512) == 56320) {
        output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
      } else {
        output.push(value);
        counter--;
      }
    } else {
      output.push(value);
    }
  }
  return output;
}
var ucs2encode = (array) => String.fromCodePoint(...array);
var basicToDigit = function(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(digit2, flag) {
  return digit2 + 22 + 75 * Number(digit2 < 26) - (Number(flag != 0) << 5);
};
var adapt = function(delta, numPoints, firstTime) {
  let k4 = 0;
  delta = firstTime ? floor(delta / damp) : delta >> 1;
  delta += floor(delta / numPoints);
  for (
    ;
    /* no initialization */
    delta > baseMinusTMin * tMax >> 1;
    k4 += base
  ) {
    delta = floor(delta / baseMinusTMin);
  }
  return floor(k4 + (baseMinusTMin + 1) * delta / (delta + skew));
};
var decode = function(input) {
  const output = [];
  const inputLength = input.length;
  let i4 = 0;
  let n3 = initialN;
  let bias = initialBias;
  let basic = input.lastIndexOf(delimiter);
  if (basic < 0) {
    basic = 0;
  }
  for (let j4 = 0; j4 < basic; ++j4) {
    if (input.charCodeAt(j4) >= 128) {
      error("not-basic");
    }
    output.push(input.charCodeAt(j4));
  }
  for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; ) {
    let oldi = i4;
    for (let w4 = 1, k4 = base; ; k4 += base) {
      if (index >= inputLength) {
        error("invalid-input");
      }
      const digit2 = basicToDigit(input.charCodeAt(index++));
      if (digit2 >= base || digit2 > floor((maxInt - i4) / w4)) {
        error("overflow");
      }
      i4 += digit2 * w4;
      const t4 = k4 <= bias ? tMin : k4 >= bias + tMax ? tMax : k4 - bias;
      if (digit2 < t4) {
        break;
      }
      const baseMinusT = base - t4;
      if (w4 > floor(maxInt / baseMinusT)) {
        error("overflow");
      }
      w4 *= baseMinusT;
    }
    const out = output.length + 1;
    bias = adapt(i4 - oldi, out, oldi == 0);
    if (floor(i4 / out) > maxInt - n3) {
      error("overflow");
    }
    n3 += floor(i4 / out);
    i4 %= out;
    output.splice(i4++, 0, n3);
  }
  return String.fromCodePoint(...output);
};
var encode = function(inputArg) {
  const output = [];
  let input = ucs2decode(inputArg);
  let inputLength = input.length;
  let n3 = initialN;
  let delta = 0;
  let bias = initialBias;
  for (const currentValue of input) {
    if (currentValue < 128) {
      output.push(stringFromCharCode(currentValue));
    }
  }
  let basicLength = output.length;
  let handledCPCount = basicLength;
  if (basicLength) {
    output.push(delimiter);
  }
  while (handledCPCount < inputLength) {
    let m4 = maxInt;
    for (const currentValue of input) {
      if (currentValue >= n3 && currentValue < m4) {
        m4 = currentValue;
      }
    }
    const handledCPCountPlusOne = handledCPCount + 1;
    if (m4 - n3 > floor((maxInt - delta) / handledCPCountPlusOne)) {
      error("overflow");
    }
    delta += (m4 - n3) * handledCPCountPlusOne;
    n3 = m4;
    for (const currentValue of input) {
      if (currentValue < n3 && ++delta > maxInt) {
        error("overflow");
      }
      if (currentValue == n3) {
        let q4 = delta;
        for (let k4 = base; ; k4 += base) {
          const t4 = k4 <= bias ? tMin : k4 >= bias + tMax ? tMax : k4 - bias;
          if (q4 < t4) {
            break;
          }
          const qMinusT = q4 - t4;
          const baseMinusT = base - t4;
          output.push(stringFromCharCode(digitToBasic(t4 + qMinusT % baseMinusT, 0)));
          q4 = floor(qMinusT / baseMinusT);
        }
        output.push(stringFromCharCode(digitToBasic(q4, 0)));
        bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
        delta = 0;
        ++handledCPCount;
      }
    }
    ++delta;
    ++n3;
  }
  return output.join("");
};
var toUnicode = function(input) {
  return mapDomain(input, function(string) {
    return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
  });
};
var toASCII = function(input) {
  return mapDomain(input, function(string) {
    return regexNonASCII.test(string) ? "xn--" + encode(string) : string;
  });
};
var punycode = {
  /**
   * A string representing the current Punycode.js version number.
   * @memberOf punycode
   * @type String
   */
  version: "2.1.0",
  /**
   * An object of methods to convert from JavaScript's internal character
   * representation (UCS-2) to Unicode code points, and back.
   * @see <https://mathiasbynens.be/notes/javascript-encoding>
   * @memberOf punycode
   * @type Object
   */
  ucs2: {
    decode: ucs2decode,
    encode: ucs2encode
  },
  decode,
  encode,
  toASCII,
  toUnicode
};

// ../taler-util/lib/whatwg-url.js
var utf8Encoder = new TextEncoder();
var utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
function utf8Encode(string) {
  return utf8Encoder.encode(string);
}
function utf8DecodeWithoutBOM(bytes) {
  return utf8Decoder.decode(bytes);
}
function parseUrlencoded(input) {
  const sequences = strictlySplitByteSequence(input, p2("&"));
  const output = [];
  for (const bytes of sequences) {
    if (bytes.length === 0) {
      continue;
    }
    let name, value;
    const indexOfEqual = bytes.indexOf(p2("="));
    if (indexOfEqual >= 0) {
      name = bytes.slice(0, indexOfEqual);
      value = bytes.slice(indexOfEqual + 1);
    } else {
      name = bytes;
      value = new Uint8Array(0);
    }
    name = replaceByteInByteSequence(name, 43, 32);
    value = replaceByteInByteSequence(value, 43, 32);
    const nameString = utf8DecodeWithoutBOM(percentDecodeBytes(name));
    const valueString = utf8DecodeWithoutBOM(percentDecodeBytes(value));
    output.push([nameString, valueString]);
  }
  return output;
}
function parseUrlencodedString(input) {
  return parseUrlencoded(utf8Encode(input));
}
function serializeUrlencoded(tuples, encodingOverride = void 0) {
  let encoding = "utf-8";
  if (encodingOverride !== void 0) {
    encoding = encodingOverride;
  }
  let output = "";
  for (const [i4, tuple] of tuples.entries()) {
    const name = utf8PercentEncodeString(tuple[0], isURLEncodedPercentEncode, true);
    let value = tuple[1];
    if (tuple.length > 2 && tuple[2] !== void 0) {
      if (tuple[2] === "hidden" && name === "_charset_") {
        value = encoding;
      } else if (tuple[2] === "file") {
        value = value.name;
      }
    }
    value = utf8PercentEncodeString(value, isURLEncodedPercentEncode, true);
    if (i4 !== 0) {
      output += "&";
    }
    output += `${name}=${value}`;
  }
  return output;
}
function strictlySplitByteSequence(buf, cp) {
  const list = [];
  let last = 0;
  let i4 = buf.indexOf(cp);
  while (i4 >= 0) {
    list.push(buf.slice(last, i4));
    last = i4 + 1;
    i4 = buf.indexOf(cp, last);
  }
  if (last !== buf.length) {
    list.push(buf.slice(last));
  }
  return list;
}
function replaceByteInByteSequence(buf, from, to) {
  let i4 = buf.indexOf(from);
  while (i4 >= 0) {
    buf[i4] = to;
    i4 = buf.indexOf(from, i4 + 1);
  }
  return buf;
}
function p2(char) {
  return char.codePointAt(0);
}
function percentEncode(c4) {
  let hex = c4.toString(16).toUpperCase();
  if (hex.length === 1) {
    hex = `0${hex}`;
  }
  return `%${hex}`;
}
function percentDecodeBytes(input) {
  const output = new Uint8Array(input.byteLength);
  let outputIndex = 0;
  for (let i4 = 0; i4 < input.byteLength; ++i4) {
    const byte = input[i4];
    if (byte !== 37) {
      output[outputIndex++] = byte;
    } else if (byte === 37 && (!isASCIIHex(input[i4 + 1]) || !isASCIIHex(input[i4 + 2]))) {
      output[outputIndex++] = byte;
    } else {
      const bytePoint = parseInt(String.fromCodePoint(input[i4 + 1], input[i4 + 2]), 16);
      output[outputIndex++] = bytePoint;
      i4 += 2;
    }
  }
  return output.slice(0, outputIndex);
}
function percentDecodeString(input) {
  const bytes = utf8Encode(input);
  return percentDecodeBytes(bytes);
}
function isC0ControlPercentEncode(c4) {
  return c4 <= 31 || c4 > 126;
}
var extraFragmentPercentEncodeSet = /* @__PURE__ */ new Set([
  p2(" "),
  p2('"'),
  p2("<"),
  p2(">"),
  p2("`")
]);
function isFragmentPercentEncode(c4) {
  return isC0ControlPercentEncode(c4) || extraFragmentPercentEncodeSet.has(c4);
}
var extraQueryPercentEncodeSet = /* @__PURE__ */ new Set([
  p2(" "),
  p2('"'),
  p2("#"),
  p2("<"),
  p2(">")
]);
function isQueryPercentEncode(c4) {
  return isC0ControlPercentEncode(c4) || extraQueryPercentEncodeSet.has(c4);
}
function isSpecialQueryPercentEncode(c4) {
  return isQueryPercentEncode(c4) || c4 === p2("'");
}
var extraPathPercentEncodeSet = /* @__PURE__ */ new Set([p2("?"), p2("`"), p2("{"), p2("}")]);
function isPathPercentEncode(c4) {
  return isQueryPercentEncode(c4) || extraPathPercentEncodeSet.has(c4);
}
var extraUserinfoPercentEncodeSet = /* @__PURE__ */ new Set([
  p2("/"),
  p2(":"),
  p2(";"),
  p2("="),
  p2("@"),
  p2("["),
  p2("\\"),
  p2("]"),
  p2("^"),
  p2("|")
]);
function isUserinfoPercentEncode(c4) {
  return isPathPercentEncode(c4) || extraUserinfoPercentEncodeSet.has(c4);
}
var extraComponentPercentEncodeSet = /* @__PURE__ */ new Set([
  p2("$"),
  p2("%"),
  p2("&"),
  p2("+"),
  p2(",")
]);
function isComponentPercentEncode(c4) {
  return isUserinfoPercentEncode(c4) || extraComponentPercentEncodeSet.has(c4);
}
var extraURLEncodedPercentEncodeSet = /* @__PURE__ */ new Set([
  p2("!"),
  p2("'"),
  p2("("),
  p2(")"),
  p2("~")
]);
function isURLEncodedPercentEncode(c4) {
  return isComponentPercentEncode(c4) || extraURLEncodedPercentEncodeSet.has(c4);
}
function utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate) {
  const bytes = utf8Encode(codePoint);
  let output = "";
  for (const byte of bytes) {
    if (!percentEncodePredicate(byte)) {
      output += String.fromCharCode(byte);
    } else {
      output += percentEncode(byte);
    }
  }
  return output;
}
function utf8PercentEncodeCodePoint(codePoint, percentEncodePredicate) {
  return utf8PercentEncodeCodePointInternal(String.fromCodePoint(codePoint), percentEncodePredicate);
}
function utf8PercentEncodeString(input, percentEncodePredicate, spaceAsPlus = false) {
  let output = "";
  for (const codePoint of input) {
    if (spaceAsPlus && codePoint === " ") {
      output += "+";
    } else {
      output += utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate);
    }
  }
  return output;
}
function isASCIIDigit(c4) {
  return c4 >= 48 && c4 <= 57;
}
function isASCIIAlpha(c4) {
  return c4 >= 65 && c4 <= 90 || c4 >= 97 && c4 <= 122;
}
function isASCIIAlphanumeric(c4) {
  return isASCIIAlpha(c4) || isASCIIDigit(c4);
}
function isASCIIHex(c4) {
  return isASCIIDigit(c4) || c4 >= 65 && c4 <= 70 || c4 >= 97 && c4 <= 102;
}
var URLSearchParamsImpl = class {
  constructor(init, { doNotStripQMark = false } = {}) {
    this._list = [];
    this._url = null;
    if (!doNotStripQMark && typeof init === "string" && init[0] === "?") {
      init = init.slice(1);
    }
    if (Array.isArray(init)) {
      for (const pair of init) {
        if (pair.length !== 2) {
          throw new TypeError("Failed to construct 'URLSearchParams': parameter 1 sequence's element does not contain exactly two elements.");
        }
        this._list.push([pair[0], pair[1]]);
      }
    } else if (typeof init === "object" && Object.getPrototypeOf(init) === null) {
      for (const name of Object.keys(init)) {
        const value = init[name];
        this._list.push([name, value]);
      }
    } else {
      this._list = parseUrlencodedString(init);
    }
  }
  _updateSteps() {
    if (this._url !== null) {
      let query = serializeUrlencoded(this._list);
      if (query === "") {
        query = null;
      }
      this._url._url.query = query;
    }
  }
  append(name, value) {
    this._list.push([name, value]);
    this._updateSteps();
  }
  delete(name) {
    let i4 = 0;
    while (i4 < this._list.length) {
      if (this._list[i4][0] === name) {
        this._list.splice(i4, 1);
      } else {
        i4++;
      }
    }
    this._updateSteps();
  }
  get(name) {
    for (const tuple of this._list) {
      if (tuple[0] === name) {
        return tuple[1];
      }
    }
    return null;
  }
  getAll(name) {
    const output = [];
    for (const tuple of this._list) {
      if (tuple[0] === name) {
        output.push(tuple[1]);
      }
    }
    return output;
  }
  forEach(callbackfn, thisArg) {
    for (const tuple of this._list) {
      callbackfn.call(thisArg, tuple[1], tuple[0], this);
    }
  }
  has(name) {
    for (const tuple of this._list) {
      if (tuple[0] === name) {
        return true;
      }
    }
    return false;
  }
  set(name, value) {
    let found = false;
    let i4 = 0;
    while (i4 < this._list.length) {
      if (this._list[i4][0] === name) {
        if (found) {
          this._list.splice(i4, 1);
        } else {
          found = true;
          this._list[i4][1] = value;
          i4++;
        }
      } else {
        i4++;
      }
    }
    if (!found) {
      this._list.push([name, value]);
    }
    this._updateSteps();
  }
  sort() {
    this._list.sort((a4, b4) => {
      if (a4[0] < b4[0]) {
        return -1;
      }
      if (a4[0] > b4[0]) {
        return 1;
      }
      return 0;
    });
    this._updateSteps();
  }
  [Symbol.iterator]() {
    return this._list[Symbol.iterator]();
  }
  toString() {
    return serializeUrlencoded(this._list);
  }
};
var specialSchemes = {
  ftp: 21,
  file: null,
  http: 80,
  https: 443,
  ws: 80,
  wss: 443
};
var failure = Symbol("failure");
function countSymbols(str) {
  return [...str].length;
}
function at(input, idx) {
  const c4 = input[idx];
  return isNaN(c4) ? void 0 : String.fromCodePoint(c4);
}
function isSingleDot(buffer) {
  return buffer === "." || buffer.toLowerCase() === "%2e";
}
function isDoubleDot(buffer) {
  buffer = buffer.toLowerCase();
  return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e";
}
function isWindowsDriveLetterCodePoints(cp1, cp2) {
  return isASCIIAlpha(cp1) && (cp2 === p2(":") || cp2 === p2("|"));
}
function isWindowsDriveLetterString(string) {
  return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|");
}
function isNormalizedWindowsDriveLetterString(string) {
  return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":";
}
function containsForbiddenHostCodePoint(string) {
  return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u) !== -1;
}
function containsForbiddenDomainCodePoint(string) {
  return containsForbiddenHostCodePoint(string) || string.search(/[\u0000-\u001F]|%|\u007F/u) !== -1;
}
function isSpecialScheme(scheme) {
  return specialSchemes[scheme] !== void 0;
}
function isSpecial(url) {
  return isSpecialScheme(url.scheme);
}
function isNotSpecial(url) {
  return !isSpecialScheme(url.scheme);
}
function defaultPort(scheme) {
  return specialSchemes[scheme];
}
function parseIPv4Number(input) {
  if (input === "") {
    return failure;
  }
  let R2 = 10;
  if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") {
    input = input.substring(2);
    R2 = 16;
  } else if (input.length >= 2 && input.charAt(0) === "0") {
    input = input.substring(1);
    R2 = 8;
  }
  if (input === "") {
    return 0;
  }
  let regex = /[^0-7]/u;
  if (R2 === 10) {
    regex = /[^0-9]/u;
  }
  if (R2 === 16) {
    regex = /[^0-9A-Fa-f]/u;
  }
  if (regex.test(input)) {
    return failure;
  }
  return parseInt(input, R2);
}
function parseIPv4(input) {
  const parts = input.split(".");
  if (parts[parts.length - 1] === "") {
    if (parts.length > 1) {
      parts.pop();
    }
  }
  if (parts.length > 4) {
    return failure;
  }
  const numbers = [];
  for (const part of parts) {
    const n3 = parseIPv4Number(part);
    if (n3 === failure) {
      return failure;
    }
    numbers.push(n3);
  }
  for (let i4 = 0; i4 < numbers.length - 1; ++i4) {
    if (numbers[i4] > 255) {
      return failure;
    }
  }
  if (numbers[numbers.length - 1] >= 256 ** (5 - numbers.length)) {
    return failure;
  }
  let ipv4 = numbers.pop();
  let counter = 0;
  for (const n3 of numbers) {
    ipv4 += n3 * 256 ** (3 - counter);
    ++counter;
  }
  return ipv4;
}
function serializeIPv4(address) {
  let output = "";
  let n3 = address;
  for (let i4 = 1; i4 <= 4; ++i4) {
    output = String(n3 % 256) + output;
    if (i4 !== 4) {
      output = `.${output}`;
    }
    n3 = Math.floor(n3 / 256);
  }
  return output;
}
function parseIPv6(inputArg) {
  const address = [0, 0, 0, 0, 0, 0, 0, 0];
  let pieceIndex = 0;
  let compress = null;
  let pointer = 0;
  const input = Array.from(inputArg, (c4) => c4.codePointAt(0));
  if (input[pointer] === p2(":")) {
    if (input[pointer + 1] !== p2(":")) {
      return failure;
    }
    pointer += 2;
    ++pieceIndex;
    compress = pieceIndex;
  }
  while (pointer < input.length) {
    if (pieceIndex === 8) {
      return failure;
    }
    if (input[pointer] === p2(":")) {
      if (compress !== null) {
        return failure;
      }
      ++pointer;
      ++pieceIndex;
      compress = pieceIndex;
      continue;
    }
    let value = 0;
    let length = 0;
    while (length < 4 && isASCIIHex(input[pointer])) {
      value = value * 16 + parseInt(at(input, pointer), 16);
      ++pointer;
      ++length;
    }
    if (input[pointer] === p2(".")) {
      if (length === 0) {
        return failure;
      }
      pointer -= length;
      if (pieceIndex > 6) {
        return failure;
      }
      let numbersSeen = 0;
      while (input[pointer] !== void 0) {
        let ipv4Piece = null;
        if (numbersSeen > 0) {
          if (input[pointer] === p2(".") && numbersSeen < 4) {
            ++pointer;
          } else {
            return failure;
          }
        }
        if (!isASCIIDigit(input[pointer])) {
          return failure;
        }
        while (isASCIIDigit(input[pointer])) {
          const number = parseInt(at(input, pointer));
          if (ipv4Piece === null) {
            ipv4Piece = number;
          } else if (ipv4Piece === 0) {
            return failure;
          } else {
            ipv4Piece = ipv4Piece * 10 + number;
          }
          if (ipv4Piece > 255) {
            return failure;
          }
          ++pointer;
        }
        address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece;
        ++numbersSeen;
        if (numbersSeen === 2 || numbersSeen === 4) {
          ++pieceIndex;
        }
      }
      if (numbersSeen !== 4) {
        return failure;
      }
      break;
    } else if (input[pointer] === p2(":")) {
      ++pointer;
      if (input[pointer] === void 0) {
        return failure;
      }
    } else if (input[pointer] !== void 0) {
      return failure;
    }
    address[pieceIndex] = value;
    ++pieceIndex;
  }
  if (compress !== null) {
    let swaps = pieceIndex - compress;
    pieceIndex = 7;
    while (pieceIndex !== 0 && swaps > 0) {
      const temp = address[compress + swaps - 1];
      address[compress + swaps - 1] = address[pieceIndex];
      address[pieceIndex] = temp;
      --pieceIndex;
      --swaps;
    }
  } else if (compress === null && pieceIndex !== 8) {
    return failure;
  }
  return address;
}
function serializeIPv6(address) {
  let output = "";
  const compress = findLongestZeroSequence(address);
  let ignore0 = false;
  for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) {
    if (ignore0 && address[pieceIndex] === 0) {
      continue;
    } else if (ignore0) {
      ignore0 = false;
    }
    if (compress === pieceIndex) {
      const separator = pieceIndex === 0 ? "::" : ":";
      output += separator;
      ignore0 = true;
      continue;
    }
    output += address[pieceIndex].toString(16);
    if (pieceIndex !== 7) {
      output += ":";
    }
  }
  return output;
}
function parseHost(input, isNotSpecialArg = false) {
  if (input[0] === "[") {
    if (input[input.length - 1] !== "]") {
      return failure;
    }
    return parseIPv6(input.substring(1, input.length - 1));
  }
  if (isNotSpecialArg) {
    return parseOpaqueHost(input);
  }
  const domain = utf8DecodeWithoutBOM(percentDecodeString(input));
  const asciiDomain = domainToASCII(domain);
  if (asciiDomain === failure) {
    return failure;
  }
  if (containsForbiddenDomainCodePoint(asciiDomain)) {
    return failure;
  }
  if (endsInANumber(asciiDomain)) {
    return parseIPv4(asciiDomain);
  }
  return asciiDomain;
}
function endsInANumber(input) {
  const parts = input.split(".");
  if (parts[parts.length - 1] === "") {
    if (parts.length === 1) {
      return false;
    }
    parts.pop();
  }
  const last = parts[parts.length - 1];
  if (parseIPv4Number(last) !== failure) {
    return true;
  }
  if (/^[0-9]+$/u.test(last)) {
    return true;
  }
  return false;
}
function parseOpaqueHost(input) {
  if (containsForbiddenHostCodePoint(input)) {
    return failure;
  }
  return utf8PercentEncodeString(input, isC0ControlPercentEncode);
}
function findLongestZeroSequence(arr) {
  let maxIdx = null;
  let maxLen = 1;
  let currStart = null;
  let currLen = 0;
  for (let i4 = 0; i4 < arr.length; ++i4) {
    if (arr[i4] !== 0) {
      if (currLen > maxLen) {
        maxIdx = currStart;
        maxLen = currLen;
      }
      currStart = null;
      currLen = 0;
    } else {
      if (currStart === null) {
        currStart = i4;
      }
      ++currLen;
    }
  }
  if (currLen > maxLen) {
    return currStart;
  }
  return maxIdx;
}
function serializeHost(host) {
  if (typeof host === "number") {
    return serializeIPv4(host);
  }
  if (host instanceof Array) {
    return `[${serializeIPv6(host)}]`;
  }
  return host;
}
function domainToASCII(domain, beStrict = false) {
  let result;
  try {
    result = punycode.toASCII(domain);
  } catch (e4) {
    return failure;
  }
  if (result === null || result === "") {
    return failure;
  }
  return result;
}
function trimControlChars(url) {
  return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/gu, "");
}
function trimTabAndNewline(url) {
  return url.replace(/\u0009|\u000A|\u000D/gu, "");
}
function shortenPath(url) {
  const { path } = url;
  if (path.length === 0) {
    return;
  }
  if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) {
    return;
  }
  path.pop();
}
function includesCredentials(url) {
  return url.username !== "" || url.password !== "";
}
function cannotHaveAUsernamePasswordPort(url) {
  return url.host === null || url.host === "" || url.scheme === "file";
}
function hasAnOpaquePath(url) {
  return typeof url.path === "string";
}
function isNormalizedWindowsDriveLetter(string) {
  return /^[A-Za-z]:$/u.test(string);
}
var URLStateMachine = class {
  constructor(input, base3, encodingOverride, url, stateOverride) {
    this.table = {
      "parse scheme start": this.parseSchemeStart,
      "parse scheme": this.parseScheme,
      "parse no scheme": this.parseNoScheme,
      "parse special relative or authority": this.parseSpecialRelativeOrAuthority,
      "parse path or authority": this.parsePathOrAuthority,
      "parse relative": this.parseRelative,
      "parse relative slash": this.parseRelativeSlash,
      "parse special authority slashes": this.parseSpecialAuthoritySlashes,
      "parse special authority ignore slashes": this.parseSpecialAuthorityIgnoreSlashes,
      "parse authority": this.parseAuthority,
      "parse host": this.parseHostName,
      "parse hostname": this.parseHostName,
      "parse port": this.parsePort,
      "parse file": this.parseFile,
      "parse file slash": this.parseFileSlash,
      "parse file host": this.parseFileHost,
      "parse path start": this.parsePathStart,
      "parse path": this.parsePath,
      "parse opaque path": this.parseOpaquePath,
      "parse query": this.parseQuery,
      "parse fragment": this.parseFragment
    };
    this.pointer = 0;
    this.base = base3 || null;
    this.encodingOverride = encodingOverride || "utf-8";
    this.url = url;
    this.failure = false;
    this.parseError = false;
    if (!this.url) {
      this.url = {
        scheme: "",
        username: "",
        password: "",
        host: null,
        port: null,
        path: [],
        query: null,
        fragment: null
      };
      const res2 = trimControlChars(input);
      if (res2 !== input) {
        this.parseError = true;
      }
      input = res2;
    }
    const res = trimTabAndNewline(input);
    if (res !== input) {
      this.parseError = true;
    }
    input = res;
    this.state = stateOverride || "scheme start";
    this.buffer = "";
    this.atFlag = false;
    this.arrFlag = false;
    this.passwordTokenSeenFlag = false;
    this.input = Array.from(input, (c4) => c4.codePointAt(0));
    for (; this.pointer <= this.input.length; ++this.pointer) {
      const c4 = this.input[this.pointer];
      const cStr = isNaN(c4) ? void 0 : String.fromCodePoint(c4);
      const ret = this.table[`parse ${this.state}`].call(this, c4, cStr);
      if (!ret) {
        break;
      } else if (ret === failure) {
        this.failure = true;
        break;
      }
    }
  }
  parseSchemeStart(c4, cStr) {
    if (isASCIIAlpha(c4)) {
      this.buffer += cStr.toLowerCase();
      this.state = "scheme";
    } else if (!this.stateOverride) {
      this.state = "no scheme";
      --this.pointer;
    } else {
      this.parseError = true;
      return failure;
    }
    return true;
  }
  parseScheme(c4, cStr) {
    if (isASCIIAlphanumeric(c4) || c4 === p2("+") || c4 === p2("-") || c4 === p2(".")) {
      this.buffer += cStr.toLowerCase();
    } else if (c4 === p2(":")) {
      if (this.stateOverride) {
        if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) {
          return false;
        }
        if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) {
          return false;
        }
        if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") {
          return false;
        }
        if (this.url.scheme === "file" && this.url.host === "") {
          return false;
        }
      }
      this.url.scheme = this.buffer;
      if (this.stateOverride) {
        if (this.url.port === defaultPort(this.url.scheme)) {
          this.url.port = null;
        }
        return false;
      }
      this.buffer = "";
      if (this.url.scheme === "file") {
        if (this.input[this.pointer + 1] !== p2("/") || this.input[this.pointer + 2] !== p2("/")) {
          this.parseError = true;
        }
        this.state = "file";
      } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) {
        this.state = "special relative or authority";
      } else if (isSpecial(this.url)) {
        this.state = "special authority slashes";
      } else if (this.input[this.pointer + 1] === p2("/")) {
        this.state = "path or authority";
        ++this.pointer;
      } else {
        this.url.path = [""];
        this.state = "opaque path";
      }
    } else if (!this.stateOverride) {
      this.buffer = "";
      this.state = "no scheme";
      this.pointer = -1;
    } else {
      this.parseError = true;
      return failure;
    }
    return true;
  }
  parseNoScheme(c4) {
    if (this.base === null || hasAnOpaquePath(this.base) && c4 !== p2("#")) {
      return failure;
    } else if (hasAnOpaquePath(this.base) && c4 === p2("#")) {
      this.url.scheme = this.base.scheme;
      this.url.path = this.base.path;
      this.url.query = this.base.query;
      this.url.fragment = "";
      this.state = "fragment";
    } else if (this.base.scheme === "file") {
      this.state = "file";
      --this.pointer;
    } else {
      this.state = "relative";
      --this.pointer;
    }
    return true;
  }
  parseSpecialRelativeOrAuthority(c4) {
    if (c4 === p2("/") && this.input[this.pointer + 1] === p2("/")) {
      this.state = "special authority ignore slashes";
      ++this.pointer;
    } else {
      this.parseError = true;
      this.state = "relative";
      --this.pointer;
    }
    return true;
  }
  parsePathOrAuthority(c4) {
    if (c4 === p2("/")) {
      this.state = "authority";
    } else {
      this.state = "path";
      --this.pointer;
    }
    return true;
  }
  parseRelative(c4) {
    this.url.scheme = this.base.scheme;
    if (c4 === p2("/")) {
      this.state = "relative slash";
    } else if (isSpecial(this.url) && c4 === p2("\\")) {
      this.parseError = true;
      this.state = "relative slash";
    } else {
      this.url.username = this.base.username;
      this.url.password = this.base.password;
      this.url.host = this.base.host;
      this.url.port = this.base.port;
      this.url.path = this.base.path.slice();
      this.url.query = this.base.query;
      if (c4 === p2("?")) {
        this.url.query = "";
        this.state = "query";
      } else if (c4 === p2("#")) {
        this.url.fragment = "";
        this.state = "fragment";
      } else if (!isNaN(c4)) {
        this.url.query = null;
        this.url.path.pop();
        this.state = "path";
        --this.pointer;
      }
    }
    return true;
  }
  parseRelativeSlash(c4) {
    if (isSpecial(this.url) && (c4 === p2("/") || c4 === p2("\\"))) {
      if (c4 === p2("\\")) {
        this.parseError = true;
      }
      this.state = "special authority ignore slashes";
    } else if (c4 === p2("/")) {
      this.state = "authority";
    } else {
      this.url.username = this.base.username;
      this.url.password = this.base.password;
      this.url.host = this.base.host;
      this.url.port = this.base.port;
      this.state = "path";
      --this.pointer;
    }
    return true;
  }
  parseSpecialAuthoritySlashes(c4) {
    if (c4 === p2("/") && this.input[this.pointer + 1] === p2("/")) {
      this.state = "special authority ignore slashes";
      ++this.pointer;
    } else {
      this.parseError = true;
      this.state = "special authority ignore slashes";
      --this.pointer;
    }
    return true;
  }
  parseSpecialAuthorityIgnoreSlashes(c4) {
    if (c4 !== p2("/") && c4 !== p2("\\")) {
      this.state = "authority";
      --this.pointer;
    } else {
      this.parseError = true;
    }
    return true;
  }
  parseAuthority(c4, cStr) {
    if (c4 === p2("@")) {
      this.parseError = true;
      if (this.atFlag) {
        this.buffer = `%40${this.buffer}`;
      }
      this.atFlag = true;
      const len = countSymbols(this.buffer);
      for (let pointer = 0; pointer < len; ++pointer) {
        const codePoint = this.buffer.codePointAt(pointer);
        if (codePoint === p2(":") && !this.passwordTokenSeenFlag) {
          this.passwordTokenSeenFlag = true;
          continue;
        }
        const encodedCodePoints = utf8PercentEncodeCodePoint(codePoint, isUserinfoPercentEncode);
        if (this.passwordTokenSeenFlag) {
          this.url.password += encodedCodePoints;
        } else {
          this.url.username += encodedCodePoints;
        }
      }
      this.buffer = "";
    } else if (isNaN(c4) || c4 === p2("/") || c4 === p2("?") || c4 === p2("#") || isSpecial(this.url) && c4 === p2("\\")) {
      if (this.atFlag && this.buffer === "") {
        this.parseError = true;
        return failure;
      }
      this.pointer -= countSymbols(this.buffer) + 1;
      this.buffer = "";
      this.state = "host";
    } else {
      this.buffer += cStr;
    }
    return true;
  }
  parseHostName(c4, cStr) {
    if (this.stateOverride && this.url.scheme === "file") {
      --this.pointer;
      this.state = "file host";
    } else if (c4 === p2(":") && !this.arrFlag) {
      if (this.buffer === "") {
        this.parseError = true;
        return failure;
      }
      if (this.stateOverride === "hostname") {
        return false;
      }
      const host = parseHost(this.buffer, isNotSpecial(this.url));
      if (host === failure) {
        return failure;
      }
      this.url.host = host;
      this.buffer = "";
      this.state = "port";
    } else if (isNaN(c4) || c4 === p2("/") || c4 === p2("?") || c4 === p2("#") || isSpecial(this.url) && c4 === p2("\\")) {
      --this.pointer;
      if (isSpecial(this.url) && this.buffer === "") {
        this.parseError = true;
        return failure;
      } else if (this.stateOverride && this.buffer === "" && (includesCredentials(this.url) || this.url.port !== null)) {
        this.parseError = true;
        return false;
      }
      const host = parseHost(this.buffer, isNotSpecial(this.url));
      if (host === failure) {
        return failure;
      }
      this.url.host = host;
      this.buffer = "";
      this.state = "path start";
      if (this.stateOverride) {
        return false;
      }
    } else {
      if (c4 === p2("[")) {
        this.arrFlag = true;
      } else if (c4 === p2("]")) {
        this.arrFlag = false;
      }
      this.buffer += cStr;
    }
    return true;
  }
  parsePort(c4, cStr) {
    if (isASCIIDigit(c4)) {
      this.buffer += cStr;
    } else if (isNaN(c4) || c4 === p2("/") || c4 === p2("?") || c4 === p2("#") || isSpecial(this.url) && c4 === p2("\\") || this.stateOverride) {
      if (this.buffer !== "") {
        const port = parseInt(this.buffer);
        if (port > 2 ** 16 - 1) {
          this.parseError = true;
          return failure;
        }
        this.url.port = port === defaultPort(this.url.scheme) ? null : port;
        this.buffer = "";
      }
      if (this.stateOverride) {
        return false;
      }
      this.state = "path start";
      --this.pointer;
    } else {
      this.parseError = true;
      return failure;
    }
    return true;
  }
  parseFile(c4) {
    this.url.scheme = "file";
    this.url.host = "";
    if (c4 === p2("/") || c4 === p2("\\")) {
      if (c4 === p2("\\")) {
        this.parseError = true;
      }
      this.state = "file slash";
    } else if (this.base !== null && this.base.scheme === "file") {
      this.url.host = this.base.host;
      this.url.path = this.base.path.slice();
      this.url.query = this.base.query;
      if (c4 === p2("?")) {
        this.url.query = "";
        this.state = "query";
      } else if (c4 === p2("#")) {
        this.url.fragment = "";
        this.state = "fragment";
      } else if (!isNaN(c4)) {
        this.url.query = null;
        if (!startsWithWindowsDriveLetter(this.input, this.pointer)) {
          shortenPath(this.url);
        } else {
          this.parseError = true;
          this.url.path = [];
        }
        this.state = "path";
        --this.pointer;
      }
    } else {
      this.state = "path";
      --this.pointer;
    }
    return true;
  }
  parseFileSlash(c4) {
    if (c4 === p2("/") || c4 === p2("\\")) {
      if (c4 === p2("\\")) {
        this.parseError = true;
      }
      this.state = "file host";
    } else {
      if (this.base !== null && this.base.scheme === "file") {
        if (!startsWithWindowsDriveLetter(this.input, this.pointer) && isNormalizedWindowsDriveLetterString(this.base.path[0])) {
          this.url.path.push(this.base.path[0]);
        }
        this.url.host = this.base.host;
      }
      this.state = "path";
      --this.pointer;
    }
    return true;
  }
  parseFileHost(c4, cStr) {
    if (isNaN(c4) || c4 === p2("/") || c4 === p2("\\") || c4 === p2("?") || c4 === p2("#")) {
      --this.pointer;
      if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) {
        this.parseError = true;
        this.state = "path";
      } else if (this.buffer === "") {
        this.url.host = "";
        if (this.stateOverride) {
          return false;
        }
        this.state = "path start";
      } else {
        let host = parseHost(this.buffer, isNotSpecial(this.url));
        if (host === failure) {
          return failure;
        }
        if (host === "localhost") {
          host = "";
        }
        this.url.host = host;
        if (this.stateOverride) {
          return false;
        }
        this.buffer = "";
        this.state = "path start";
      }
    } else {
      this.buffer += cStr;
    }
    return true;
  }
  parsePathStart(c4) {
    if (isSpecial(this.url)) {
      if (c4 === p2("\\")) {
        this.parseError = true;
      }
      this.state = "path";
      if (c4 !== p2("/") && c4 !== p2("\\")) {
        --this.pointer;
      }
    } else if (!this.stateOverride && c4 === p2("?")) {
      this.url.query = "";
      this.state = "query";
    } else if (!this.stateOverride && c4 === p2("#")) {
      this.url.fragment = "";
      this.state = "fragment";
    } else if (c4 !== void 0) {
      this.state = "path";
      if (c4 !== p2("/")) {
        --this.pointer;
      }
    } else if (this.stateOverride && this.url.host === null) {
      this.url.path.push("");
    }
    return true;
  }
  parsePath(c4) {
    if (isNaN(c4) || c4 === p2("/") || isSpecial(this.url) && c4 === p2("\\") || !this.stateOverride && (c4 === p2("?") || c4 === p2("#"))) {
      if (isSpecial(this.url) && c4 === p2("\\")) {
        this.parseError = true;
      }
      if (isDoubleDot(this.buffer)) {
        shortenPath(this.url);
        if (c4 !== p2("/") && !(isSpecial(this.url) && c4 === p2("\\"))) {
          this.url.path.push("");
        }
      } else if (isSingleDot(this.buffer) && c4 !== p2("/") && !(isSpecial(this.url) && c4 === p2("\\"))) {
        this.url.path.push("");
      } else if (!isSingleDot(this.buffer)) {
        if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) {
          this.buffer = `${this.buffer[0]}:`;
        }
        this.url.path.push(this.buffer);
      }
      this.buffer = "";
      if (c4 === p2("?")) {
        this.url.query = "";
        this.state = "query";
      }
      if (c4 === p2("#")) {
        this.url.fragment = "";
        this.state = "fragment";
      }
    } else {
      if (c4 === p2("%") && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
        this.parseError = true;
      }
      this.buffer += utf8PercentEncodeCodePoint(c4, isPathPercentEncode);
    }
    return true;
  }
  parseOpaquePath(c4) {
    if (c4 === p2("?")) {
      this.url.query = "";
      this.state = "query";
    } else if (c4 === p2("#")) {
      this.url.fragment = "";
      this.state = "fragment";
    } else {
      if (!isNaN(c4) && c4 !== p2("%")) {
        this.parseError = true;
      }
      if (c4 === p2("%") && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
        this.parseError = true;
      }
      if (!isNaN(c4)) {
        this.url.path += utf8PercentEncodeCodePoint(c4, isC0ControlPercentEncode);
      }
    }
    return true;
  }
  parseQuery(c4, cStr) {
    if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") {
      this.encodingOverride = "utf-8";
    }
    if (!this.stateOverride && c4 === p2("#") || isNaN(c4)) {
      const queryPercentEncodePredicate = isSpecial(this.url) ? isSpecialQueryPercentEncode : isQueryPercentEncode;
      this.url.query += utf8PercentEncodeString(this.buffer, queryPercentEncodePredicate);
      this.buffer = "";
      if (c4 === p2("#")) {
        this.url.fragment = "";
        this.state = "fragment";
      }
    } else if (!isNaN(c4)) {
      if (c4 === p2("%") && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
        this.parseError = true;
      }
      this.buffer += cStr;
    }
    return true;
  }
  parseFragment(c4) {
    if (!isNaN(c4)) {
      if (c4 === p2("%") && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
        this.parseError = true;
      }
      this.url.fragment += utf8PercentEncodeCodePoint(c4, isFragmentPercentEncode);
    }
    return true;
  }
};
var fileOtherwiseCodePoints = /* @__PURE__ */ new Set([p2("/"), p2("\\"), p2("?"), p2("#")]);
function startsWithWindowsDriveLetter(input, pointer) {
  const length = input.length - pointer;
  return length >= 2 && isWindowsDriveLetterCodePoints(input[pointer], input[pointer + 1]) && (length === 2 || fileOtherwiseCodePoints.has(input[pointer + 2]));
}
function serializeURL(url, excludeFragment) {
  let output = `${url.scheme}:`;
  if (url.host !== null) {
    output += "//";
    if (url.username !== "" || url.password !== "") {
      output += url.username;
      if (url.password !== "") {
        output += `:${url.password}`;
      }
      output += "@";
    }
    output += serializeHost(url.host);
    if (url.port !== null) {
      output += `:${url.port}`;
    }
  }
  if (url.host === null && !hasAnOpaquePath(url) && url.path.length > 1 && url.path[0] === "") {
    output += "/.";
  }
  output += serializePath(url);
  if (url.query !== null) {
    output += `?${url.query}`;
  }
  if (!excludeFragment && url.fragment !== null) {
    output += `#${url.fragment}`;
  }
  return output;
}
function serializeOrigin(tuple) {
  let result = `${tuple.scheme}://`;
  result += serializeHost(tuple.host);
  if (tuple.port !== null) {
    result += `:${tuple.port}`;
  }
  return result;
}
function serializePath(url) {
  if (typeof url.path === "string") {
    return url.path;
  }
  let output = "";
  for (const segment of url.path) {
    output += `/${segment}`;
  }
  return output;
}
function serializeURLOrigin(url) {
  switch (url.scheme) {
    case "blob":
      try {
        return serializeURLOrigin(parseURL(serializePath(url)));
      } catch (e4) {
        return "null";
      }
    case "ftp":
    case "http":
    case "https":
    case "ws":
    case "wss":
      return serializeOrigin({
        scheme: url.scheme,
        host: url.host,
        port: url.port
      });
    case "file":
      return "null";
    default:
      return "null";
  }
}
function basicURLParse(input, options) {
  if (options === void 0) {
    options = {};
  }
  const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride);
  if (usm.failure) {
    return null;
  }
  return usm.url;
}
function setTheUsername(url, username) {
  url.username = utf8PercentEncodeString(username, isUserinfoPercentEncode);
}
function setThePassword(url, password) {
  url.password = utf8PercentEncodeString(password, isUserinfoPercentEncode);
}
function serializeInteger(integer) {
  return String(integer);
}
function parseURL(input, options) {
  if (options === void 0) {
    options = {};
  }
  return basicURLParse(input, {
    baseURL: options.baseURL,
    encodingOverride: options.encodingOverride
  });
}
var URLImpl = class {
  //Include URL type for "url" and "base" params.
  constructor(url, base3) {
    let parsedBase = null;
    if (base3 !== void 0) {
      if (base3 instanceof URL) {
        base3 = base3.href;
      }
      parsedBase = basicURLParse(base3);
      if (parsedBase === null) {
        throw new TypeError(`Invalid base URL: ${base3}`);
      }
    }
    if (url instanceof URL) {
      url = url.href;
    }
    const parsedURL = basicURLParse(url, { baseURL: parsedBase });
    if (parsedURL === null) {
      throw new TypeError(`Invalid URL: ${url}`);
    }
    const query = parsedURL.query !== null ? parsedURL.query : "";
    this._url = parsedURL;
    this._query = new URLSearchParamsImpl(query, {
      doNotStripQMark: true
    });
    this._query._url = this;
  }
  get href() {
    return serializeURL(this._url);
  }
  set href(v4) {
    const parsedURL = basicURLParse(v4);
    if (parsedURL === null) {
      throw new TypeError(`Invalid URL: ${v4}`);
    }
    this._url = parsedURL;
    this._query._list.splice(0);
    const { query } = parsedURL;
    if (query !== null) {
      this._query._list = parseUrlencodedString(query);
    }
  }
  get origin() {
    return serializeURLOrigin(this._url);
  }
  get protocol() {
    return `${this._url.scheme}:`;
  }
  set protocol(v4) {
    basicURLParse(`${v4}:`, {
      url: this._url,
      stateOverride: "scheme start"
    });
  }
  get username() {
    return this._url.username;
  }
  set username(v4) {
    if (cannotHaveAUsernamePasswordPort(this._url)) {
      return;
    }
    setTheUsername(this._url, v4);
  }
  get password() {
    return this._url.password;
  }
  set password(v4) {
    if (cannotHaveAUsernamePasswordPort(this._url)) {
      return;
    }
    setThePassword(this._url, v4);
  }
  get host() {
    const url = this._url;
    if (url.host === null) {
      return "";
    }
    if (url.port === null) {
      return serializeHost(url.host);
    }
    return `${serializeHost(url.host)}:${serializeInteger(url.port)}`;
  }
  set host(v4) {
    if (hasAnOpaquePath(this._url)) {
      return;
    }
    basicURLParse(v4, { url: this._url, stateOverride: "host" });
  }
  get hostname() {
    if (this._url.host === null) {
      return "";
    }
    return serializeHost(this._url.host);
  }
  set hostname(v4) {
    if (hasAnOpaquePath(this._url)) {
      return;
    }
    basicURLParse(v4, { url: this._url, stateOverride: "hostname" });
  }
  get port() {
    if (this._url.port === null) {
      return "";
    }
    return serializeInteger(this._url.port);
  }
  set port(v4) {
    if (cannotHaveAUsernamePasswordPort(this._url)) {
      return;
    }
    if (v4 === "") {
      this._url.port = null;
    } else {
      basicURLParse(v4, { url: this._url, stateOverride: "port" });
    }
  }
  get pathname() {
    return serializePath(this._url);
  }
  set pathname(v4) {
    if (hasAnOpaquePath(this._url)) {
      return;
    }
    this._url.path = [];
    basicURLParse(v4, { url: this._url, stateOverride: "path start" });
  }
  get search() {
    if (this._url.query === null || this._url.query === "") {
      return "";
    }
    return `?${this._url.query}`;
  }
  set search(v4) {
    const url = this._url;
    if (v4 === "") {
      url.query = null;
      this._query._list = [];
      return;
    }
    const input = v4[0] === "?" ? v4.substring(1) : v4;
    url.query = "";
    basicURLParse(input, { url, stateOverride: "query" });
    this._query._list = parseUrlencodedString(input);
  }
  get searchParams() {
    return this._query;
  }
  get hash() {
    if (this._url.fragment === null || this._url.fragment === "") {
      return "";
    }
    return `#${this._url.fragment}`;
  }
  set hash(v4) {
    if (v4 === "") {
      this._url.fragment = null;
      return;
    }
    const input = v4[0] === "#" ? v4.substring(1) : v4;
    this._url.fragment = "";
    basicURLParse(input, { url: this._url, stateOverride: "fragment" });
  }
  toJSON() {
    return this.href;
  }
};

// ../taler-util/lib/url.js
(function() {
  if (typeof globalThis === "object")
    return;
  Object.defineProperty(Object.prototype, "__magic__", {
    get: function() {
      return this;
    },
    configurable: true
    // This makes it possible to `delete` the getter later.
  });
  __magic__.globalThis = __magic__;
  delete Object.prototype.__magic__;
})();
var useOwnUrlImp = true;
var _URL = globalThis.URL;
if (useOwnUrlImp || !_URL) {
  globalThis.URL = _URL = URLImpl;
  _URL = URLImpl;
}
var URL2 = _URL;
var _URLSearchParams = globalThis.URLSearchParams;
if (useOwnUrlImp || !_URLSearchParams) {
  globalThis.URLSearchParams = URLSearchParamsImpl;
  _URLSearchParams = URLSearchParamsImpl;
}
var URLSearchParams2 = _URLSearchParams;

// ../taler-util/lib/helpers.js
function canonicalizeBaseUrl(url) {
  if (!url.startsWith("http") && !url.startsWith("https")) {
    url = "https://" + url;
  }
  const x3 = new URL2(url);
  if (!x3.pathname.endsWith("/")) {
    x3.pathname = x3.pathname + "/";
  }
  x3.search = "";
  x3.hash = "";
  return x3.href;
}
function canonicalJson(obj) {
  obj = JSON.parse(JSON.stringify(obj));
  if (typeof obj === "string") {
    return JSON.stringify(obj);
  }
  if (typeof obj === "number" || typeof obj === "boolean" || obj === null) {
    return JSON.stringify(obj);
  }
  if (Array.isArray(obj)) {
    const objs = obj.map((e4) => canonicalJson(e4));
    return `[${objs.join(",")}]`;
  }
  const keys = [];
  for (const key in obj) {
    keys.push(key);
  }
  keys.sort();
  let s4 = "{";
  for (let i4 = 0; i4 < keys.length; i4++) {
    const key = keys[i4];
    s4 += JSON.stringify(key) + ":" + canonicalJson(obj[key]);
    if (i4 !== keys.length - 1) {
      s4 += ",";
    }
  }
  return s4 + "}";
}
function strcmp(s1, s22) {
  if (s1 < s22) {
    return -1;
  }
  if (s1 > s22) {
    return 1;
  }
  return 0;
}
function j2s(x3) {
  return JSON.stringify(x3, void 0, 2);
}

// ../taler-util/lib/logging.js
var isNode = typeof process !== "undefined" && typeof process.release !== "undefined" && process.release.name === "node";
var LogLevel;
(function(LogLevel2) {
  LogLevel2["Trace"] = "trace";
  LogLevel2["Message"] = "message";
  LogLevel2["Info"] = "info";
  LogLevel2["Warn"] = "warn";
  LogLevel2["Error"] = "error";
  LogLevel2["None"] = "none";
})(LogLevel || (LogLevel = {}));
var globalLogLevel = LogLevel.Info;
var byTagLogLevel = {};
var nativeLogging = false;
Error.prototype.toString = function() {
  if (this === null || typeof this !== "object" && typeof this !== "function") {
    throw new TypeError();
  }
  let name = this.name;
  name = name === void 0 ? "Error" : `${name}`;
  let msg = this.message;
  msg = msg === void 0 ? "" : `${msg}`;
  let cause = "";
  if ("cause" in this) {
    cause = `
 Caused by: ${this.cause}`;
  }
  return `${name}: ${msg}${cause}`;
};
function writeNativeLog(message, tag, level, args) {
  const logFn = globalThis.__nativeLog;
  if (logFn) {
    let m4;
    if (args.length == 0) {
      m4 = message;
    } else {
      m4 = message + " " + args.toString();
    }
    logFn(level, tag, message);
  }
}
function writeNodeLog(message, tag, level, args) {
  try {
    let msg = `${(/* @__PURE__ */ new Date()).toISOString()} ${tag} ${level} ${message}`;
    if (args.length != 0) {
      msg += ` ${JSON.stringify(args, void 0, 2)}
`;
    } else {
      msg += `
`;
    }
    process.stderr.write(msg);
  } catch (e4) {
    let msg = `${(/* @__PURE__ */ new Date()).toISOString()} (logger) FATAL `;
    if (e4 instanceof Error) {
      msg += `failed to write log: ${e4.message}
`;
    } else {
      msg += "failed to write log\n";
    }
    process.stderr.write(msg);
  }
}
var Logger = class {
  constructor(tag) {
    this.tag = tag;
  }
  shouldLogTrace() {
    const level = byTagLogLevel[this.tag] ?? globalLogLevel;
    switch (level) {
      case LogLevel.Trace:
        return true;
      case LogLevel.Message:
      case LogLevel.Info:
      case LogLevel.Warn:
      case LogLevel.Error:
      case LogLevel.None:
        return false;
    }
  }
  shouldLogInfo() {
    const level = byTagLogLevel[this.tag] ?? globalLogLevel;
    switch (level) {
      case LogLevel.Trace:
      case LogLevel.Message:
      case LogLevel.Info:
        return true;
      case LogLevel.Warn:
      case LogLevel.Error:
      case LogLevel.None:
        return false;
    }
  }
  shouldLogWarn() {
    const level = byTagLogLevel[this.tag] ?? globalLogLevel;
    switch (level) {
      case LogLevel.Trace:
      case LogLevel.Message:
      case LogLevel.Info:
      case LogLevel.Warn:
        return true;
      case LogLevel.Error:
      case LogLevel.None:
        return false;
    }
  }
  shouldLogError() {
    const level = byTagLogLevel[this.tag] ?? globalLogLevel;
    switch (level) {
      case LogLevel.Trace:
      case LogLevel.Message:
      case LogLevel.Info:
      case LogLevel.Warn:
      case LogLevel.Error:
        return true;
      case LogLevel.None:
        return false;
    }
  }
  info(message, ...args) {
    if (!this.shouldLogInfo()) {
      return;
    }
    if (nativeLogging) {
      writeNativeLog(message, this.tag, 2, args);
      return;
    }
    if (isNode) {
      writeNodeLog(message, this.tag, "INFO", args);
    } else {
      console.info(`${(/* @__PURE__ */ new Date()).toISOString()} ${this.tag} INFO ` + message, ...args);
    }
  }
  warn(message, ...args) {
    if (!this.shouldLogWarn()) {
      return;
    }
    if (nativeLogging) {
      writeNativeLog(message, this.tag, 3, args);
      return;
    }
    if (isNode) {
      writeNodeLog(message, this.tag, "WARN", args);
    } else {
      console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} ${this.tag} INFO ` + message, ...args);
    }
  }
  error(message, ...args) {
    if (!this.shouldLogError()) {
      return;
    }
    if (nativeLogging) {
      writeNativeLog(message, this.tag, 4, args);
      return;
    }
    if (isNode) {
      writeNodeLog(message, this.tag, "ERROR", args);
    } else {
      console.info(`${(/* @__PURE__ */ new Date()).toISOString()} ${this.tag} ERROR ` + message, ...args);
    }
  }
  trace(message, ...args) {
    if (!this.shouldLogTrace()) {
      return;
    }
    if (nativeLogging) {
      writeNativeLog(message, this.tag, 1, args);
      return;
    }
    if (isNode) {
      writeNodeLog(message, this.tag, "TRACE", args);
    } else {
      console.info(`${(/* @__PURE__ */ new Date()).toISOString()} ${this.tag} TRACE ` + message, ...args);
    }
  }
  reportBreak() {
    if (!this.shouldLogError()) {
      return;
    }
    const location2 = new Error("programming error");
    this.error(`assertion failed: ${location2.stack}`);
  }
};

// ../taler-util/lib/codec.js
var logger = new Logger("codec.ts");
var DecodingError = class _DecodingError extends Error {
  constructor(message) {
    super(message);
    Object.setPrototypeOf(this, _DecodingError.prototype);
    this.name = "DecodingError";
  }
};
function renderContext(c4) {
  const p5 = c4?.path;
  if (p5) {
    return p5.join(".");
  } else {
    return "(unknown)";
  }
}
function joinContext(c4, part) {
  const path = c4?.path ?? [];
  return {
    path: path.concat([part])
  };
}
var ObjectCodecBuilder = class {
  constructor() {
    this.propList = [];
  }
  /**
   * Define a property for the object.
   */
  property(x3, codec) {
    if (!codec) {
      throw Error("inner codec must be defined");
    }
    this.propList.push({ name: x3, codec });
    return this;
  }
  /**
   * Return the built codec.
   *
   * @param objectDisplayName name of the object that this codec operates on,
   *   used in error messages.
   */
  build(objectDisplayName) {
    const propList = this.propList;
    return {
      decode(x3, c4) {
        if (!c4) {
          c4 = {
            path: [`(${objectDisplayName})`]
          };
        }
        if (typeof x3 !== "object") {
          throw new DecodingError(`expected object for ${objectDisplayName} at ${renderContext(c4)} but got ${typeof x3}`);
        }
        const obj = {};
        for (const prop of propList) {
          const propRawVal = x3[prop.name];
          const propVal = prop.codec.decode(propRawVal, joinContext(c4, prop.name));
          obj[prop.name] = propVal;
        }
        return obj;
      }
    };
  }
};
var UnionCodecBuilder = class {
  constructor(discriminator, baseCodec) {
    this.discriminator = discriminator;
    this.baseCodec = baseCodec;
    this.alternatives = /* @__PURE__ */ new Map();
  }
  /**
   * Define a property for the object.
   */
  alternative(tagValue, codec) {
    if (!codec) {
      throw Error("inner codec must be defined");
    }
    this.alternatives.set(tagValue, { codec, tagValue });
    return this;
  }
  /**
   * Return the built codec.
   *
   * @param objectDisplayName name of the object that this codec operates on,
   *   used in error messages.
   */
  build(objectDisplayName) {
    const alternatives = this.alternatives;
    const discriminator = this.discriminator;
    const baseCodec = this.baseCodec;
    return {
      decode(x3, c4) {
        if (!c4) {
          c4 = {
            path: [`(${objectDisplayName})`]
          };
        }
        const d4 = x3[discriminator];
        if (d4 === void 0) {
          throw new DecodingError(`expected tag for ${objectDisplayName} at ${renderContext(c4)}.${String(discriminator)}`);
        }
        const alt = alternatives.get(d4);
        if (!alt) {
          throw new DecodingError(`unknown tag for ${objectDisplayName} ${d4} at ${renderContext(c4)}.${String(discriminator)}`);
        }
        const altDecoded = alt.codec.decode(x3);
        if (baseCodec) {
          const baseDecoded = baseCodec.decode(x3, c4);
          return { ...baseDecoded, ...altDecoded };
        } else {
          return altDecoded;
        }
      }
    };
  }
};
var UnionCodecPreBuilder = class {
  discriminateOn(discriminator, baseCodec) {
    return new UnionCodecBuilder(discriminator, baseCodec);
  }
};
function buildCodecForObject() {
  return new ObjectCodecBuilder();
}
function buildCodecForUnion() {
  return new UnionCodecPreBuilder();
}
function codecForMap(innerCodec) {
  if (!innerCodec) {
    throw Error("inner codec must be defined");
  }
  return {
    decode(x3, c4) {
      const map3 = {};
      if (typeof x3 !== "object") {
        throw new DecodingError(`expected object at ${renderContext(c4)}`);
      }
      for (const i4 in x3) {
        map3[i4] = innerCodec.decode(x3[i4], joinContext(c4, `[${i4}]`));
      }
      return map3;
    }
  };
}
function codecForList(innerCodec) {
  if (!innerCodec) {
    throw Error("inner codec must be defined");
  }
  return {
    decode(x3, c4) {
      const arr = [];
      if (!Array.isArray(x3)) {
        throw new DecodingError(`expected array at ${renderContext(c4)}`);
      }
      for (const i4 in x3) {
        arr.push(innerCodec.decode(x3[i4], joinContext(c4, `[${i4}]`)));
      }
      return arr;
    }
  };
}
function codecForNumber() {
  return {
    decode(x3, c4) {
      if (typeof x3 === "number") {
        return x3;
      }
      throw new DecodingError(`expected number at ${renderContext(c4)} but got ${typeof x3}`);
    }
  };
}
function codecForString() {
  return {
    decode(x3, c4) {
      if (typeof x3 === "string") {
        return x3;
      }
      throw new DecodingError(`expected string at ${renderContext(c4)} but got ${typeof x3}`);
    }
  };
}
function codecForAny() {
  return {
    decode(x3, c4) {
      return x3;
    }
  };
}
function codecForConstString(s4) {
  return {
    decode(x3, c4) {
      if (x3 === s4) {
        return x3;
      }
      if (typeof x3 !== "string") {
        throw new DecodingError(`expected string constant "${s4}" at ${renderContext(c4)} but got ${typeof x3}`);
      }
      throw new DecodingError(`expected string constant "${s4}" at ${renderContext(c4)} but got string value "${x3}"`);
    }
  };
}
function codecOptional(innerCodec) {
  return {
    decode(x3, c4) {
      if (x3 === void 0 || x3 === null) {
        return void 0;
      }
      return innerCodec.decode(x3, c4);
    }
  };
}
function codecForEither(...alts) {
  return {
    decode(x3, c4) {
      for (const alt of alts) {
        try {
          return alt.decode(x3, c4);
        } catch (e4) {
          continue;
        }
      }
      if (logger.shouldLogTrace()) {
        logger.trace(`offending value: ${j2s(x3)}`);
      }
      throw new DecodingError(`No alternative matched at at ${renderContext(c4)}`);
    }
  };
}

// ../taler-util/lib/taler-crypto.js
var import_big_integer = __toESM(require_BigInteger(), 1);

// ../../node_modules/.pnpm/fflate@0.8.1/node_modules/fflate/esm/browser.js
var u8 = Uint8Array;
var u16 = Uint16Array;
var i32 = Int32Array;
var fleb = new u8([
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  1,
  1,
  1,
  1,
  2,
  2,
  2,
  2,
  3,
  3,
  3,
  3,
  4,
  4,
  4,
  4,
  5,
  5,
  5,
  5,
  0,
  /* unused */
  0,
  0,
  /* impossible */
  0
]);
var fdeb = new u8([
  0,
  0,
  0,
  0,
  1,
  1,
  2,
  2,
  3,
  3,
  4,
  4,
  5,
  5,
  6,
  6,
  7,
  7,
  8,
  8,
  9,
  9,
  10,
  10,
  11,
  11,
  12,
  12,
  13,
  13,
  /* unused */
  0,
  0
]);
var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
var freb = function(eb, start) {
  var b4 = new u16(31);
  for (var i4 = 0; i4 < 31; ++i4) {
    b4[i4] = start += 1 << eb[i4 - 1];
  }
  var r4 = new i32(b4[30]);
  for (var i4 = 1; i4 < 30; ++i4) {
    for (var j4 = b4[i4]; j4 < b4[i4 + 1]; ++j4) {
      r4[j4] = j4 - b4[i4] << 5 | i4;
    }
  }
  return { b: b4, r: r4 };
};
var _a = freb(fleb, 2);
var fl = _a.b;
var revfl = _a.r;
fl[28] = 258, revfl[258] = 28;
var _b = freb(fdeb, 0);
var fd = _b.b;
var revfd = _b.r;
var rev = new u16(32768);
for (i4 = 0; i4 < 32768; ++i4) {
  x3 = (i4 & 43690) >> 1 | (i4 & 21845) << 1;
  x3 = (x3 & 52428) >> 2 | (x3 & 13107) << 2;
  x3 = (x3 & 61680) >> 4 | (x3 & 3855) << 4;
  rev[i4] = ((x3 & 65280) >> 8 | (x3 & 255) << 8) >> 1;
}
var x3;
var i4;
var hMap = function(cd, mb, r4) {
  var s4 = cd.length;
  var i4 = 0;
  var l4 = new u16(mb);
  for (; i4 < s4; ++i4) {
    if (cd[i4])
      ++l4[cd[i4] - 1];
  }
  var le = new u16(mb);
  for (i4 = 1; i4 < mb; ++i4) {
    le[i4] = le[i4 - 1] + l4[i4 - 1] << 1;
  }
  var co;
  if (r4) {
    co = new u16(1 << mb);
    var rvb = 15 - mb;
    for (i4 = 0; i4 < s4; ++i4) {
      if (cd[i4]) {
        var sv = i4 << 4 | cd[i4];
        var r_1 = mb - cd[i4];
        var v4 = le[cd[i4] - 1]++ << r_1;
        for (var m4 = v4 | (1 << r_1) - 1; v4 <= m4; ++v4) {
          co[rev[v4] >> rvb] = sv;
        }
      }
    }
  } else {
    co = new u16(s4);
    for (i4 = 0; i4 < s4; ++i4) {
      if (cd[i4]) {
        co[i4] = rev[le[cd[i4] - 1]++] >> 15 - cd[i4];
      }
    }
  }
  return co;
};
var flt = new u8(288);
for (i4 = 0; i4 < 144; ++i4)
  flt[i4] = 8;
var i4;
for (i4 = 144; i4 < 256; ++i4)
  flt[i4] = 9;
var i4;
for (i4 = 256; i4 < 280; ++i4)
  flt[i4] = 7;
var i4;
for (i4 = 280; i4 < 288; ++i4)
  flt[i4] = 8;
var i4;
var fdt = new u8(32);
for (i4 = 0; i4 < 32; ++i4)
  fdt[i4] = 5;
var i4;
var flm = /* @__PURE__ */ hMap(flt, 9, 0);
var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
var fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
var max = function(a4) {
  var m4 = a4[0];
  for (var i4 = 1; i4 < a4.length; ++i4) {
    if (a4[i4] > m4)
      m4 = a4[i4];
  }
  return m4;
};
var bits = function(d4, p5, m4) {
  var o4 = p5 / 8 | 0;
  return (d4[o4] | d4[o4 + 1] << 8) >> (p5 & 7) & m4;
};
var bits16 = function(d4, p5) {
  var o4 = p5 / 8 | 0;
  return (d4[o4] | d4[o4 + 1] << 8 | d4[o4 + 2] << 16) >> (p5 & 7);
};
var shft = function(p5) {
  return (p5 + 7) / 8 | 0;
};
var slc = function(v4, s4, e4) {
  if (s4 == null || s4 < 0)
    s4 = 0;
  if (e4 == null || e4 > v4.length)
    e4 = v4.length;
  return new u8(v4.subarray(s4, e4));
};
var ec = [
  "unexpected EOF",
  "invalid block type",
  "invalid length/literal",
  "invalid distance",
  "stream finished",
  "no stream handler",
  ,
  "no callback",
  "invalid UTF-8 data",
  "extra field too long",
  "date not in range 1980-2099",
  "filename too long",
  "stream finishing",
  "invalid zip data"
  // determined by unknown compression method
];
var err = function(ind, msg, nt2) {
  var e4 = new Error(msg || ec[ind]);
  e4.code = ind;
  if (Error.captureStackTrace)
    Error.captureStackTrace(e4, err);
  if (!nt2)
    throw e4;
  return e4;
};
var inflt = function(dat, st, buf, dict) {
  var sl = dat.length, dl = dict ? dict.length : 0;
  if (!sl || st.f && !st.l)
    return buf || new u8(0);
  var noBuf = !buf;
  var resize = noBuf || st.i != 2;
  var noSt = st.i;
  if (noBuf)
    buf = new u8(sl * 3);
  var cbuf = function(l5) {
    var bl = buf.length;
    if (l5 > bl) {
      var nbuf = new u8(Math.max(bl * 2, l5));
      nbuf.set(buf);
      buf = nbuf;
    }
  };
  var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
  var tbts = sl * 8;
  do {
    if (!lm) {
      final = bits(dat, pos, 1);
      var type = bits(dat, pos + 1, 3);
      pos += 3;
      if (!type) {
        var s4 = shft(pos) + 4, l4 = dat[s4 - 4] | dat[s4 - 3] << 8, t4 = s4 + l4;
        if (t4 > sl) {
          if (noSt)
            err(0);
          break;
        }
        if (resize)
          cbuf(bt + l4);
        buf.set(dat.subarray(s4, t4), bt);
        st.b = bt += l4, st.p = pos = t4 * 8, st.f = final;
        continue;
      } else if (type == 1)
        lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
      else if (type == 2) {
        var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
        var tl = hLit + bits(dat, pos + 5, 31) + 1;
        pos += 14;
        var ldt = new u8(tl);
        var clt = new u8(19);
        for (var i4 = 0; i4 < hcLen; ++i4) {
          clt[clim[i4]] = bits(dat, pos + i4 * 3, 7);
        }
        pos += hcLen * 3;
        var clb = max(clt), clbmsk = (1 << clb) - 1;
        var clm = hMap(clt, clb, 1);
        for (var i4 = 0; i4 < tl; ) {
          var r4 = clm[bits(dat, pos, clbmsk)];
          pos += r4 & 15;
          var s4 = r4 >> 4;
          if (s4 < 16) {
            ldt[i4++] = s4;
          } else {
            var c4 = 0, n3 = 0;
            if (s4 == 16)
              n3 = 3 + bits(dat, pos, 3), pos += 2, c4 = ldt[i4 - 1];
            else if (s4 == 17)
              n3 = 3 + bits(dat, pos, 7), pos += 3;
            else if (s4 == 18)
              n3 = 11 + bits(dat, pos, 127), pos += 7;
            while (n3--)
              ldt[i4++] = c4;
          }
        }
        var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
        lbt = max(lt);
        dbt = max(dt);
        lm = hMap(lt, lbt, 1);
        dm = hMap(dt, dbt, 1);
      } else
        err(1);
      if (pos > tbts) {
        if (noSt)
          err(0);
        break;
      }
    }
    if (resize)
      cbuf(bt + 131072);
    var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
    var lpos = pos;
    for (; ; lpos = pos) {
      var c4 = lm[bits16(dat, pos) & lms], sym = c4 >> 4;
      pos += c4 & 15;
      if (pos > tbts) {
        if (noSt)
          err(0);
        break;
      }
      if (!c4)
        err(2);
      if (sym < 256)
        buf[bt++] = sym;
      else if (sym == 256) {
        lpos = pos, lm = null;
        break;
      } else {
        var add2 = sym - 254;
        if (sym > 264) {
          var i4 = sym - 257, b4 = fleb[i4];
          add2 = bits(dat, pos, (1 << b4) - 1) + fl[i4];
          pos += b4;
        }
        var d4 = dm[bits16(dat, pos) & dms], dsym = d4 >> 4;
        if (!d4)
          err(3);
        pos += d4 & 15;
        var dt = fd[dsym];
        if (dsym > 3) {
          var b4 = fdeb[dsym];
          dt += bits16(dat, pos) & (1 << b4) - 1, pos += b4;
        }
        if (pos > tbts) {
          if (noSt)
            err(0);
          break;
        }
        if (resize)
          cbuf(bt + 131072);
        var end = bt + add2;
        if (bt < dt) {
          var shift = dl - dt, dend = Math.min(dt, end);
          if (shift + bt < 0)
            err(3);
          for (; bt < dend; ++bt)
            buf[bt] = dict[shift + bt];
        }
        for (; bt < end; ++bt)
          buf[bt] = buf[bt - dt];
      }
    }
    st.l = lm, st.p = lpos, st.b = bt, st.f = final;
    if (lm)
      final = 1, st.m = lbt, st.d = dm, st.n = dbt;
  } while (!final);
  return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
};
var wbits = function(d4, p5, v4) {
  v4 <<= p5 & 7;
  var o4 = p5 / 8 | 0;
  d4[o4] |= v4;
  d4[o4 + 1] |= v4 >> 8;
};
var wbits16 = function(d4, p5, v4) {
  v4 <<= p5 & 7;
  var o4 = p5 / 8 | 0;
  d4[o4] |= v4;
  d4[o4 + 1] |= v4 >> 8;
  d4[o4 + 2] |= v4 >> 16;
};
var hTree = function(d4, mb) {
  var t4 = [];
  for (var i4 = 0; i4 < d4.length; ++i4) {
    if (d4[i4])
      t4.push({ s: i4, f: d4[i4] });
  }
  var s4 = t4.length;
  var t22 = t4.slice();
  if (!s4)
    return { t: et, l: 0 };
  if (s4 == 1) {
    var v4 = new u8(t4[0].s + 1);
    v4[t4[0].s] = 1;
    return { t: v4, l: 1 };
  }
  t4.sort(function(a4, b4) {
    return a4.f - b4.f;
  });
  t4.push({ s: -1, f: 25001 });
  var l4 = t4[0], r4 = t4[1], i0 = 0, i1 = 1, i22 = 2;
  t4[0] = { s: -1, f: l4.f + r4.f, l: l4, r: r4 };
  while (i1 != s4 - 1) {
    l4 = t4[t4[i0].f < t4[i22].f ? i0++ : i22++];
    r4 = t4[i0 != i1 && t4[i0].f < t4[i22].f ? i0++ : i22++];
    t4[i1++] = { s: -1, f: l4.f + r4.f, l: l4, r: r4 };
  }
  var maxSym = t22[0].s;
  for (var i4 = 1; i4 < s4; ++i4) {
    if (t22[i4].s > maxSym)
      maxSym = t22[i4].s;
  }
  var tr = new u16(maxSym + 1);
  var mbt = ln(t4[i1 - 1], tr, 0);
  if (mbt > mb) {
    var i4 = 0, dt = 0;
    var lft = mbt - mb, cst = 1 << lft;
    t22.sort(function(a4, b4) {
      return tr[b4.s] - tr[a4.s] || a4.f - b4.f;
    });
    for (; i4 < s4; ++i4) {
      var i2_1 = t22[i4].s;
      if (tr[i2_1] > mb) {
        dt += cst - (1 << mbt - tr[i2_1]);
        tr[i2_1] = mb;
      } else
        break;
    }
    dt >>= lft;
    while (dt > 0) {
      var i2_2 = t22[i4].s;
      if (tr[i2_2] < mb)
        dt -= 1 << mb - tr[i2_2]++ - 1;
      else
        ++i4;
    }
    for (; i4 >= 0 && dt; --i4) {
      var i2_3 = t22[i4].s;
      if (tr[i2_3] == mb) {
        --tr[i2_3];
        ++dt;
      }
    }
    mbt = mb;
  }
  return { t: new u8(tr), l: mbt };
};
var ln = function(n3, l4, d4) {
  return n3.s == -1 ? Math.max(ln(n3.l, l4, d4 + 1), ln(n3.r, l4, d4 + 1)) : l4[n3.s] = d4;
};
var lc = function(c4) {
  var s4 = c4.length;
  while (s4 && !c4[--s4])
    ;
  var cl = new u16(++s4);
  var cli = 0, cln = c4[0], cls = 1;
  var w4 = function(v4) {
    cl[cli++] = v4;
  };
  for (var i4 = 1; i4 <= s4; ++i4) {
    if (c4[i4] == cln && i4 != s4)
      ++cls;
    else {
      if (!cln && cls > 2) {
        for (; cls > 138; cls -= 138)
          w4(32754);
        if (cls > 2) {
          w4(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
          cls = 0;
        }
      } else if (cls > 3) {
        w4(cln), --cls;
        for (; cls > 6; cls -= 6)
          w4(8304);
        if (cls > 2)
          w4(cls - 3 << 5 | 8208), cls = 0;
      }
      while (cls--)
        w4(cln);
      cls = 1;
      cln = c4[i4];
    }
  }
  return { c: cl.subarray(0, cli), n: s4 };
};
var clen = function(cf, cl) {
  var l4 = 0;
  for (var i4 = 0; i4 < cl.length; ++i4)
    l4 += cf[i4] * cl[i4];
  return l4;
};
var wfblk = function(out, pos, dat) {
  var s4 = dat.length;
  var o4 = shft(pos + 2);
  out[o4] = s4 & 255;
  out[o4 + 1] = s4 >> 8;
  out[o4 + 2] = out[o4] ^ 255;
  out[o4 + 3] = out[o4 + 1] ^ 255;
  for (var i4 = 0; i4 < s4; ++i4)
    out[o4 + i4 + 4] = dat[i4];
  return (o4 + 4 + s4) * 8;
};
var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p5) {
  wbits(out, p5++, final);
  ++lf[256];
  var _a3 = hTree(lf, 15), dlt = _a3.t, mlb = _a3.l;
  var _b2 = hTree(df, 15), ddt = _b2.t, mdb = _b2.l;
  var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
  var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
  var lcfreq = new u16(19);
  for (var i4 = 0; i4 < lclt.length; ++i4)
    ++lcfreq[lclt[i4] & 31];
  for (var i4 = 0; i4 < lcdt.length; ++i4)
    ++lcfreq[lcdt[i4] & 31];
  var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
  var nlcc = 19;
  for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
    ;
  var flen = bl + 5 << 3;
  var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
  var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
  if (bs >= 0 && flen <= ftlen && flen <= dtlen)
    return wfblk(out, p5, dat.subarray(bs, bs + bl));
  var lm, ll, dm, dl;
  wbits(out, p5, 1 + (dtlen < ftlen)), p5 += 2;
  if (dtlen < ftlen) {
    lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
    var llm = hMap(lct, mlcb, 0);
    wbits(out, p5, nlc - 257);
    wbits(out, p5 + 5, ndc - 1);
    wbits(out, p5 + 10, nlcc - 4);
    p5 += 14;
    for (var i4 = 0; i4 < nlcc; ++i4)
      wbits(out, p5 + 3 * i4, lct[clim[i4]]);
    p5 += 3 * nlcc;
    var lcts = [lclt, lcdt];
    for (var it = 0; it < 2; ++it) {
      var clct = lcts[it];
      for (var i4 = 0; i4 < clct.length; ++i4) {
        var len = clct[i4] & 31;
        wbits(out, p5, llm[len]), p5 += lct[len];
        if (len > 15)
          wbits(out, p5, clct[i4] >> 5 & 127), p5 += clct[i4] >> 12;
      }
    }
  } else {
    lm = flm, ll = flt, dm = fdm, dl = fdt;
  }
  for (var i4 = 0; i4 < li; ++i4) {
    var sym = syms[i4];
    if (sym > 255) {
      var len = sym >> 18 & 31;
      wbits16(out, p5, lm[len + 257]), p5 += ll[len + 257];
      if (len > 7)
        wbits(out, p5, sym >> 23 & 31), p5 += fleb[len];
      var dst = sym & 31;
      wbits16(out, p5, dm[dst]), p5 += dl[dst];
      if (dst > 3)
        wbits16(out, p5, sym >> 5 & 8191), p5 += fdeb[dst];
    } else {
      wbits16(out, p5, lm[sym]), p5 += ll[sym];
    }
  }
  wbits16(out, p5, lm[256]);
  return p5 + ll[256];
};
var deo = /* @__PURE__ */ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
var et = /* @__PURE__ */ new u8(0);
var dflt = function(dat, lvl, plvl, pre, post, st) {
  var s4 = st.z || dat.length;
  var o4 = new u8(pre + s4 + 5 * (1 + Math.ceil(s4 / 7e3)) + post);
  var w4 = o4.subarray(pre, o4.length - post);
  var lst = st.l;
  var pos = (st.r || 0) & 7;
  if (lvl) {
    if (pos)
      w4[0] = st.r >> 3;
    var opt = deo[lvl - 1];
    var n3 = opt >> 13, c4 = opt & 8191;
    var msk_1 = (1 << plvl) - 1;
    var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
    var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
    var hsh = function(i5) {
      return (dat[i5] ^ dat[i5 + 1] << bs1_1 ^ dat[i5 + 2] << bs2_1) & msk_1;
    };
    var syms = new i32(25e3);
    var lf = new u16(288), df = new u16(32);
    var lc_1 = 0, eb = 0, i4 = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
    for (; i4 + 2 < s4; ++i4) {
      var hv = hsh(i4);
      var imod = i4 & 32767, pimod = head[hv];
      prev[imod] = pimod;
      head[hv] = imod;
      if (wi <= i4) {
        var rem = s4 - i4;
        if ((lc_1 > 7e3 || li > 24576) && (rem > 423 || !lst)) {
          pos = wblk(dat, w4, 0, syms, lf, df, eb, li, bs, i4 - bs, pos);
          li = lc_1 = eb = 0, bs = i4;
          for (var j4 = 0; j4 < 286; ++j4)
            lf[j4] = 0;
          for (var j4 = 0; j4 < 30; ++j4)
            df[j4] = 0;
        }
        var l4 = 2, d4 = 0, ch_1 = c4, dif = imod - pimod & 32767;
        if (rem > 2 && hv == hsh(i4 - dif)) {
          var maxn = Math.min(n3, rem) - 1;
          var maxd = Math.min(32767, i4);
          var ml = Math.min(258, rem);
          while (dif <= maxd && --ch_1 && imod != pimod) {
            if (dat[i4 + l4] == dat[i4 + l4 - dif]) {
              var nl = 0;
              for (; nl < ml && dat[i4 + nl] == dat[i4 + nl - dif]; ++nl)
                ;
              if (nl > l4) {
                l4 = nl, d4 = dif;
                if (nl > maxn)
                  break;
                var mmd = Math.min(dif, nl - 2);
                var md = 0;
                for (var j4 = 0; j4 < mmd; ++j4) {
                  var ti = i4 - dif + j4 & 32767;
                  var pti = prev[ti];
                  var cd = ti - pti & 32767;
                  if (cd > md)
                    md = cd, pimod = ti;
                }
              }
            }
            imod = pimod, pimod = prev[imod];
            dif += imod - pimod & 32767;
          }
        }
        if (d4) {
          syms[li++] = 268435456 | revfl[l4] << 18 | revfd[d4];
          var lin = revfl[l4] & 31, din = revfd[d4] & 31;
          eb += fleb[lin] + fdeb[din];
          ++lf[257 + lin];
          ++df[din];
          wi = i4 + l4;
          ++lc_1;
        } else {
          syms[li++] = dat[i4];
          ++lf[dat[i4]];
        }
      }
    }
    for (i4 = Math.max(i4, wi); i4 < s4; ++i4) {
      syms[li++] = dat[i4];
      ++lf[dat[i4]];
    }
    pos = wblk(dat, w4, lst, syms, lf, df, eb, li, bs, i4 - bs, pos);
    if (!lst) {
      st.r = pos & 7 | w4[pos / 8 | 0] << 3;
      pos -= 7;
      st.h = head, st.p = prev, st.i = i4, st.w = wi;
    }
  } else {
    for (var i4 = st.w || 0; i4 < s4 + lst; i4 += 65535) {
      var e4 = i4 + 65535;
      if (e4 >= s4) {
        w4[pos / 8 | 0] = lst;
        e4 = s4;
      }
      pos = wfblk(w4, pos + 1, dat.subarray(i4, e4));
    }
    st.i = s4;
  }
  return slc(o4, 0, pre + shft(pos) + post);
};
var adler = function() {
  var a4 = 1, b4 = 0;
  return {
    p: function(d4) {
      var n3 = a4, m4 = b4;
      var l4 = d4.length | 0;
      for (var i4 = 0; i4 != l4; ) {
        var e4 = Math.min(i4 + 2655, l4);
        for (; i4 < e4; ++i4)
          m4 += n3 += d4[i4];
        n3 = (n3 & 65535) + 15 * (n3 >> 16), m4 = (m4 & 65535) + 15 * (m4 >> 16);
      }
      a4 = n3, b4 = m4;
    },
    d: function() {
      a4 %= 65521, b4 %= 65521;
      return (a4 & 255) << 24 | (a4 & 65280) << 8 | (b4 & 255) << 8 | b4 >> 8;
    }
  };
};
var dopt = function(dat, opt, pre, post, st) {
  if (!st) {
    st = { l: 1 };
    if (opt.dictionary) {
      var dict = opt.dictionary.subarray(-32768);
      var newDat = new u8(dict.length + dat.length);
      newDat.set(dict);
      newDat.set(dat, dict.length);
      dat = newDat;
      st.w = dict.length;
    }
  }
  return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 12 + opt.mem, pre, post, st);
};
var wbytes = function(d4, b4, v4) {
  for (; v4; ++b4)
    d4[b4] = v4, v4 >>>= 8;
};
var zlh = function(c4, o4) {
  var lv = o4.level, fl2 = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
  c4[0] = 120, c4[1] = fl2 << 6 | (o4.dictionary && 32);
  c4[1] |= 31 - (c4[0] << 8 | c4[1]) % 31;
  if (o4.dictionary) {
    var h4 = adler();
    h4.p(o4.dictionary);
    wbytes(c4, 2, h4.d());
  }
};
var zls = function(d4, dict) {
  if ((d4[0] & 15) != 8 || d4[0] >> 4 > 7 || (d4[0] << 8 | d4[1]) % 31)
    err(6, "invalid zlib data");
  if ((d4[1] >> 5 & 1) == +!dict)
    err(6, "invalid zlib data: " + (d4[1] & 32 ? "need" : "unexpected") + " dictionary");
  return (d4[1] >> 3 & 4) + 2;
};
function zlibSync(data, opts) {
  if (!opts)
    opts = {};
  var a4 = adler();
  a4.p(data);
  var d4 = dopt(data, opts, opts.dictionary ? 6 : 2, 4);
  return zlh(d4, opts), wbytes(d4, d4.length - 4, a4.d()), d4;
}
function unzlibSync(data, opts) {
  return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);
}
var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
var tds = 0;
try {
  td.decode(et, { stream: true });
  tds = 1;
} catch (e4) {
}

// ../../node_modules/.pnpm/hash-wasm@4.11.0/node_modules/hash-wasm/dist/index.esm.js
function __awaiter(thisArg, _arguments, P4, generator) {
  function adopt(value) {
    return value instanceof P4 ? value : new P4(function(resolve) {
      resolve(value);
    });
  }
  return new (P4 || (P4 = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject(e4);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
var Mutex = class {
  constructor() {
    this.mutex = Promise.resolve();
  }
  lock() {
    let begin = () => {
    };
    this.mutex = this.mutex.then(() => new Promise(begin));
    return new Promise((res) => {
      begin = res;
    });
  }
  dispatch(fn) {
    return __awaiter(this, void 0, void 0, function* () {
      const unlock = yield this.lock();
      try {
        return yield Promise.resolve(fn());
      } finally {
        unlock();
      }
    });
  }
};
var _a2;
function getGlobal() {
  if (typeof globalThis !== "undefined")
    return globalThis;
  if (typeof self !== "undefined")
    return self;
  if (typeof window !== "undefined")
    return window;
  return global;
}
var globalObject = getGlobal();
var nodeBuffer = (_a2 = globalObject.Buffer) !== null && _a2 !== void 0 ? _a2 : null;
var textEncoder = globalObject.TextEncoder ? new globalObject.TextEncoder() : null;
function hexCharCodesToInt(a4, b4) {
  return (a4 & 15) + (a4 >> 6 | a4 >> 3 & 8) << 4 | (b4 & 15) + (b4 >> 6 | b4 >> 3 & 8);
}
function writeHexToUInt8(buf, str) {
  const size = str.length >> 1;
  for (let i4 = 0; i4 < size; i4++) {
    const index = i4 << 1;
    buf[i4] = hexCharCodesToInt(str.charCodeAt(index), str.charCodeAt(index + 1));
  }
}
function hexStringEqualsUInt8(str, buf) {
  if (str.length !== buf.length * 2) {
    return false;
  }
  for (let i4 = 0; i4 < buf.length; i4++) {
    const strIndex = i4 << 1;
    if (buf[i4] !== hexCharCodesToInt(str.charCodeAt(strIndex), str.charCodeAt(strIndex + 1))) {
      return false;
    }
  }
  return true;
}
var alpha = "a".charCodeAt(0) - 10;
var digit = "0".charCodeAt(0);
function getDigestHex(tmpBuffer, input, hashLength) {
  let p5 = 0;
  for (let i4 = 0; i4 < hashLength; i4++) {
    let nibble = input[i4] >>> 4;
    tmpBuffer[p5++] = nibble > 9 ? nibble + alpha : nibble + digit;
    nibble = input[i4] & 15;
    tmpBuffer[p5++] = nibble > 9 ? nibble + alpha : nibble + digit;
  }
  return String.fromCharCode.apply(null, tmpBuffer);
}
var getUInt8Buffer = nodeBuffer !== null ? (data) => {
  if (typeof data === "string") {
    const buf = nodeBuffer.from(data, "utf8");
    return new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
  }
  if (nodeBuffer.isBuffer(data)) {
    return new Uint8Array(data.buffer, data.byteOffset, data.length);
  }
  if (ArrayBuffer.isView(data)) {
    return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  }
  throw new Error("Invalid data type!");
} : (data) => {
  if (typeof data === "string") {
    return textEncoder.encode(data);
  }
  if (ArrayBuffer.isView(data)) {
    return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  }
  throw new Error("Invalid data type!");
};
var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64Lookup = new Uint8Array(256);
for (let i4 = 0; i4 < base64Chars.length; i4++) {
  base64Lookup[base64Chars.charCodeAt(i4)] = i4;
}
function encodeBase64(data, pad = true) {
  const len = data.length;
  const extraBytes = len % 3;
  const parts = [];
  const len2 = len - extraBytes;
  for (let i4 = 0; i4 < len2; i4 += 3) {
    const tmp = (data[i4] << 16 & 16711680) + (data[i4 + 1] << 8 & 65280) + (data[i4 + 2] & 255);
    const triplet = base64Chars.charAt(tmp >> 18 & 63) + base64Chars.charAt(tmp >> 12 & 63) + base64Chars.charAt(tmp >> 6 & 63) + base64Chars.charAt(tmp & 63);
    parts.push(triplet);
  }
  if (extraBytes === 1) {
    const tmp = data[len - 1];
    const a4 = base64Chars.charAt(tmp >> 2);
    const b4 = base64Chars.charAt(tmp << 4 & 63);
    parts.push(`${a4}${b4}`);
    if (pad) {
      parts.push("==");
    }
  } else if (extraBytes === 2) {
    const tmp = (data[len - 2] << 8) + data[len - 1];
    const a4 = base64Chars.charAt(tmp >> 10);
    const b4 = base64Chars.charAt(tmp >> 4 & 63);
    const c4 = base64Chars.charAt(tmp << 2 & 63);
    parts.push(`${a4}${b4}${c4}`);
    if (pad) {
      parts.push("=");
    }
  }
  return parts.join("");
}
function getDecodeBase64Length(data) {
  let bufferLength = Math.floor(data.length * 0.75);
  const len = data.length;
  if (data[len - 1] === "=") {
    bufferLength -= 1;
    if (data[len - 2] === "=") {
      bufferLength -= 1;
    }
  }
  return bufferLength;
}
function decodeBase64(data) {
  const bufferLength = getDecodeBase64Length(data);
  const len = data.length;
  const bytes = new Uint8Array(bufferLength);
  let p5 = 0;
  for (let i4 = 0; i4 < len; i4 += 4) {
    const encoded1 = base64Lookup[data.charCodeAt(i4)];
    const encoded2 = base64Lookup[data.charCodeAt(i4 + 1)];
    const encoded3 = base64Lookup[data.charCodeAt(i4 + 2)];
    const encoded4 = base64Lookup[data.charCodeAt(i4 + 3)];
    bytes[p5] = encoded1 << 2 | encoded2 >> 4;
    p5 += 1;
    bytes[p5] = (encoded2 & 15) << 4 | encoded3 >> 2;
    p5 += 1;
    bytes[p5] = (encoded3 & 3) << 6 | encoded4 & 63;
    p5 += 1;
  }
  return bytes;
}
var MAX_HEAP = 16 * 1024;
var WASM_FUNC_HASH_LENGTH = 4;
var wasmMutex = new Mutex();
var wasmModuleCache = /* @__PURE__ */ new Map();
function WASMInterface(binary, hashLength) {
  return __awaiter(this, void 0, void 0, function* () {
    let wasmInstance = null;
    let memoryView = null;
    let initialized = false;
    if (typeof WebAssembly === "undefined") {
      throw new Error("WebAssembly is not supported in this environment!");
    }
    const writeMemory = (data, offset = 0) => {
      memoryView.set(data, offset);
    };
    const getMemory = () => memoryView;
    const getExports = () => wasmInstance.exports;
    const setMemorySize = (totalSize) => {
      wasmInstance.exports.Hash_SetMemorySize(totalSize);
      const arrayOffset = wasmInstance.exports.Hash_GetBuffer();
      const memoryBuffer = wasmInstance.exports.memory.buffer;
      memoryView = new Uint8Array(memoryBuffer, arrayOffset, totalSize);
    };
    const getStateSize = () => {
      const view = new DataView(wasmInstance.exports.memory.buffer);
      const stateSize = view.getUint32(wasmInstance.exports.STATE_SIZE, true);
      return stateSize;
    };
    const loadWASMPromise = wasmMutex.dispatch(() => __awaiter(this, void 0, void 0, function* () {
      if (!wasmModuleCache.has(binary.name)) {
        const asm = decodeBase64(binary.data);
        const promise = WebAssembly.compile(asm);
        wasmModuleCache.set(binary.name, promise);
      }
      const module = yield wasmModuleCache.get(binary.name);
      wasmInstance = yield WebAssembly.instantiate(module, {
        // env: {
        //   emscripten_memcpy_big: (dest, src, num) => {
        //     const memoryBuffer = wasmInstance.exports.memory.buffer;
        //     const memView = new Uint8Array(memoryBuffer, 0);
        //     memView.set(memView.subarray(src, src + num), dest);
        //   },
        //   print_memory: (offset, len) => {
        //     const memoryBuffer = wasmInstance.exports.memory.buffer;
        //     const memView = new Uint8Array(memoryBuffer, 0);
        //     console.log('print_int32', memView.subarray(offset, offset + len));
        //   },
        // },
      });
    }));
    const setupInterface = () => __awaiter(this, void 0, void 0, function* () {
      if (!wasmInstance) {
        yield loadWASMPromise;
      }
      const arrayOffset = wasmInstance.exports.Hash_GetBuffer();
      const memoryBuffer = wasmInstance.exports.memory.buffer;
      memoryView = new Uint8Array(memoryBuffer, arrayOffset, MAX_HEAP);
    });
    const init = (bits2 = null) => {
      initialized = true;
      wasmInstance.exports.Hash_Init(bits2);
    };
    const updateUInt8Array = (data) => {
      let read = 0;
      while (read < data.length) {
        const chunk = data.subarray(read, read + MAX_HEAP);
        read += chunk.length;
        memoryView.set(chunk);
        wasmInstance.exports.Hash_Update(chunk.length);
      }
    };
    const update = (data) => {
      if (!initialized) {
        throw new Error("update() called before init()");
      }
      const Uint8Buffer = getUInt8Buffer(data);
      updateUInt8Array(Uint8Buffer);
    };
    const digestChars = new Uint8Array(hashLength * 2);
    const digest = (outputType, padding = null) => {
      if (!initialized) {
        throw new Error("digest() called before init()");
      }
      initialized = false;
      wasmInstance.exports.Hash_Final(padding);
      if (outputType === "binary") {
        return memoryView.slice(0, hashLength);
      }
      return getDigestHex(digestChars, memoryView, hashLength);
    };
    const save = () => {
      if (!initialized) {
        throw new Error("save() can only be called after init() and before digest()");
      }
      const stateOffset = wasmInstance.exports.Hash_GetState();
      const stateLength = getStateSize();
      const memoryBuffer = wasmInstance.exports.memory.buffer;
      const internalState = new Uint8Array(memoryBuffer, stateOffset, stateLength);
      const prefixedState = new Uint8Array(WASM_FUNC_HASH_LENGTH + stateLength);
      writeHexToUInt8(prefixedState, binary.hash);
      prefixedState.set(internalState, WASM_FUNC_HASH_LENGTH);
      return prefixedState;
    };
    const load = (state) => {
      if (!(state instanceof Uint8Array)) {
        throw new Error("load() expects an Uint8Array generated by save()");
      }
      const stateOffset = wasmInstance.exports.Hash_GetState();
      const stateLength = getStateSize();
      const overallLength = WASM_FUNC_HASH_LENGTH + stateLength;
      const memoryBuffer = wasmInstance.exports.memory.buffer;
      if (state.length !== overallLength) {
        throw new Error(`Bad state length (expected ${overallLength} bytes, got ${state.length})`);
      }
      if (!hexStringEqualsUInt8(binary.hash, state.subarray(0, WASM_FUNC_HASH_LENGTH))) {
        throw new Error("This state was written by an incompatible hash implementation");
      }
      const internalState = state.subarray(WASM_FUNC_HASH_LENGTH);
      new Uint8Array(memoryBuffer, stateOffset, stateLength).set(internalState);
      initialized = true;
    };
    const isDataShort = (data) => {
      if (typeof data === "string") {
        return data.length < MAX_HEAP / 4;
      }
      return data.byteLength < MAX_HEAP;
    };
    let canSimplify = isDataShort;
    switch (binary.name) {
      case "argon2":
      case "scrypt":
        canSimplify = () => true;
        break;
      case "blake2b":
      case "blake2s":
        canSimplify = (data, initParam) => initParam <= 512 && isDataShort(data);
        break;
      case "blake3":
        canSimplify = (data, initParam) => initParam === 0 && isDataShort(data);
        break;
      case "xxhash64":
      case "xxhash3":
      case "xxhash128":
        canSimplify = () => false;
        break;
    }
    const calculate = (data, initParam = null, digestParam = null) => {
      if (!canSimplify(data, initParam)) {
        init(initParam);
        update(data);
        return digest("hex", digestParam);
      }
      const buffer = getUInt8Buffer(data);
      memoryView.set(buffer);
      wasmInstance.exports.Hash_Calculate(buffer.length, initParam, digestParam);
      return getDigestHex(digestChars, memoryView, hashLength);
    };
    yield setupInterface();
    return {
      getMemory,
      writeMemory,
      getExports,
      setMemorySize,
      init,
      update,
      digest,
      save,
      load,
      calculate,
      hashLength
    };
  });
}
var mutex$l = new Mutex();
var name$j = "blake2b";
var data$j = " ";
var hash$j = "656e0f66";
var wasmJson$j = {
  name: name$j,
  data: data$j,
  hash: hash$j
};
var mutex$k = new Mutex();
function validateBits$4(bits2) {
  if (!Number.isInteger(bits2) || bits2 < 8 || bits2 > 512 || bits2 % 8 !== 0) {
    return new Error("Invalid variant! Valid values: 8, 16, ..., 512");
  }
  return null;
}
function getInitParam$1(outputBits, keyBits) {
  return outputBits | keyBits << 16;
}
function createBLAKE2b(bits2 = 512, key = null) {
  if (validateBits$4(bits2)) {
    return Promise.reject(validateBits$4(bits2));
  }
  let keyBuffer = null;
  let initParam = bits2;
  if (key !== null) {
    keyBuffer = getUInt8Buffer(key);
    if (keyBuffer.length > 64) {
      return Promise.reject(new Error("Max key length is 64 bytes"));
    }
    initParam = getInitParam$1(bits2, keyBuffer.length);
  }
  const outputSize = bits2 / 8;
  return WASMInterface(wasmJson$j, outputSize).then((wasm) => {
    if (initParam > 512) {
      wasm.writeMemory(keyBuffer);
    }
    wasm.init(initParam);
    const obj = {
      init: initParam > 512 ? () => {
        wasm.writeMemory(keyBuffer);
        wasm.init(initParam);
        return obj;
      } : () => {
        wasm.init(initParam);
        return obj;
      },
      update: (data) => {
        wasm.update(data);
        return obj;
      },
      digest: (outputType) => wasm.digest(outputType),
      save: () => wasm.save(),
      load: (data) => {
        wasm.load(data);
        return obj;
      },
      blockSize: 128,
      digestSize: outputSize
    };
    return obj;
  });
}
var name$i = "argon2";
var data$i = " ";
var hash$i = "7ab14c91";
var wasmJson$i = {
  name: name$i,
  data: data$i,
  hash: hash$i
};
function encodeResult(salt, options, res) {
  const parameters = [
    `m=${options.memorySize}`,
    `t=${options.iterations}`,
    `p=${options.parallelism}`
  ].join(",");
  return `$argon2${options.hashType}$v=19$${parameters}$${encodeBase64(salt, false)}$${encodeBase64(res, false)}`;
}
var uint32View = new DataView(new ArrayBuffer(4));
function int32LE(x3) {
  uint32View.setInt32(0, x3, true);
  return new Uint8Array(uint32View.buffer);
}
function hashFunc(blake512, buf, len) {
  return __awaiter(this, void 0, void 0, function* () {
    if (len <= 64) {
      const blake = yield createBLAKE2b(len * 8);
      blake.update(int32LE(len));
      blake.update(buf);
      return blake.digest("binary");
    }
    const r4 = Math.ceil(len / 32) - 2;
    const ret = new Uint8Array(len);
    blake512.init();
    blake512.update(int32LE(len));
    blake512.update(buf);
    let vp = blake512.digest("binary");
    ret.set(vp.subarray(0, 32), 0);
    for (let i4 = 1; i4 < r4; i4++) {
      blake512.init();
      blake512.update(vp);
      vp = blake512.digest("binary");
      ret.set(vp.subarray(0, 32), i4 * 32);
    }
    const partialBytesNeeded = len - 32 * r4;
    let blakeSmall;
    if (partialBytesNeeded === 64) {
      blakeSmall = blake512;
      blakeSmall.init();
    } else {
      blakeSmall = yield createBLAKE2b(partialBytesNeeded * 8);
    }
    blakeSmall.update(vp);
    vp = blakeSmall.digest("binary");
    ret.set(vp.subarray(0, partialBytesNeeded), r4 * 32);
    return ret;
  });
}
function getHashType(type) {
  switch (type) {
    case "d":
      return 0;
    case "i":
      return 1;
    default:
      return 2;
  }
}
function argon2Internal(options) {
  var _a3;
  return __awaiter(this, void 0, void 0, function* () {
    const { parallelism, iterations, hashLength } = options;
    const password = getUInt8Buffer(options.password);
    const salt = getUInt8Buffer(options.salt);
    const version = 19;
    const hashType = getHashType(options.hashType);
    const { memorySize } = options;
    const secret = getUInt8Buffer((_a3 = options.secret) !== null && _a3 !== void 0 ? _a3 : "");
    const [argon2Interface, blake512] = yield Promise.all([
      WASMInterface(wasmJson$i, 1024),
      createBLAKE2b(512)
    ]);
    argon2Interface.setMemorySize(memorySize * 1024 + 1024);
    const initVector = new Uint8Array(24);
    const initVectorView = new DataView(initVector.buffer);
    initVectorView.setInt32(0, parallelism, true);
    initVectorView.setInt32(4, hashLength, true);
    initVectorView.setInt32(8, memorySize, true);
    initVectorView.setInt32(12, iterations, true);
    initVectorView.setInt32(16, version, true);
    initVectorView.setInt32(20, hashType, true);
    argon2Interface.writeMemory(initVector, memorySize * 1024);
    blake512.init();
    blake512.update(initVector);
    blake512.update(int32LE(password.length));
    blake512.update(password);
    blake512.update(int32LE(salt.length));
    blake512.update(salt);
    blake512.update(int32LE(secret.length));
    blake512.update(secret);
    blake512.update(int32LE(0));
    const segments = Math.floor(memorySize / (parallelism * 4));
    const lanes = segments * 4;
    const param = new Uint8Array(72);
    const H0 = blake512.digest("binary");
    param.set(H0);
    for (let lane = 0; lane < parallelism; lane++) {
      param.set(int32LE(0), 64);
      param.set(int32LE(lane), 68);
      let position = lane * lanes;
      let chunk = yield hashFunc(blake512, param, 1024);
      argon2Interface.writeMemory(chunk, position * 1024);
      position += 1;
      param.set(int32LE(1), 64);
      chunk = yield hashFunc(blake512, param, 1024);
      argon2Interface.writeMemory(chunk, position * 1024);
    }
    const C3 = new Uint8Array(1024);
    writeHexToUInt8(C3, argon2Interface.calculate(new Uint8Array([]), memorySize));
    const res = yield hashFunc(blake512, C3, hashLength);
    if (options.outputType === "hex") {
      const digestChars = new Uint8Array(hashLength * 2);
      return getDigestHex(digestChars, res, hashLength);
    }
    if (options.outputType === "encoded") {
      return encodeResult(salt, options, res);
    }
    return res;
  });
}
var validateOptions$3 = (options) => {
  var _a3;
  if (!options || typeof options !== "object") {
    throw new Error("Invalid options parameter. It requires an object.");
  }
  if (!options.password) {
    throw new Error("Password must be specified");
  }
  options.password = getUInt8Buffer(options.password);
  if (options.password.length < 1) {
    throw new Error("Password must be specified");
  }
  if (!options.salt) {
    throw new Error("Salt must be specified");
  }
  options.salt = getUInt8Buffer(options.salt);
  if (options.salt.length < 8) {
    throw new Error("Salt should be at least 8 bytes long");
  }
  options.secret = getUInt8Buffer((_a3 = options.secret) !== null && _a3 !== void 0 ? _a3 : "");
  if (!Number.isInteger(options.iterations) || options.iterations < 1) {
    throw new Error("Iterations should be a positive number");
  }
  if (!Number.isInteger(options.parallelism) || options.parallelism < 1) {
    throw new Error("Parallelism should be a positive number");
  }
  if (!Number.isInteger(options.hashLength) || options.hashLength < 4) {
    throw new Error("Hash length should be at least 4 bytes.");
  }
  if (!Number.isInteger(options.memorySize)) {
    throw new Error("Memory size should be specified.");
  }
  if (options.memorySize < 8 * options.parallelism) {
    throw new Error("Memory size should be at least 8 * parallelism.");
  }
  if (options.outputType === void 0) {
    options.outputType = "hex";
  }
  if (!["hex", "binary", "encoded"].includes(options.outputType)) {
    throw new Error(`Insupported output type ${options.outputType}. Valid values: ['hex', 'binary', 'encoded']`);
  }
};
function argon2id(options) {
  return __awaiter(this, void 0, void 0, function* () {
    validateOptions$3(options);
    return argon2Internal(Object.assign(Object.assign({}, options), { hashType: "id" }));
  });
}
var mutex$j = new Mutex();
var mutex$i = new Mutex();
var mutex$h = new Mutex();
var mutex$g = new Mutex();
var mutex$f = new Mutex();
var mutex$e = new Mutex();
var mutex$d = new Mutex();
var mutex$c = new Mutex();
var mutex$b = new Mutex();
var mutex$a = new Mutex();
var mutex$9 = new Mutex();
var mutex$8 = new Mutex();
var mutex$7 = new Mutex();
var mutex$6 = new Mutex();
var mutex$5 = new Mutex();
var seedBuffer$2 = new ArrayBuffer(8);
var mutex$4 = new Mutex();
var seedBuffer$1 = new ArrayBuffer(8);
var mutex$3 = new Mutex();
var seedBuffer = new ArrayBuffer(8);
var mutex$2 = new Mutex();
var mutex$1 = new Mutex();
var mutex = new Mutex();

// ../taler-util/lib/argon2-impl.wasm.js
async function HashArgon2idImpl(password, salt, iterations, memorySize, hashLength) {
  return await argon2id({
    password,
    salt,
    iterations,
    memorySize,
    hashLength,
    parallelism: 1,
    outputType: "binary"
  });
}

// ../taler-util/lib/argon2.js
async function hashArgon2id(password, salt, iterations, memorySize, hashLength) {
  return await HashArgon2idImpl(password, salt, iterations, memorySize, hashLength);
}

// ../taler-util/lib/sha256.js
var digestLength = 32;
var blockSize = 64;
var K2 = new Uint32Array([
  1116352408,
  1899447441,
  3049323471,
  3921009573,
  961987163,
  1508970993,
  2453635748,
  2870763221,
  3624381080,
  310598401,
  607225278,
  1426881987,
  1925078388,
  2162078206,
  2614888103,
  3248222580,
  3835390401,
  4022224774,
  264347078,
  604807628,
  770255983,
  1249150122,
  1555081692,
  1996064986,
  2554220882,
  2821834349,
  2952996808,
  3210313671,
  3336571891,
  3584528711,
  113926993,
  338241895,
  666307205,
  773529912,
  1294757372,
  1396182291,
  1695183700,
  1986661051,
  2177026350,
  2456956037,
  2730485921,
  2820302411,
  3259730800,
  3345764771,
  3516065817,
  3600352804,
  4094571909,
  275423344,
  430227734,
  506948616,
  659060556,
  883997877,
  958139571,
  1322822218,
  1537002063,
  1747873779,
  1955562222,
  2024104815,
  2227730452,
  2361852424,
  2428436474,
  2756734187,
  3204031479,
  3329325298
]);
function hashBlocks(w4, v4, p5, pos, len) {
  let a4, b4, c4, d4, e4, f4, g4, h4, u4, i4, j4, t1, t22;
  while (len >= 64) {
    a4 = v4[0];
    b4 = v4[1];
    c4 = v4[2];
    d4 = v4[3];
    e4 = v4[4];
    f4 = v4[5];
    g4 = v4[6];
    h4 = v4[7];
    for (i4 = 0; i4 < 16; i4++) {
      j4 = pos + i4 * 4;
      w4[i4] = (p5[j4] & 255) << 24 | (p5[j4 + 1] & 255) << 16 | (p5[j4 + 2] & 255) << 8 | p5[j4 + 3] & 255;
    }
    for (i4 = 16; i4 < 64; i4++) {
      u4 = w4[i4 - 2];
      t1 = (u4 >>> 17 | u4 << 32 - 17) ^ (u4 >>> 19 | u4 << 32 - 19) ^ u4 >>> 10;
      u4 = w4[i4 - 15];
      t22 = (u4 >>> 7 | u4 << 32 - 7) ^ (u4 >>> 18 | u4 << 32 - 18) ^ u4 >>> 3;
      w4[i4] = (t1 + w4[i4 - 7] | 0) + (t22 + w4[i4 - 16] | 0);
    }
    for (i4 = 0; i4 < 64; i4++) {
      t1 = (((e4 >>> 6 | e4 << 32 - 6) ^ (e4 >>> 11 | e4 << 32 - 11) ^ (e4 >>> 25 | e4 << 32 - 25)) + (e4 & f4 ^ ~e4 & g4) | 0) + (h4 + (K2[i4] + w4[i4] | 0) | 0) | 0;
      t22 = ((a4 >>> 2 | a4 << 32 - 2) ^ (a4 >>> 13 | a4 << 32 - 13) ^ (a4 >>> 22 | a4 << 32 - 22)) + (a4 & b4 ^ a4 & c4 ^ b4 & c4) | 0;
      h4 = g4;
      g4 = f4;
      f4 = e4;
      e4 = d4 + t1 | 0;
      d4 = c4;
      c4 = b4;
      b4 = a4;
      a4 = t1 + t22 | 0;
    }
    v4[0] += a4;
    v4[1] += b4;
    v4[2] += c4;
    v4[3] += d4;
    v4[4] += e4;
    v4[5] += f4;
    v4[6] += g4;
    v4[7] += h4;
    pos += 64;
    len -= 64;
  }
  return pos;
}
var HashSha256 = class {
  constructor() {
    this.digestLength = digestLength;
    this.blockSize = blockSize;
    this.state = new Int32Array(8);
    this.temp = new Int32Array(64);
    this.buffer = new Uint8Array(128);
    this.bufferLength = 0;
    this.bytesHashed = 0;
    this.finished = false;
    this.reset();
  }
  // Resets hash state making it possible
  // to reuse this instance to hash other data.
  reset() {
    this.state[0] = 1779033703;
    this.state[1] = 3144134277;
    this.state[2] = 1013904242;
    this.state[3] = 2773480762;
    this.state[4] = 1359893119;
    this.state[5] = 2600822924;
    this.state[6] = 528734635;
    this.state[7] = 1541459225;
    this.bufferLength = 0;
    this.bytesHashed = 0;
    this.finished = false;
    return this;
  }
  // Cleans internal buffers and re-initializes hash state.
  clean() {
    for (let i4 = 0; i4 < this.buffer.length; i4++) {
      this.buffer[i4] = 0;
    }
    for (let i4 = 0; i4 < this.temp.length; i4++) {
      this.temp[i4] = 0;
    }
    this.reset();
  }
  // Updates hash state with the given data.
  //
  // Optionally, length of the data can be specified to hash
  // fewer bytes than data.length.
  //
  // Throws error when trying to update already finalized hash:
  // instance must be reset to use it again.
  update(data, dataLength = data.length) {
    if (this.finished) {
      throw new Error("SHA256: can't update because hash was finished.");
    }
    let dataPos = 0;
    this.bytesHashed += dataLength;
    if (this.bufferLength > 0) {
      while (this.bufferLength < 64 && dataLength > 0) {
        this.buffer[this.bufferLength++] = data[dataPos++];
        dataLength--;
      }
      if (this.bufferLength === 64) {
        hashBlocks(this.temp, this.state, this.buffer, 0, 64);
        this.bufferLength = 0;
      }
    }
    if (dataLength >= 64) {
      dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength);
      dataLength %= 64;
    }
    while (dataLength > 0) {
      this.buffer[this.bufferLength++] = data[dataPos++];
      dataLength--;
    }
    return this;
  }
  // Finalizes hash state and puts hash into out.
  //
  // If hash was already finalized, puts the same value.
  finish(out) {
    if (!this.finished) {
      const bytesHashed = this.bytesHashed;
      const left = this.bufferLength;
      const bitLenHi = bytesHashed / 536870912 | 0;
      const bitLenLo = bytesHashed << 3;
      const padLength = bytesHashed % 64 < 56 ? 64 : 128;
      this.buffer[left] = 128;
      for (let i4 = left + 1; i4 < padLength - 8; i4++) {
        this.buffer[i4] = 0;
      }
      this.buffer[padLength - 8] = bitLenHi >>> 24 & 255;
      this.buffer[padLength - 7] = bitLenHi >>> 16 & 255;
      this.buffer[padLength - 6] = bitLenHi >>> 8 & 255;
      this.buffer[padLength - 5] = bitLenHi >>> 0 & 255;
      this.buffer[padLength - 4] = bitLenLo >>> 24 & 255;
      this.buffer[padLength - 3] = bitLenLo >>> 16 & 255;
      this.buffer[padLength - 2] = bitLenLo >>> 8 & 255;
      this.buffer[padLength - 1] = bitLenLo >>> 0 & 255;
      hashBlocks(this.temp, this.state, this.buffer, 0, padLength);
      this.finished = true;
    }
    for (let i4 = 0; i4 < 8; i4++) {
      out[i4 * 4 + 0] = this.state[i4] >>> 24 & 255;
      out[i4 * 4 + 1] = this.state[i4] >>> 16 & 255;
      out[i4 * 4 + 2] = this.state[i4] >>> 8 & 255;
      out[i4 * 4 + 3] = this.state[i4] >>> 0 & 255;
    }
    return this;
  }
  // Returns the final hash digest.
  digest() {
    const out = new Uint8Array(this.digestLength);
    this.finish(out);
    return out;
  }
  // Internal function for use in HMAC for optimization.
  _saveState(out) {
    for (let i4 = 0; i4 < this.state.length; i4++) {
      out[i4] = this.state[i4];
    }
  }
  // Internal function for use in HMAC for optimization.
  _restoreState(from, bytesHashed) {
    for (let i4 = 0; i4 < this.state.length; i4++) {
      this.state[i4] = from[i4];
    }
    this.bytesHashed = bytesHashed;
    this.finished = false;
    this.bufferLength = 0;
  }
};
function sha256(data) {
  const h4 = new HashSha256().update(data);
  const digest = h4.digest();
  h4.clean();
  return digest;
}

// ../taler-util/lib/kdf.js
function sha512(data) {
  return hash(data);
}
function hmac(digest, blockSize2, key, message) {
  if (key.byteLength > blockSize2) {
    key = digest(key);
  }
  if (key.byteLength < blockSize2) {
    const k4 = key;
    key = new Uint8Array(blockSize2);
    key.set(k4, 0);
  }
  const okp = new Uint8Array(blockSize2);
  const ikp = new Uint8Array(blockSize2);
  for (let i4 = 0; i4 < blockSize2; i4++) {
    ikp[i4] = key[i4] ^ 54;
    okp[i4] = key[i4] ^ 92;
  }
  const b1 = new Uint8Array(blockSize2 + message.byteLength);
  b1.set(ikp, 0);
  b1.set(message, blockSize2);
  const h0 = digest(b1);
  const b22 = new Uint8Array(blockSize2 + h0.length);
  b22.set(okp, 0);
  b22.set(h0, blockSize2);
  return digest(b22);
}
function hmacSha512(key, message) {
  return hmac(sha512, 128, key, message);
}
function hmacSha256(key, message) {
  return hmac(sha256, 64, key, message);
}

// ../taler-util/lib/time.js
var opaque_AbsoluteTime = Symbol("opaque_AbsoluteTime");
var TalerPreciseTimestamp;
(function(TalerPreciseTimestamp2) {
  function now2() {
    const absNow = AbsoluteTime.now();
    return AbsoluteTime.toPreciseTimestamp(absNow);
  }
  TalerPreciseTimestamp2.now = now2;
  function round(t4) {
    return {
      t_s: t4.t_s
    };
  }
  TalerPreciseTimestamp2.round = round;
  function fromSeconds(s4) {
    return {
      t_s: Math.floor(s4),
      off_us: Math.floor((s4 - Math.floor(s4)) / 1e3 / 1e3)
    };
  }
  TalerPreciseTimestamp2.fromSeconds = fromSeconds;
  function fromMilliseconds(ms) {
    return {
      t_s: Math.floor(ms / 1e3),
      off_us: Math.floor((ms - Math.floor(ms / 1e3) * 1e3) * 1e3)
    };
  }
  TalerPreciseTimestamp2.fromMilliseconds = fromMilliseconds;
})(TalerPreciseTimestamp || (TalerPreciseTimestamp = {}));
var TalerProtocolTimestamp;
(function(TalerProtocolTimestamp2) {
  function now2() {
    return AbsoluteTime.toProtocolTimestamp(AbsoluteTime.now());
  }
  TalerProtocolTimestamp2.now = now2;
  function zero() {
    return {
      t_s: 0
    };
  }
  TalerProtocolTimestamp2.zero = zero;
  function never() {
    return {
      t_s: "never"
    };
  }
  TalerProtocolTimestamp2.never = never;
  function isNever(t4) {
    return t4.t_s === "never";
  }
  TalerProtocolTimestamp2.isNever = isNever;
  function fromSeconds(s4) {
    return {
      t_s: s4
    };
  }
  TalerProtocolTimestamp2.fromSeconds = fromSeconds;
  function min(t1, t22) {
    if (t1.t_s === "never") {
      return { t_s: t22.t_s };
    }
    if (t22.t_s === "never") {
      return { t_s: t1.t_s };
    }
    return { t_s: Math.min(t1.t_s, t22.t_s) };
  }
  TalerProtocolTimestamp2.min = min;
  function max2(t1, t22) {
    if (t1.t_s === "never" || t22.t_s === "never") {
      return { t_s: "never" };
    }
    return { t_s: Math.max(t1.t_s, t22.t_s) };
  }
  TalerProtocolTimestamp2.max = max2;
})(TalerProtocolTimestamp || (TalerProtocolTimestamp = {}));
var timeshift = 0;
var Duration;
(function(Duration2) {
  function toMilliseconds(d4) {
    if (d4.d_ms === "forever") {
      return Number.MAX_VALUE;
    }
    return d4.d_ms;
  }
  Duration2.toMilliseconds = toMilliseconds;
  function getRemaining(deadline, now2 = AbsoluteTime.now()) {
    if (deadline.t_ms === "never") {
      return { d_ms: "forever" };
    }
    if (now2.t_ms === "never") {
      throw Error("invalid argument for 'now'");
    }
    if (deadline.t_ms < now2.t_ms) {
      return { d_ms: 0 };
    }
    return { d_ms: deadline.t_ms - now2.t_ms };
  }
  Duration2.getRemaining = getRemaining;
  function fromPrettyString(s4) {
    let dMs = 0;
    let currentNum = "";
    let parsingNum = true;
    for (let i4 = 0; i4 < s4.length; i4++) {
      const cc = s4.charCodeAt(i4);
      if (cc >= "0".charCodeAt(0) && cc <= "9".charCodeAt(0)) {
        if (!parsingNum) {
          throw Error("invalid duration, unexpected number");
        }
        currentNum += s4[i4];
        continue;
      }
      if (s4[i4] == " ") {
        if (currentNum != "") {
          parsingNum = false;
        }
        continue;
      }
      if (currentNum == "") {
        throw Error("invalid duration, missing number");
      }
      if (s4[i4] === "s") {
        dMs += 1e3 * Number.parseInt(currentNum, 10);
      } else if (s4[i4] === "m") {
        dMs += 60 * 1e3 * Number.parseInt(currentNum, 10);
      } else if (s4[i4] === "h") {
        dMs += 60 * 60 * 1e3 * Number.parseInt(currentNum, 10);
      } else if (s4[i4] === "d") {
        dMs += 24 * 60 * 60 * 1e3 * Number.parseInt(currentNum, 10);
      } else {
        throw Error("invalid duration, unsupported unit");
      }
      currentNum = "";
      parsingNum = true;
    }
    return {
      d_ms: dMs
    };
  }
  Duration2.fromPrettyString = fromPrettyString;
  function cmp(d1, d22) {
    if (d1.d_ms === "forever") {
      if (d22.d_ms === "forever") {
        return 0;
      }
      return 1;
    }
    if (d22.d_ms === "forever") {
      return -1;
    }
    if (d1.d_ms == d22.d_ms) {
      return 0;
    }
    if (d1.d_ms > d22.d_ms) {
      return 1;
    }
    return -1;
  }
  Duration2.cmp = cmp;
  function max2(d1, d22) {
    return durationMax(d1, d22);
  }
  Duration2.max = max2;
  function min(d1, d22) {
    return durationMin(d1, d22);
  }
  Duration2.min = min;
  function multiply(d1, n3) {
    return durationMul(d1, n3);
  }
  Duration2.multiply = multiply;
  function toIntegerYears(d4) {
    if (typeof d4.d_ms !== "number") {
      throw Error("infinite duration");
    }
    return Math.ceil(d4.d_ms / 1e3 / 60 / 60 / 24 / 365);
  }
  Duration2.toIntegerYears = toIntegerYears;
  function fromSpec(spec) {
    let d_ms = 0;
    d_ms += (spec.seconds ?? 0) * SECONDS;
    d_ms += (spec.minutes ?? 0) * MINUTES;
    d_ms += (spec.hours ?? 0) * HOURS;
    d_ms += (spec.days ?? 0) * DAYS;
    d_ms += (spec.months ?? 0) * MONTHS;
    d_ms += (spec.years ?? 0) * YEARS;
    return { d_ms };
  }
  Duration2.fromSpec = fromSpec;
  function getForever() {
    return { d_ms: "forever" };
  }
  Duration2.getForever = getForever;
  function getZero() {
    return { d_ms: 0 };
  }
  Duration2.getZero = getZero;
  function fromTalerProtocolDuration(d4) {
    if (d4.d_us === "forever") {
      return {
        d_ms: "forever"
      };
    }
    return {
      d_ms: Math.floor(d4.d_us / 1e3)
    };
  }
  Duration2.fromTalerProtocolDuration = fromTalerProtocolDuration;
  function toTalerProtocolDuration(d4) {
    if (d4.d_ms === "forever") {
      return {
        d_us: "forever"
      };
    }
    return {
      d_us: d4.d_ms * 1e3
    };
  }
  Duration2.toTalerProtocolDuration = toTalerProtocolDuration;
  function fromMilliseconds(ms) {
    return {
      d_ms: ms
    };
  }
  Duration2.fromMilliseconds = fromMilliseconds;
  function clamp(args) {
    return durationMax(durationMin(args.value, args.upper), args.lower);
  }
  Duration2.clamp = clamp;
})(Duration || (Duration = {}));
var AbsoluteTime;
(function(AbsoluteTime2) {
  function getStampMsNow() {
    return (/* @__PURE__ */ new Date()).getTime();
  }
  AbsoluteTime2.getStampMsNow = getStampMsNow;
  function getStampMsNever() {
    return Number.MAX_SAFE_INTEGER;
  }
  AbsoluteTime2.getStampMsNever = getStampMsNever;
  function now2() {
    return {
      t_ms: (/* @__PURE__ */ new Date()).getTime() + timeshift,
      [opaque_AbsoluteTime]: true
    };
  }
  AbsoluteTime2.now = now2;
  function never() {
    return {
      t_ms: "never",
      [opaque_AbsoluteTime]: true
    };
  }
  AbsoluteTime2.never = never;
  function fromMilliseconds(ms) {
    return {
      t_ms: ms,
      [opaque_AbsoluteTime]: true
    };
  }
  AbsoluteTime2.fromMilliseconds = fromMilliseconds;
  function cmp(t1, t22) {
    if (t1.t_ms === "never") {
      if (t22.t_ms === "never") {
        return 0;
      }
      return 1;
    }
    if (t22.t_ms === "never") {
      return -1;
    }
    if (t1.t_ms == t22.t_ms) {
      return 0;
    }
    if (t1.t_ms > t22.t_ms) {
      return 1;
    }
    return -1;
  }
  AbsoluteTime2.cmp = cmp;
  function min(t1, t22) {
    if (t1.t_ms === "never") {
      return { t_ms: t22.t_ms, [opaque_AbsoluteTime]: true };
    }
    if (t22.t_ms === "never") {
      return { t_ms: t22.t_ms, [opaque_AbsoluteTime]: true };
    }
    return { t_ms: Math.min(t1.t_ms, t22.t_ms), [opaque_AbsoluteTime]: true };
  }
  AbsoluteTime2.min = min;
  function max2(t1, t22) {
    if (t1.t_ms === "never") {
      return { t_ms: "never", [opaque_AbsoluteTime]: true };
    }
    if (t22.t_ms === "never") {
      return { t_ms: "never", [opaque_AbsoluteTime]: true };
    }
    return { t_ms: Math.max(t1.t_ms, t22.t_ms), [opaque_AbsoluteTime]: true };
  }
  AbsoluteTime2.max = max2;
  function difference(t1, t22) {
    if (t1.t_ms === "never") {
      return { d_ms: "forever" };
    }
    if (t22.t_ms === "never") {
      return { d_ms: "forever" };
    }
    return { d_ms: Math.abs(t1.t_ms - t22.t_ms) };
  }
  AbsoluteTime2.difference = difference;
  function isExpired(t4) {
    return cmp(t4, now2()) <= 0;
  }
  AbsoluteTime2.isExpired = isExpired;
  function isNever(t4) {
    return t4.t_ms === "never";
  }
  AbsoluteTime2.isNever = isNever;
  function fromProtocolTimestamp(t4) {
    if (t4.t_s === "never") {
      return { t_ms: "never", [opaque_AbsoluteTime]: true };
    }
    return {
      t_ms: t4.t_s * 1e3,
      [opaque_AbsoluteTime]: true
    };
  }
  AbsoluteTime2.fromProtocolTimestamp = fromProtocolTimestamp;
  function fromStampMs(stampMs) {
    return {
      t_ms: stampMs,
      [opaque_AbsoluteTime]: true
    };
  }
  AbsoluteTime2.fromStampMs = fromStampMs;
  function fromPreciseTimestamp(t4) {
    if (t4.t_s === "never") {
      return { t_ms: "never", [opaque_AbsoluteTime]: true };
    }
    const offsetUs = t4.off_us ?? 0;
    return {
      t_ms: t4.t_s * 1e3 + Math.floor(offsetUs / 1e3),
      [opaque_AbsoluteTime]: true
    };
  }
  AbsoluteTime2.fromPreciseTimestamp = fromPreciseTimestamp;
  function toStampMs(at2) {
    if (at2.t_ms === "never") {
      return Number.MAX_SAFE_INTEGER;
    }
    return at2.t_ms;
  }
  AbsoluteTime2.toStampMs = toStampMs;
  function toPreciseTimestamp(at2) {
    if (at2.t_ms == "never") {
      return {
        t_s: "never"
      };
    }
    const t_s = Math.floor(at2.t_ms / 1e3);
    const off_us = Math.floor(1e3 * (at2.t_ms - t_s * 1e3));
    return {
      t_s,
      off_us
    };
  }
  AbsoluteTime2.toPreciseTimestamp = toPreciseTimestamp;
  function toProtocolTimestamp(at2) {
    if (at2.t_ms === "never") {
      return { t_s: "never" };
    }
    return {
      t_s: Math.floor(at2.t_ms / 1e3)
    };
  }
  AbsoluteTime2.toProtocolTimestamp = toProtocolTimestamp;
  function isBetween(t4, start, end) {
    if (cmp(t4, start) < 0) {
      return false;
    }
    if (cmp(t4, end) > 0) {
      return false;
    }
    return true;
  }
  AbsoluteTime2.isBetween = isBetween;
  function toIsoString(t4) {
    if (t4.t_ms === "never") {
      return "<never>";
    } else {
      return new Date(t4.t_ms).toISOString();
    }
  }
  AbsoluteTime2.toIsoString = toIsoString;
  function addDuration(t1, d4) {
    if (t1.t_ms === "never" || d4.d_ms === "forever") {
      return { t_ms: "never", [opaque_AbsoluteTime]: true };
    }
    return { t_ms: t1.t_ms + d4.d_ms, [opaque_AbsoluteTime]: true };
  }
  AbsoluteTime2.addDuration = addDuration;
  function remaining(t1) {
    if (t1.t_ms === "never") {
      return Duration.getForever();
    }
    const stampNow = now2();
    if (stampNow.t_ms === "never") {
      throw Error("invariant violated");
    }
    return Duration.fromMilliseconds(Math.max(0, t1.t_ms - stampNow.t_ms));
  }
  AbsoluteTime2.remaining = remaining;
  function subtractDuraction(t1, d4) {
    if (t1.t_ms === "never") {
      return { t_ms: "never", [opaque_AbsoluteTime]: true };
    }
    if (d4.d_ms === "forever") {
      return { t_ms: 0, [opaque_AbsoluteTime]: true };
    }
    return { t_ms: Math.max(0, t1.t_ms - d4.d_ms), [opaque_AbsoluteTime]: true };
  }
  AbsoluteTime2.subtractDuraction = subtractDuraction;
  function stringify(t4) {
    if (t4.t_ms === "never") {
      return "never";
    }
    return new Date(t4.t_ms).toISOString();
  }
  AbsoluteTime2.stringify = stringify;
})(AbsoluteTime || (AbsoluteTime = {}));
var SECONDS = 1e3;
var MINUTES = SECONDS * 60;
var HOURS = MINUTES * 60;
var DAYS = HOURS * 24;
var MONTHS = DAYS * 30;
var YEARS = DAYS * 365;
function durationMin(d1, d22) {
  if (d1.d_ms === "forever") {
    return { d_ms: d22.d_ms };
  }
  if (d22.d_ms === "forever") {
    return { d_ms: d1.d_ms };
  }
  return { d_ms: Math.min(d1.d_ms, d22.d_ms) };
}
function durationMax(d1, d22) {
  if (d1.d_ms === "forever") {
    return { d_ms: "forever" };
  }
  if (d22.d_ms === "forever") {
    return { d_ms: "forever" };
  }
  return { d_ms: Math.max(d1.d_ms, d22.d_ms) };
}
function durationMul(d4, n3) {
  if (d4.d_ms === "forever") {
    return { d_ms: "forever" };
  }
  return { d_ms: Math.round(d4.d_ms * n3) };
}
var codecForAbsoluteTime = {
  decode(x3, c4) {
    if (x3 === void 0) {
      throw Error(`got undefined and expected absolute time at ${renderContext(c4)}`);
    }
    const t_ms = x3.t_ms;
    if (typeof t_ms === "string") {
      if (t_ms === "never") {
        return { t_ms: "never", [opaque_AbsoluteTime]: true };
      }
    } else if (typeof t_ms === "number") {
      return { t_ms, [opaque_AbsoluteTime]: true };
    }
    throw Error(`expected timestamp at ${renderContext(c4)}`);
  }
};
var codecForTimestamp = {
  decode(x3, c4) {
    if (x3 === void 0) {
      throw Error(`got undefined and expected timestamp at ${renderContext(c4)}`);
    }
    const t_ms = x3.t_ms;
    if (typeof t_ms === "string") {
      if (t_ms === "never") {
        return { t_s: "never" };
      }
    } else if (typeof t_ms === "number") {
      return { t_s: Math.floor(t_ms / 1e3) };
    }
    const t_s = x3.t_s;
    if (typeof t_s === "string") {
      if (t_s === "never") {
        return { t_s: "never" };
      }
      throw Error(`expected timestamp at ${renderContext(c4)}`);
    }
    if (typeof t_s === "number") {
      return { t_s };
    }
    throw Error(`expected protocol timestamp at ${renderContext(c4)}`);
  }
};

// ../taler-util/lib/taler-types.js
var DenomKeyType;
(function(DenomKeyType2) {
  DenomKeyType2["Rsa"] = "RSA";
  DenomKeyType2["ClauseSchnorr"] = "CS";
})(DenomKeyType || (DenomKeyType = {}));
(function(DenomKeyType2) {
  function toIntTag(t4) {
    switch (t4) {
      case DenomKeyType2.Rsa:
        return 1;
      case DenomKeyType2.ClauseSchnorr:
        return 2;
    }
  }
  DenomKeyType2.toIntTag = toIntTag;
})(DenomKeyType || (DenomKeyType = {}));
var DenominationPubKey;
(function(DenominationPubKey2) {
  function cmp(p1, p22) {
    if (p1.cipher < p22.cipher) {
      return -1;
    } else if (p1.cipher > p22.cipher) {
      return 1;
    } else if (p1.cipher === DenomKeyType.Rsa && p22.cipher === DenomKeyType.Rsa) {
      if ((p1.age_mask ?? 0) < (p22.age_mask ?? 0)) {
        return -1;
      } else if ((p1.age_mask ?? 0) > (p22.age_mask ?? 0)) {
        return 1;
      }
      return strcmp(p1.rsa_public_key, p22.rsa_public_key);
    } else if (p1.cipher === DenomKeyType.ClauseSchnorr && p22.cipher === DenomKeyType.ClauseSchnorr) {
      if ((p1.age_mask ?? 0) < (p22.age_mask ?? 0)) {
        return -1;
      } else if ((p1.age_mask ?? 0) > (p22.age_mask ?? 0)) {
        return 1;
      }
      return strcmp(p1.cs_public_key, p22.cs_public_key);
    } else {
      throw Error("unsupported cipher");
    }
  }
  DenominationPubKey2.cmp = cmp;
})(DenominationPubKey || (DenominationPubKey = {}));
var codecForNgDenominations = codecForAny();
var ExchangeProtocolVersion;
(function(ExchangeProtocolVersion2) {
  ExchangeProtocolVersion2[ExchangeProtocolVersion2["V12"] = 12] = "V12";
})(ExchangeProtocolVersion || (ExchangeProtocolVersion = {}));
var MerchantProtocolVersion;
(function(MerchantProtocolVersion2) {
  MerchantProtocolVersion2[MerchantProtocolVersion2["V3"] = 3] = "V3";
})(MerchantProtocolVersion || (MerchantProtocolVersion = {}));

// ../taler-util/lib/taler-crypto.js
function getRandomBytes(n3) {
  return randomBytes(n3);
}
var useNative = true;
var tart;
if (useNative) {
  tart = globalThis._tart;
}
var encTable = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
var EncodingError = class _EncodingError extends Error {
  constructor() {
    super("Encoding error");
    Object.setPrototypeOf(this, _EncodingError.prototype);
  }
};
function getValue(chr) {
  let a4 = chr;
  switch (chr) {
    case "O":
    case "o":
      a4 = "0";
      break;
    case "i":
    case "I":
    case "l":
    case "L":
      a4 = "1";
      break;
    case "u":
    case "U":
      a4 = "V";
  }
  if (a4 >= "0" && a4 <= "9") {
    return a4.charCodeAt(0) - "0".charCodeAt(0);
  }
  if (a4 >= "a" && a4 <= "z")
    a4 = a4.toUpperCase();
  let dec = 0;
  if (a4 >= "A" && a4 <= "Z") {
    if ("I" < a4)
      dec++;
    if ("L" < a4)
      dec++;
    if ("O" < a4)
      dec++;
    if ("U" < a4)
      dec++;
    return a4.charCodeAt(0) - "A".charCodeAt(0) + 10 - dec;
  }
  throw new EncodingError();
}
function encodeCrock(data) {
  if (tart) {
    return tart.encodeCrock(data);
  }
  const dataBytes = new Uint8Array(data);
  let sb = "";
  const size = data.byteLength;
  let bitBuf = 0;
  let numBits = 0;
  let pos = 0;
  while (pos < size || numBits > 0) {
    if (pos < size && numBits < 5) {
      const d4 = dataBytes[pos++];
      bitBuf = bitBuf << 8 | d4;
      numBits += 8;
    }
    if (numBits < 5) {
      bitBuf = bitBuf << 5 - numBits;
      numBits = 5;
    }
    const v4 = bitBuf >>> numBits - 5 & 31;
    sb += encTable[v4];
    numBits -= 5;
  }
  return sb;
}
function kdf(outputLength, ikm, salt, info) {
  if (tart) {
    return tart.kdf(outputLength, ikm, salt, info);
  }
  salt = salt ?? new Uint8Array(64);
  const prk = hmacSha512(salt, ikm);
  info = info ?? new Uint8Array(0);
  const N3 = Math.ceil(outputLength / 32);
  const output = new Uint8Array(N3 * 32);
  for (let i4 = 0; i4 < N3; i4++) {
    let buf;
    if (i4 == 0) {
      buf = new Uint8Array(info.byteLength + 1);
      buf.set(info, 0);
    } else {
      buf = new Uint8Array(info.byteLength + 1 + 32);
      for (let j4 = 0; j4 < 32; j4++) {
        buf[j4] = output[(i4 - 1) * 32 + j4];
      }
      buf.set(info, 32);
    }
    buf[buf.length - 1] = i4 + 1;
    const chunk = hmacSha256(prk, buf);
    output.set(chunk, i4 * 32);
  }
  return output.slice(0, outputLength);
}
function kdfKw(args) {
  return kdf(args.outputLength, args.ikm, args.salt, args.info);
}
function decodeCrock(encoded) {
  if (tart) {
    return tart.decodeCrock(encoded);
  }
  const size = encoded.length;
  let bitpos = 0;
  let bitbuf = 0;
  let readPosition = 0;
  const outLen = Math.floor(size * 5 / 8);
  const out = new Uint8Array(outLen);
  let outPos = 0;
  while (readPosition < size || bitpos > 0) {
    if (readPosition < size) {
      const v4 = getValue(encoded[readPosition++]);
      bitbuf = bitbuf << 5 | v4;
      bitpos += 5;
    }
    while (bitpos >= 8) {
      const d4 = bitbuf >>> bitpos - 8 & 255;
      out[outPos++] = d4;
      bitpos -= 8;
    }
    if (readPosition == size && bitpos > 0) {
      bitbuf = bitbuf << 8 - bitpos & 255;
      bitpos = bitbuf == 0 ? 0 : 8;
    }
  }
  return out;
}
async function hashArgon2id2(password, salt, iterations, memorySize, hashLength) {
  if (tart) {
    return tart.hashArgon2id(password, salt, iterations, memorySize, hashLength);
  }
  return await hashArgon2id(password, salt, iterations, memorySize, hashLength);
}
var encoder;
var decoder;
function stringToBytes(s4) {
  if (!encoder) {
    encoder = new TextEncoder();
  }
  return encoder.encode(s4);
}
function bytesToString(b4) {
  if (!decoder) {
    decoder = new TextDecoder();
  }
  return decoder.decode(b4);
}
function typedArrayConcat(chunks) {
  let payloadLen = 0;
  for (const c4 of chunks) {
    payloadLen += c4.byteLength;
  }
  const buf = new ArrayBuffer(payloadLen);
  const u8buf = new Uint8Array(buf);
  let p5 = 0;
  for (const c4 of chunks) {
    u8buf.set(c4, p5);
    p5 += c4.byteLength;
  }
  return u8buf;
}
function hash2(d4) {
  if (tart) {
    return tart.hash(d4);
  }
  return hash(d4);
}
var logger2 = new Logger("talerCrypto.ts");
function eddsaSign(msg, eddsaPriv) {
  if (tart) {
    return tart.eddsaSign(msg, eddsaPriv);
  }
  const pair = crypto_sign_keyPair_fromSeed(eddsaPriv);
  return sign_detached(msg, pair.secretKey);
}
function bufferForUint32(n3) {
  const arrBuf = new ArrayBuffer(4);
  const buf = new Uint8Array(arrBuf);
  const dv = new DataView(arrBuf);
  dv.setUint32(0, n3);
  return buf;
}
var TalerSignaturePurpose;
(function(TalerSignaturePurpose2) {
  TalerSignaturePurpose2[TalerSignaturePurpose2["MERCHANT_TRACK_TRANSACTION"] = 1103] = "MERCHANT_TRACK_TRANSACTION";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_RESERVE_WITHDRAW"] = 1200] = "WALLET_RESERVE_WITHDRAW";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_RESERVE_HISTORY"] = 1208] = "WALLET_RESERVE_HISTORY";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_COIN_DEPOSIT"] = 1201] = "WALLET_COIN_DEPOSIT";
  TalerSignaturePurpose2[TalerSignaturePurpose2["GLOBAL_FEES"] = 1022] = "GLOBAL_FEES";
  TalerSignaturePurpose2[TalerSignaturePurpose2["MASTER_DENOMINATION_KEY_VALIDITY"] = 1025] = "MASTER_DENOMINATION_KEY_VALIDITY";
  TalerSignaturePurpose2[TalerSignaturePurpose2["MASTER_WIRE_FEES"] = 1028] = "MASTER_WIRE_FEES";
  TalerSignaturePurpose2[TalerSignaturePurpose2["MASTER_WIRE_DETAILS"] = 1030] = "MASTER_WIRE_DETAILS";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_COIN_MELT"] = 1202] = "WALLET_COIN_MELT";
  TalerSignaturePurpose2[TalerSignaturePurpose2["TEST"] = 4242] = "TEST";
  TalerSignaturePurpose2[TalerSignaturePurpose2["MERCHANT_PAYMENT_OK"] = 1104] = "MERCHANT_PAYMENT_OK";
  TalerSignaturePurpose2[TalerSignaturePurpose2["MERCHANT_CONTRACT"] = 1101] = "MERCHANT_CONTRACT";
  TalerSignaturePurpose2[TalerSignaturePurpose2["MERCHANT_REFUND"] = 1102] = "MERCHANT_REFUND";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_COIN_RECOUP"] = 1203] = "WALLET_COIN_RECOUP";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_COIN_LINK"] = 1204] = "WALLET_COIN_LINK";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_COIN_RECOUP_REFRESH"] = 1206] = "WALLET_COIN_RECOUP_REFRESH";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_AGE_ATTESTATION"] = 1207] = "WALLET_AGE_ATTESTATION";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_PURSE_CREATE"] = 1210] = "WALLET_PURSE_CREATE";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_PURSE_DEPOSIT"] = 1211] = "WALLET_PURSE_DEPOSIT";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_PURSE_MERGE"] = 1213] = "WALLET_PURSE_MERGE";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_ACCOUNT_MERGE"] = 1214] = "WALLET_ACCOUNT_MERGE";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_PURSE_ECONTRACT"] = 1216] = "WALLET_PURSE_ECONTRACT";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_PURSE_DELETE"] = 1220] = "WALLET_PURSE_DELETE";
  TalerSignaturePurpose2[TalerSignaturePurpose2["WALLET_COIN_HISTORY"] = 1209] = "WALLET_COIN_HISTORY";
  TalerSignaturePurpose2[TalerSignaturePurpose2["EXCHANGE_CONFIRM_RECOUP"] = 1039] = "EXCHANGE_CONFIRM_RECOUP";
  TalerSignaturePurpose2[TalerSignaturePurpose2["EXCHANGE_CONFIRM_RECOUP_REFRESH"] = 1041] = "EXCHANGE_CONFIRM_RECOUP_REFRESH";
  TalerSignaturePurpose2[TalerSignaturePurpose2["TALER_SIGNATURE_AML_DECISION"] = 1350] = "TALER_SIGNATURE_AML_DECISION";
  TalerSignaturePurpose2[TalerSignaturePurpose2["TALER_SIGNATURE_AML_QUERY"] = 1351] = "TALER_SIGNATURE_AML_QUERY";
  TalerSignaturePurpose2[TalerSignaturePurpose2["TALER_SIGNATURE_MASTER_AML_KEY"] = 1017] = "TALER_SIGNATURE_MASTER_AML_KEY";
  TalerSignaturePurpose2[TalerSignaturePurpose2["ANASTASIS_POLICY_UPLOAD"] = 1400] = "ANASTASIS_POLICY_UPLOAD";
  TalerSignaturePurpose2[TalerSignaturePurpose2["ANASTASIS_POLICY_DOWNLOAD"] = 1401] = "ANASTASIS_POLICY_DOWNLOAD";
  TalerSignaturePurpose2[TalerSignaturePurpose2["SYNC_BACKUP_UPLOAD"] = 1450] = "SYNC_BACKUP_UPLOAD";
})(TalerSignaturePurpose || (TalerSignaturePurpose = {}));
var WalletAccountMergeFlags;
(function(WalletAccountMergeFlags2) {
  WalletAccountMergeFlags2[WalletAccountMergeFlags2["None"] = 0] = "None";
  WalletAccountMergeFlags2[WalletAccountMergeFlags2["MergeFullyPaidPurse"] = 1] = "MergeFullyPaidPurse";
  WalletAccountMergeFlags2[WalletAccountMergeFlags2["CreateFromPurseQuota"] = 2] = "CreateFromPurseQuota";
  WalletAccountMergeFlags2[WalletAccountMergeFlags2["CreateWithPurseFee"] = 3] = "CreateWithPurseFee";
})(WalletAccountMergeFlags || (WalletAccountMergeFlags = {}));
var SignaturePurposeBuilder = class {
  constructor(purposeNum) {
    this.purposeNum = purposeNum;
    this.chunks = [];
  }
  put(bytes) {
    this.chunks.push(Uint8Array.from(bytes));
    return this;
  }
  build() {
    let payloadLen = 0;
    for (const c4 of this.chunks) {
      payloadLen += c4.byteLength;
    }
    const buf = new ArrayBuffer(4 + 4 + payloadLen);
    const u8buf = new Uint8Array(buf);
    let p5 = 8;
    for (const c4 of this.chunks) {
      u8buf.set(c4, p5);
      p5 += c4.byteLength;
    }
    const dvbuf = new DataView(buf);
    dvbuf.setUint32(0, payloadLen + 4 + 4);
    dvbuf.setUint32(4, this.purposeNum);
    return u8buf;
  }
};
function buildSigPS(purposeNum) {
  return new SignaturePurposeBuilder(purposeNum);
}
function bigintToNaclArr(x3, size) {
  const byteArr = new Uint8Array(size);
  const arr = x3.toArray(256).value.reverse();
  byteArr.set(arr, 0);
  return byteArr;
}
function bigintFromNaclArr(arr) {
  let rev2 = new Uint8Array(arr);
  rev2 = rev2.reverse();
  return import_big_integer.default.fromArray(Array.from(rev2), 256, false);
}
var Edx25519;
(function(Edx255192) {
  const revL = [
    237,
    211,
    245,
    92,
    26,
    99,
    18,
    88,
    214,
    156,
    247,
    162,
    222,
    249,
    222,
    20,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    16
  ];
  const L4 = import_big_integer.default.fromArray(revL.reverse(), 256, false);
  async function keyCreateFromSeed(seed) {
    return crypto_edx25519_private_key_create_from_seed(seed);
  }
  Edx255192.keyCreateFromSeed = keyCreateFromSeed;
  async function keyCreate() {
    return crypto_edx25519_private_key_create();
  }
  Edx255192.keyCreate = keyCreate;
  async function getPublic(priv) {
    return crypto_edx25519_get_public(priv);
  }
  Edx255192.getPublic = getPublic;
  function sign2(msg, key) {
    throw Error("not implemented");
  }
  Edx255192.sign = sign2;
  async function deriveFactor(pub, seed) {
    const res = kdfKw({
      outputLength: 64,
      salt: seed,
      ikm: pub,
      info: stringToBytes("edx25519-derivation")
    });
    return res;
  }
  async function privateKeyDerive(priv, seed) {
    const pub = await getPublic(priv);
    const privDec = priv;
    const a4 = bigintFromNaclArr(privDec.subarray(0, 32));
    const factorEnc = await deriveFactor(pub, seed);
    const factorModL = bigintFromNaclArr(factorEnc).mod(L4);
    const aPrime = a4.divide(8).multiply(factorModL).mod(L4).multiply(8).mod(L4);
    const bPrime = hash(typedArrayConcat([privDec.subarray(32, 64), factorEnc])).subarray(0, 32);
    const newPriv = typedArrayConcat([bigintToNaclArr(aPrime, 32), bPrime]);
    return newPriv;
  }
  Edx255192.privateKeyDerive = privateKeyDerive;
  async function publicKeyDerive(pub, seed) {
    const factorEnc = await deriveFactor(pub, seed);
    const factorReduced = crypto_core_ed25519_scalar_reduce(factorEnc);
    const res = crypto_scalarmult_ed25519_noclamp(factorReduced, pub);
    return res;
  }
  Edx255192.publicKeyDerive = publicKeyDerive;
})(Edx25519 || (Edx25519 = {}));
function invariant(cond) {
  if (!cond) {
    throw Error("invariant failed");
  }
}
var AgeRestriction;
(function(AgeRestriction2) {
  AgeRestriction2.AGE_UNRESTRICTED = 32;
  function hashCommitment(ac) {
    const hc = new HashState();
    for (const pub of ac.publicKeys) {
      hc.update(decodeCrock(pub));
    }
    return encodeCrock(hc.finish().subarray(0, 32));
  }
  AgeRestriction2.hashCommitment = hashCommitment;
  function countAgeGroups(mask) {
    let count = 0;
    let m4 = mask;
    while (m4 > 0) {
      count += m4 & 1;
      m4 = m4 >> 1;
    }
    return count;
  }
  AgeRestriction2.countAgeGroups = countAgeGroups;
  function getAgeGroupsFromMask(mask) {
    const groups = [];
    let age = 1;
    let m4 = mask >> 1;
    while (m4 > 0) {
      if (m4 & 1) {
        groups.push(age);
      }
      m4 = m4 >> 1;
      age++;
    }
    return groups;
  }
  AgeRestriction2.getAgeGroupsFromMask = getAgeGroupsFromMask;
  function getAgeGroupIndex(mask, age) {
    invariant((mask & 1) === 1);
    let i4 = 0;
    let m4 = mask;
    let a4 = age;
    while (m4 > 0) {
      if (a4 <= 0) {
        break;
      }
      m4 = m4 >> 1;
      i4 += m4 & 1;
      a4--;
    }
    return i4;
  }
  AgeRestriction2.getAgeGroupIndex = getAgeGroupIndex;
  function ageGroupSpecToMask(ageGroupSpec) {
    throw Error("not implemented");
  }
  AgeRestriction2.ageGroupSpecToMask = ageGroupSpecToMask;
  async function restrictionCommit(ageMask, age) {
    invariant((ageMask & 1) === 1);
    const numPubs = countAgeGroups(ageMask) - 1;
    const numPrivs = getAgeGroupIndex(ageMask, age);
    const pubs = [];
    const privs = [];
    for (let i4 = 0; i4 < numPubs; i4++) {
      const priv = await Edx25519.keyCreate();
      const pub = await Edx25519.getPublic(priv);
      pubs.push(pub);
      if (i4 < numPrivs) {
        privs.push(priv);
      }
    }
    return {
      commitment: {
        mask: ageMask,
        publicKeys: pubs.map((x3) => encodeCrock(x3))
      },
      proof: {
        privateKeys: privs.map((x3) => encodeCrock(x3))
      }
    };
  }
  AgeRestriction2.restrictionCommit = restrictionCommit;
  const PublishedAgeRestrictionBaseKey = decodeCrock("CH0VKFDZ2GWRWHQBBGEK9MWV5YDQVJ0RXEE0KYT3NMB69F0R96TG");
  async function restrictionCommitSeeded(ageMask, age, seed) {
    invariant((ageMask & 1) === 1);
    const numPubs = countAgeGroups(ageMask) - 1;
    const numPrivs = getAgeGroupIndex(ageMask, age);
    const pubs = [];
    const privs = [];
    for (let i4 = 0; i4 < numPrivs; i4++) {
      const privSeed = await kdfKw({
        outputLength: 32,
        ikm: seed,
        info: stringToBytes("age-commitment"),
        salt: bufferForUint32(i4)
      });
      const priv = await Edx25519.keyCreateFromSeed(privSeed);
      const pub = await Edx25519.getPublic(priv);
      pubs.push(pub);
      privs.push(priv);
    }
    for (let i4 = numPrivs; i4 < numPubs; i4++) {
      const deriveSeed = await kdfKw({
        outputLength: 32,
        ikm: seed,
        info: stringToBytes("age-factor"),
        salt: bufferForUint32(i4)
      });
      const pub = await Edx25519.publicKeyDerive(PublishedAgeRestrictionBaseKey, deriveSeed);
      pubs.push(pub);
    }
    return {
      commitment: {
        mask: ageMask,
        publicKeys: pubs.map((x3) => encodeCrock(x3))
      },
      proof: {
        privateKeys: privs.map((x3) => encodeCrock(x3))
      }
    };
  }
  AgeRestriction2.restrictionCommitSeeded = restrictionCommitSeeded;
  async function commitCompare(c1, c22, salt) {
    if (c1.publicKeys.length != c22.publicKeys.length) {
      return false;
    }
    for (let i4 = 0; i4 < c1.publicKeys.length; i4++) {
      const k1 = decodeCrock(c1.publicKeys[i4]);
      const k22 = await Edx25519.publicKeyDerive(decodeCrock(c22.publicKeys[i4]), salt);
      if (k1 != k22) {
        return false;
      }
    }
    return true;
  }
  AgeRestriction2.commitCompare = commitCompare;
  async function commitmentDerive(commitmentProof, salt) {
    const newPrivs = [];
    const newPubs = [];
    for (const oldPub of commitmentProof.commitment.publicKeys) {
      newPubs.push(await Edx25519.publicKeyDerive(decodeCrock(oldPub), salt));
    }
    for (const oldPriv of commitmentProof.proof.privateKeys) {
      newPrivs.push(await Edx25519.privateKeyDerive(decodeCrock(oldPriv), salt));
    }
    return {
      commitment: {
        mask: commitmentProof.commitment.mask,
        publicKeys: newPubs.map((x3) => encodeCrock(x3))
      },
      proof: {
        privateKeys: newPrivs.map((x3) => encodeCrock(x3))
      }
    };
  }
  AgeRestriction2.commitmentDerive = commitmentDerive;
  function commitmentAttest(commitmentProof, age) {
    const d4 = buildSigPS(TalerSignaturePurpose.WALLET_AGE_ATTESTATION).put(bufferForUint32(commitmentProof.commitment.mask)).put(bufferForUint32(age)).build();
    const group = getAgeGroupIndex(commitmentProof.commitment.mask, age);
    if (group === 0) {
      return new Uint8Array(64);
    }
    const priv = commitmentProof.proof.privateKeys[group - 1];
    const pub = commitmentProof.commitment.publicKeys[group - 1];
    const sig = crypto_edx25519_sign_detached(d4, decodeCrock(priv), decodeCrock(pub));
    return sig;
  }
  AgeRestriction2.commitmentAttest = commitmentAttest;
  function commitmentVerify(commitment, sig, age) {
    const d4 = buildSigPS(TalerSignaturePurpose.WALLET_AGE_ATTESTATION).put(bufferForUint32(commitment.mask)).put(bufferForUint32(age)).build();
    const group = getAgeGroupIndex(commitment.mask, age);
    if (group === 0) {
      return true;
    }
    const pub = commitment.publicKeys[group - 1];
    return crypto_edx25519_sign_detached_verify(d4, decodeCrock(sig), decodeCrock(pub));
  }
  AgeRestriction2.commitmentVerify = commitmentVerify;
})(AgeRestriction || (AgeRestriction = {}));
var ContractFormatTag;
(function(ContractFormatTag2) {
  ContractFormatTag2[ContractFormatTag2["PaymentOffer"] = 0] = "PaymentOffer";
  ContractFormatTag2[ContractFormatTag2["PaymentRequest"] = 1] = "PaymentRequest";
})(ContractFormatTag || (ContractFormatTag = {}));

// ../taler-util/lib/payto.js
function codecForPaytoString() {
  return {
    decode(x3, c4) {
      if (typeof x3 !== "string") {
        throw new DecodingError(`expected string at ${renderContext(c4)} but got ${typeof x3}`);
      }
      if (!x3.startsWith(paytoPfx)) {
        throw new DecodingError(`expected start with payto at ${renderContext(c4)} but got "${x3}"`);
      }
      return x3;
    }
  };
}
var paytoPfx = "payto://";

// ../taler-util/lib/http-common.js
var textEncoder2 = new TextEncoder();
var logger3 = new Logger("http.ts");
async function readTalerErrorResponse(httpResponse) {
  const contentType = httpResponse.headers.get("content-type");
  if (contentType !== "application/json") {
    throw TalerError.fromDetail(TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE, {
      requestUrl: httpResponse.requestUrl,
      requestMethod: httpResponse.requestMethod,
      httpStatusCode: httpResponse.status,
      contentType: contentType || "<null>"
    }, "Error response did not even contain JSON. The request URL might be wrong or the service might be unavailable.");
  }
  let errJson;
  try {
    errJson = await httpResponse.json();
  } catch (e4) {
    throw TalerError.fromDetail(TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE, {
      requestUrl: httpResponse.requestUrl,
      requestMethod: httpResponse.requestMethod,
      httpStatusCode: httpResponse.status,
      response: await httpResponse.text(),
      validationError: e4.toString()
    }, "Couldn't parse JSON format from error response");
  }
  const talerErrorCode = errJson.code;
  if (typeof talerErrorCode !== "number") {
    logger3.warn(`malformed error response (status ${httpResponse.status}): ${j2s(errJson)}`);
    throw TalerError.fromDetail(TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE, {
      requestUrl: httpResponse.requestUrl,
      requestMethod: httpResponse.requestMethod,
      httpStatusCode: httpResponse.status,
      response: await httpResponse.text()
    }, "Error response did not contain error code");
  }
  return errJson;
}
async function readSuccessResponseJsonOrErrorCode(httpResponse, codec) {
  if (!(httpResponse.status >= 200 && httpResponse.status < 300)) {
    return {
      isError: true,
      talerErrorResponse: await readTalerErrorResponse(httpResponse)
    };
  }
  let respJson;
  try {
    respJson = await httpResponse.json();
  } catch (e4) {
    throw TalerError.fromDetail(TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE, {
      requestUrl: httpResponse.requestUrl,
      requestMethod: httpResponse.requestMethod,
      httpStatusCode: httpResponse.status,
      response: await httpResponse.text(),
      validationError: e4.toString()
    }, "Couldn't parse JSON format from response");
  }
  let parsedResponse;
  try {
    parsedResponse = codec.decode(respJson);
  } catch (e4) {
    throw TalerError.fromDetail(TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE, {
      requestUrl: httpResponse.requestUrl,
      requestMethod: httpResponse.requestMethod,
      httpStatusCode: httpResponse.status,
      response: await httpResponse.text(),
      validationError: e4.toString()
    }, "Response invalid");
  }
  return {
    isError: false,
    response: parsedResponse
  };
}
function throwUnexpectedRequestError(httpResponse, talerErrorResponse) {
  throw TalerError.fromDetail(TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR, {
    requestUrl: httpResponse.requestUrl,
    requestMethod: httpResponse.requestMethod,
    httpStatusCode: httpResponse.status,
    errorResponse: talerErrorResponse
  }, `Unexpected HTTP status ${httpResponse.status} in response`);
}
async function readSuccessResponseJsonOrThrow(httpResponse, codec) {
  const r4 = await readSuccessResponseJsonOrErrorCode(httpResponse, codec);
  if (!r4.isError) {
    return r4.response;
  }
  throwUnexpectedRequestError(httpResponse, r4.talerErrorResponse);
}

// ../taler-util/lib/operation.js
async function opSuccessFromHttp(resp, codec) {
  const body = await readSuccessResponseJsonOrThrow(resp, codec);
  return { type: "ok", body };
}
function opFixedSuccess(body) {
  return { type: "ok", body };
}
function opEmptySuccess(resp) {
  return { type: "ok", body: void 0 };
}
async function opKnownHttpFailure(s4, resp) {
  const detail = await readTalerErrorResponse(resp);
  return { type: "fail", case: s4, detail };
}
function opKnownTalerFailure(s4, detail) {
  return { type: "fail", case: s4, detail };
}
function opUnknownFailure(resp, error2) {
  throw TalerError.fromDetail(TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR, {
    requestUrl: resp.requestUrl,
    requestMethod: resp.requestMethod,
    httpStatusCode: resp.status,
    errorResponse: error2
  }, `Unexpected HTTP status ${resp.status} in response`);
}

// ../taler-util/lib/taleruri.js
function parseWithdrawUriWithError(s4) {
  const pi = parseProtoInfoWithError(s4, "withdraw");
  if (pi.type === "fail") {
    return pi;
  }
  const c4 = pi.body.rest.split("?", 2);
  const path = c4[0];
  const q4 = new URLSearchParams2(c4[1] ?? "");
  const parts = path.split("/");
  if (parts.length < 2) {
    return opKnownTalerFailure(TalerErrorCode.WALLET_TALER_URI_MALFORMED, {
      code: TalerErrorCode.WALLET_TALER_URI_MALFORMED
    });
  }
  const host = parts[0].toLowerCase();
  const pathSegments = parts.slice(1, parts.length - 1);
  const withdrawId = parts[parts.length - 1];
  const p5 = [host, ...pathSegments].join("/");
  const result = {
    type: TalerUriAction.Withdraw,
    bankIntegrationApiBaseUrl: canonicalizeBaseUrl(`${pi.body.innerProto}://${p5}/`),
    withdrawalOperationId: withdrawId,
    externalConfirmation: q4.get("external-confirmation") == "1"
  };
  return opFixedSuccess(result);
}
function parseWithdrawUri(s4) {
  const r4 = parseWithdrawUriWithError(s4);
  if (r4.type === "fail")
    return void 0;
  return r4.body;
}
function parseAddExchangeUriWithError(s4) {
  const pi = parseProtoInfoWithError(s4, "add-exchange");
  if (pi.type === "fail") {
    return pi;
  }
  const parts = pi.body.rest.split("/");
  if (parts.length < 2) {
    return opKnownTalerFailure(TalerErrorCode.WALLET_TALER_URI_MALFORMED, {
      code: TalerErrorCode.WALLET_TALER_URI_MALFORMED
    });
  }
  const host = parts[0].toLowerCase();
  const pathSegments = parts.slice(1, parts.length - 1);
  const p5 = [host, ...pathSegments].join("/");
  const result = {
    type: TalerUriAction.AddExchange,
    exchangeBaseUrl: canonicalizeBaseUrl(`${pi.body.innerProto}://${p5}/`)
  };
  return opFixedSuccess(result);
}
function parseAddExchangeUri(s4) {
  const r4 = parseAddExchangeUriWithError(s4);
  if (r4.type === "fail")
    return void 0;
  return r4.body;
}
var TalerUriType;
(function(TalerUriType2) {
  TalerUriType2["TalerPay"] = "taler-pay";
  TalerUriType2["TalerTemplate"] = "taler-template";
  TalerUriType2["TalerPayTemplate"] = "taler-pay-template";
  TalerUriType2["TalerWithdraw"] = "taler-withdraw";
  TalerUriType2["TalerTip"] = "taler-tip";
  TalerUriType2["TalerRefund"] = "taler-refund";
  TalerUriType2["TalerPayPush"] = "taler-pay-push";
  TalerUriType2["TalerPayPull"] = "taler-pay-pull";
  TalerUriType2["TalerRecovery"] = "taler-recovery";
  TalerUriType2["TalerDevExperiment"] = "taler-dev-experiment";
  TalerUriType2["Unknown"] = "unknown";
})(TalerUriType || (TalerUriType = {}));
var TalerUriAction;
(function(TalerUriAction2) {
  TalerUriAction2["Pay"] = "pay";
  TalerUriAction2["Withdraw"] = "withdraw";
  TalerUriAction2["Refund"] = "refund";
  TalerUriAction2["PayPull"] = "pay-pull";
  TalerUriAction2["PayPush"] = "pay-push";
  TalerUriAction2["PayTemplate"] = "pay-template";
  TalerUriAction2["Restore"] = "restore";
  TalerUriAction2["DevExperiment"] = "dev-experiment";
  TalerUriAction2["WithdrawExchange"] = "withdraw-exchange";
  TalerUriAction2["AddExchange"] = "add-exchange";
})(TalerUriAction || (TalerUriAction = {}));
function parseProtoInfo(s4, action) {
  const pfxPlain = `taler://${action}/`;
  const pfxHttp = `taler+http://${action}/`;
  if (s4.toLowerCase().startsWith(pfxPlain)) {
    return {
      innerProto: "https",
      rest: s4.substring(pfxPlain.length)
    };
  } else if (s4.toLowerCase().startsWith(pfxHttp)) {
    return {
      innerProto: "http",
      rest: s4.substring(pfxHttp.length)
    };
  } else {
    return void 0;
  }
}
function parseProtoInfoWithError(s4, action) {
  if (!s4.toLowerCase().startsWith("taler://") && !s4.toLowerCase().startsWith("taler+http://")) {
    return opKnownTalerFailure(TalerErrorCode.WALLET_TALER_URI_MALFORMED, {
      code: TalerErrorCode.WALLET_TALER_URI_MALFORMED
    });
  }
  const pfxPlain = `taler://${action}/`;
  const pfxHttp = `taler+http://${action}/`;
  if (s4.toLowerCase().startsWith(pfxPlain)) {
    return opFixedSuccess({
      innerProto: "https",
      rest: s4.substring(pfxPlain.length)
    });
  } else if (s4.toLowerCase().startsWith(pfxHttp)) {
    return opFixedSuccess({
      innerProto: "http",
      rest: s4.substring(pfxHttp.length)
    });
  } else {
    return opKnownTalerFailure(TalerErrorCode.WALLET_TALER_URI_MALFORMED, {
      code: TalerErrorCode.WALLET_TALER_URI_MALFORMED
    });
  }
}
var parsers = {
  [TalerUriAction.Pay]: parsePayUri,
  [TalerUriAction.PayPull]: parsePayPullUri,
  [TalerUriAction.PayPush]: parsePayPushUri,
  [TalerUriAction.PayTemplate]: parsePayTemplateUri,
  [TalerUriAction.Restore]: parseRestoreUri,
  [TalerUriAction.Refund]: parseRefundUri,
  [TalerUriAction.Withdraw]: parseWithdrawUri,
  [TalerUriAction.DevExperiment]: parseDevExperimentUri,
  [TalerUriAction.WithdrawExchange]: parseWithdrawExchangeUri,
  [TalerUriAction.AddExchange]: parseAddExchangeUri
};
function parsePayUri(s4) {
  const pi = parseProtoInfo(s4, "pay");
  if (!pi) {
    return void 0;
  }
  const c4 = pi?.rest.split("?");
  const q4 = new URLSearchParams2(c4[1] ?? "");
  const claimToken = q4.get("c") ?? void 0;
  const noncePriv = q4.get("n") ?? void 0;
  const parts = c4[0].split("/");
  if (parts.length < 3) {
    return void 0;
  }
  const host = parts[0].toLowerCase();
  const sessionId = parts[parts.length - 1];
  const orderId = parts[parts.length - 2];
  const pathSegments = parts.slice(1, parts.length - 2);
  const p5 = [host, ...pathSegments].join("/");
  const merchantBaseUrl = canonicalizeBaseUrl(`${pi.innerProto}://${p5}/`);
  return {
    type: TalerUriAction.Pay,
    merchantBaseUrl,
    orderId,
    sessionId,
    claimToken,
    noncePriv
  };
}
function parsePayTemplateUri(uriString) {
  const pi = parseProtoInfo(uriString, TalerUriAction.PayTemplate);
  if (!pi) {
    return void 0;
  }
  const c4 = pi.rest.split("?");
  const parts = c4[0].split("/");
  if (parts.length < 2) {
    return void 0;
  }
  const q4 = new URLSearchParams2(c4[1] ?? "");
  const params = {};
  q4.forEach((v4, k4) => {
    params[k4] = v4;
  });
  const host = parts[0].toLowerCase();
  const templateId = parts[parts.length - 1];
  const pathSegments = parts.slice(1, parts.length - 1);
  const hostAndSegments = [host, ...pathSegments].join("/");
  const merchantBaseUrl = canonicalizeBaseUrl(`${pi.innerProto}://${hostAndSegments}/`);
  return {
    type: TalerUriAction.PayTemplate,
    merchantBaseUrl,
    templateId
  };
}
function parsePayPushUri(s4) {
  const pi = parseProtoInfo(s4, TalerUriAction.PayPush);
  if (!pi) {
    return void 0;
  }
  const c4 = pi?.rest.split("?");
  const parts = c4[0].split("/");
  if (parts.length < 2) {
    return void 0;
  }
  const host = parts[0].toLowerCase();
  const contractPriv = parts[parts.length - 1];
  const pathSegments = parts.slice(1, parts.length - 1);
  const hostAndSegments = [host, ...pathSegments].join("/");
  const exchangeBaseUrl = canonicalizeBaseUrl(`${pi.innerProto}://${hostAndSegments}/`);
  return {
    type: TalerUriAction.PayPush,
    exchangeBaseUrl,
    contractPriv
  };
}
function parsePayPullUri(s4) {
  const pi = parseProtoInfo(s4, TalerUriAction.PayPull);
  if (!pi) {
    return void 0;
  }
  const c4 = pi?.rest.split("?");
  const parts = c4[0].split("/");
  if (parts.length < 2) {
    return void 0;
  }
  const host = parts[0].toLowerCase();
  const contractPriv = parts[parts.length - 1];
  const pathSegments = parts.slice(1, parts.length - 1);
  const hostAndSegments = [host, ...pathSegments].join("/");
  const exchangeBaseUrl = canonicalizeBaseUrl(`${pi.innerProto}://${hostAndSegments}/`);
  return {
    type: TalerUriAction.PayPull,
    exchangeBaseUrl,
    contractPriv
  };
}
function parseWithdrawExchangeUri(s4) {
  const pi = parseProtoInfo(s4, "withdraw-exchange");
  if (!pi) {
    return void 0;
  }
  const c4 = pi?.rest.split("?");
  const parts = c4[0].split("/");
  if (parts.length < 1) {
    return void 0;
  }
  const host = parts[0].toLowerCase();
  const lastPathComponent = parts.length > 1 ? parts[parts.length - 1] : void 0;
  if (lastPathComponent) {
    return void 0;
  }
  const pathSegments = parts.slice(1, parts.length - 1);
  const hostAndSegments = [host, ...pathSegments].join("/");
  const exchangeBaseUrl = canonicalizeBaseUrl(`${pi.innerProto}://${hostAndSegments}/`);
  const q4 = new URLSearchParams2(c4[1] ?? "");
  const amount = q4.get("a") ?? void 0;
  return {
    type: TalerUriAction.WithdrawExchange,
    exchangeBaseUrl,
    amount
  };
}
function parseRefundUri(s4) {
  const pi = parseProtoInfo(s4, "refund");
  if (!pi) {
    return void 0;
  }
  const c4 = pi?.rest.split("?");
  const parts = c4[0].split("/");
  if (parts.length < 3) {
    return void 0;
  }
  const host = parts[0].toLowerCase();
  const sessionId = parts[parts.length - 1];
  const orderId = parts[parts.length - 2];
  const pathSegments = parts.slice(1, parts.length - 2);
  const hostAndSegments = [host, ...pathSegments].join("/");
  const merchantBaseUrl = canonicalizeBaseUrl(`${pi.innerProto}://${hostAndSegments}/`);
  return {
    type: TalerUriAction.Refund,
    merchantBaseUrl,
    orderId
  };
}
function parseDevExperimentUri(s4) {
  const pi = parseProtoInfo(s4, "dev-experiment");
  const c4 = pi?.rest.split("?");
  if (!c4) {
    return void 0;
  }
  const parts = c4[0].split("/");
  return {
    type: TalerUriAction.DevExperiment,
    devExperimentId: parts[0]
  };
}
function parseRestoreUri(uri) {
  const pi = parseProtoInfo(uri, "restore");
  if (!pi) {
    return void 0;
  }
  const c4 = pi.rest.split("?");
  const parts = c4[0].split("/");
  if (parts.length < 2) {
    return void 0;
  }
  const walletRootPriv = parts[0];
  if (!walletRootPriv)
    return void 0;
  const providers = new Array();
  parts[1].split(",").map((name) => {
    const url = canonicalizeBaseUrl(`${pi.innerProto}://${decodeURIComponent(name)}/`);
    providers.push(url);
  });
  return {
    type: TalerUriAction.Restore,
    walletRootPriv,
    providers
  };
}

// ../taler-util/lib/http-client/types.js
var codecForCurrencySpecificiation = () => buildCodecForObject().property("name", codecForString()).property("num_fractional_input_digits", codecForNumber()).property("num_fractional_normal_digits", codecForNumber()).property("num_fractional_trailing_zero_digits", codecForNumber()).property("alt_unit_names", codecForMap(codecForString())).build("CurrencySpecification");
var codecForIntegrationBankConfig = () => buildCodecForObject().property("name", codecForConstString("taler-bank-integration")).property("version", codecForString()).property("currency", codecForString()).property("currency_specification", codecForCurrencySpecificiation()).build("TalerCorebankApi.IntegrationConfig");
var codecForBankWithdrawalOperationStatus = () => buildCodecForObject().property("status", codecForEither(codecForConstString("pending"), codecForConstString("selected"), codecForConstString("aborted"), codecForConstString("confirmed"))).property("amount", codecOptional(codecForAmountString())).property("currency", codecOptional(codecForCurrencyName())).property("suggested_amount", codecOptional(codecForAmountString())).property("card_fees", codecOptional(codecForAmountString())).property("sender_wire", codecOptional(codecForPaytoString())).property("suggested_exchange", codecOptional(codecForURL())).property("confirm_transfer_url", codecOptional(codecForURL())).property("wire_types", codecForList(codecForString())).property("selected_reserve_pub", codecOptional(codecForString())).property("selected_exchange_account", codecOptional(codecForString())).property("max_amount", codecOptional(codecForAmountString())).build("TalerBankIntegrationApi.BankWithdrawalOperationStatus");
var codecForBankWithdrawalOperationPostResponse = () => buildCodecForObject().property("status", codecForEither(codecForConstString("selected"), codecForConstString("aborted"), codecForConstString("confirmed"))).property("confirm_transfer_url", codecOptional(codecForURL())).build("TalerBankIntegrationApi.BankWithdrawalOperationPostResponse");
var codecForURL = codecForString;
var codecForCurrencyName = codecForString;
var TalerCorebankApi;
(function(TalerCorebankApi2) {
  let MonitorTimeframeParam;
  (function(MonitorTimeframeParam2) {
    MonitorTimeframeParam2[MonitorTimeframeParam2["hour"] = 0] = "hour";
    MonitorTimeframeParam2[MonitorTimeframeParam2["day"] = 1] = "day";
    MonitorTimeframeParam2[MonitorTimeframeParam2["month"] = 2] = "month";
    MonitorTimeframeParam2[MonitorTimeframeParam2["year"] = 3] = "year";
    MonitorTimeframeParam2[MonitorTimeframeParam2["decade"] = 4] = "decade";
  })(MonitorTimeframeParam = TalerCorebankApi2.MonitorTimeframeParam || (TalerCorebankApi2.MonitorTimeframeParam = {}));
  let TanChannel;
  (function(TanChannel2) {
    TanChannel2["SMS"] = "sms";
    TanChannel2["EMAIL"] = "email";
  })(TanChannel = TalerCorebankApi2.TanChannel || (TalerCorebankApi2.TanChannel = {}));
})(TalerCorebankApi || (TalerCorebankApi = {}));
var TalerExchangeApi;
(function(TalerExchangeApi2) {
  let AmlState;
  (function(AmlState2) {
    AmlState2[AmlState2["normal"] = 0] = "normal";
    AmlState2[AmlState2["pending"] = 1] = "pending";
    AmlState2[AmlState2["frozen"] = 2] = "frozen";
  })(AmlState = TalerExchangeApi2.AmlState || (TalerExchangeApi2.AmlState = {}));
})(TalerExchangeApi || (TalerExchangeApi = {}));
var TalerMerchantApi;
(function(TalerMerchantApi2) {
  let TokenFamilyKind;
  (function(TokenFamilyKind2) {
    TokenFamilyKind2["Discount"] = "discount";
    TokenFamilyKind2["Subscription"] = "subscription";
  })(TokenFamilyKind = TalerMerchantApi2.TokenFamilyKind || (TalerMerchantApi2.TokenFamilyKind = {}));
})(TalerMerchantApi || (TalerMerchantApi = {}));

// ../taler-util/lib/http-status-codes.js
var HttpStatusCode;
(function(HttpStatusCode2) {
  HttpStatusCode2[HttpStatusCode2["Continue"] = 100] = "Continue";
  HttpStatusCode2[HttpStatusCode2["SwitchingProtocols"] = 101] = "SwitchingProtocols";
  HttpStatusCode2[HttpStatusCode2["Processing"] = 102] = "Processing";
  HttpStatusCode2[HttpStatusCode2["Ok"] = 200] = "Ok";
  HttpStatusCode2[HttpStatusCode2["Created"] = 201] = "Created";
  HttpStatusCode2[HttpStatusCode2["Accepted"] = 202] = "Accepted";
  HttpStatusCode2[HttpStatusCode2["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
  HttpStatusCode2[HttpStatusCode2["NoContent"] = 204] = "NoContent";
  HttpStatusCode2[HttpStatusCode2["ResetContent"] = 205] = "ResetContent";
  HttpStatusCode2[HttpStatusCode2["PartialContent"] = 206] = "PartialContent";
  HttpStatusCode2[HttpStatusCode2["MultiStatus"] = 207] = "MultiStatus";
  HttpStatusCode2[HttpStatusCode2["AlreadyReported"] = 208] = "AlreadyReported";
  HttpStatusCode2[HttpStatusCode2["ImUsed"] = 226] = "ImUsed";
  HttpStatusCode2[HttpStatusCode2["MultipleChoices"] = 300] = "MultipleChoices";
  HttpStatusCode2[HttpStatusCode2["MovedPermanently"] = 301] = "MovedPermanently";
  HttpStatusCode2[HttpStatusCode2["Found"] = 302] = "Found";
  HttpStatusCode2[HttpStatusCode2["SeeOther"] = 303] = "SeeOther";
  HttpStatusCode2[HttpStatusCode2["NotModified"] = 304] = "NotModified";
  HttpStatusCode2[HttpStatusCode2["UseProxy"] = 305] = "UseProxy";
  HttpStatusCode2[HttpStatusCode2["SwitchProxy"] = 306] = "SwitchProxy";
  HttpStatusCode2[HttpStatusCode2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
  HttpStatusCode2[HttpStatusCode2["PermanentRedirect"] = 308] = "PermanentRedirect";
  HttpStatusCode2[HttpStatusCode2["BadRequest"] = 400] = "BadRequest";
  HttpStatusCode2[HttpStatusCode2["Unauthorized"] = 401] = "Unauthorized";
  HttpStatusCode2[HttpStatusCode2["PaymentRequired"] = 402] = "PaymentRequired";
  HttpStatusCode2[HttpStatusCode2["Forbidden"] = 403] = "Forbidden";
  HttpStatusCode2[HttpStatusCode2["NotFound"] = 404] = "NotFound";
  HttpStatusCode2[HttpStatusCode2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
  HttpStatusCode2[HttpStatusCode2["NotAcceptable"] = 406] = "NotAcceptable";
  HttpStatusCode2[HttpStatusCode2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
  HttpStatusCode2[HttpStatusCode2["RequestTimeout"] = 408] = "RequestTimeout";
  HttpStatusCode2[HttpStatusCode2["Conflict"] = 409] = "Conflict";
  HttpStatusCode2[HttpStatusCode2["Gone"] = 410] = "Gone";
  HttpStatusCode2[HttpStatusCode2["LengthRequired"] = 411] = "LengthRequired";
  HttpStatusCode2[HttpStatusCode2["PreconditionFailed"] = 412] = "PreconditionFailed";
  HttpStatusCode2[HttpStatusCode2["PayloadTooLarge"] = 413] = "PayloadTooLarge";
  HttpStatusCode2[HttpStatusCode2["UriTooLong"] = 414] = "UriTooLong";
  HttpStatusCode2[HttpStatusCode2["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
  HttpStatusCode2[HttpStatusCode2["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
  HttpStatusCode2[HttpStatusCode2["ExpectationFailed"] = 417] = "ExpectationFailed";
  HttpStatusCode2[HttpStatusCode2["IAmATeapot"] = 418] = "IAmATeapot";
  HttpStatusCode2[HttpStatusCode2["MisdirectedRequest"] = 421] = "MisdirectedRequest";
  HttpStatusCode2[HttpStatusCode2["UnprocessableEntity"] = 422] = "UnprocessableEntity";
  HttpStatusCode2[HttpStatusCode2["Locked"] = 423] = "Locked";
  HttpStatusCode2[HttpStatusCode2["FailedDependency"] = 424] = "FailedDependency";
  HttpStatusCode2[HttpStatusCode2["UpgradeRequired"] = 426] = "UpgradeRequired";
  HttpStatusCode2[HttpStatusCode2["PreconditionRequired"] = 428] = "PreconditionRequired";
  HttpStatusCode2[HttpStatusCode2["TooManyRequests"] = 429] = "TooManyRequests";
  HttpStatusCode2[HttpStatusCode2["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
  HttpStatusCode2[HttpStatusCode2["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
  HttpStatusCode2[HttpStatusCode2["InternalServerError"] = 500] = "InternalServerError";
  HttpStatusCode2[HttpStatusCode2["NotImplemented"] = 501] = "NotImplemented";
  HttpStatusCode2[HttpStatusCode2["BadGateway"] = 502] = "BadGateway";
  HttpStatusCode2[HttpStatusCode2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
  HttpStatusCode2[HttpStatusCode2["GatewayTimeout"] = 504] = "GatewayTimeout";
  HttpStatusCode2[HttpStatusCode2["HttpVersionNotSupported"] = 505] = "HttpVersionNotSupported";
  HttpStatusCode2[HttpStatusCode2["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
  HttpStatusCode2[HttpStatusCode2["InsufficientStorage"] = 507] = "InsufficientStorage";
  HttpStatusCode2[HttpStatusCode2["LoopDetected"] = 508] = "LoopDetected";
  HttpStatusCode2[HttpStatusCode2["NotExtended"] = 510] = "NotExtended";
  HttpStatusCode2[HttpStatusCode2["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
})(HttpStatusCode || (HttpStatusCode = {}));

// ../taler-util/lib/http-impl.missing.js
var HttpLibImpl = class {
  fetch(url, opt) {
    throw new Error("Method not implemented.");
  }
};

// ../taler-util/lib/http.js
function createPlatformHttpLib(args) {
  return new HttpLibImpl(args);
}

// ../taler-util/lib/libtool-version.js
var LibtoolVersion;
(function(LibtoolVersion2) {
  function compare(me, other) {
    const meVer = parseVersion(me);
    const otherVer = parseVersion(other);
    if (!(meVer && otherVer)) {
      return void 0;
    }
    const compatible = meVer.current - meVer.age <= otherVer.current && meVer.current >= otherVer.current - otherVer.age;
    const currentCmp = Math.sign(meVer.current - otherVer.current);
    return { compatible, currentCmp };
  }
  LibtoolVersion2.compare = compare;
  function parseVersion(v4) {
    const [currentStr, revisionStr, ageStr, ...rest] = v4.split(":");
    if (rest.length !== 0) {
      return void 0;
    }
    const current = Number.parseInt(currentStr);
    const revision = Number.parseInt(revisionStr);
    const age = Number.parseInt(ageStr);
    if (Number.isNaN(current)) {
      return void 0;
    }
    if (Number.isNaN(revision)) {
      return void 0;
    }
    if (Number.isNaN(age)) {
      return void 0;
    }
    return { current, revision, age };
  }
  LibtoolVersion2.parseVersion = parseVersion;
})(LibtoolVersion || (LibtoolVersion = {}));

// ../taler-util/lib/MerchantApiClient.js
var logger4 = new Logger("MerchantApiClient.ts");

// ../taler-util/lib/RequestThrottler.js
var logger5 = new Logger("RequestThrottler.ts");

// ../taler-util/lib/ReserveTransaction.js
var ReserveTransactionType;
(function(ReserveTransactionType2) {
  ReserveTransactionType2["Withdraw"] = "WITHDRAW";
  ReserveTransactionType2["Credit"] = "CREDIT";
  ReserveTransactionType2["Recoup"] = "RECOUP";
  ReserveTransactionType2["Closing"] = "CLOSING";
})(ReserveTransactionType || (ReserveTransactionType = {}));

// ../taler-util/lib/TaskThrottler.js
var logger6 = new Logger("OperationThrottler.ts");

// ../taler-util/lib/bank-api-client.js
var logger7 = new Logger("bank-api-client.ts");
var CreditDebitIndicator;
(function(CreditDebitIndicator2) {
  CreditDebitIndicator2["Credit"] = "credit";
  CreditDebitIndicator2["Debit"] = "debit";
})(CreditDebitIndicator || (CreditDebitIndicator = {}));

// ../taler-util/lib/contract-terms.js
var logger8 = new Logger("contractTerms.ts");
var ContractTermsUtil;
(function(ContractTermsUtil2) {
  function forgetAllImpl(anyJson, path, pred) {
    const dup = JSON.parse(JSON.stringify(anyJson));
    if (Array.isArray(dup)) {
      for (let i4 = 0; i4 < dup.length; i4++) {
        dup[i4] = forgetAllImpl(dup[i4], [...path, `${i4}`], pred);
      }
    } else if (typeof dup === "object" && dup != null) {
      if (typeof dup.$forgettable === "object") {
        for (const x3 of Object.keys(dup.$forgettable)) {
          if (!pred([...path, x3])) {
            continue;
          }
          if (!dup.$forgotten) {
            dup.$forgotten = {};
          }
          if (!dup.$forgotten[x3]) {
            const membValCanon = stringToBytes(canonicalJson(scrub(dup[x3])) + "\0");
            const membSalt = stringToBytes(dup.$forgettable[x3] + "\0");
            const h4 = kdf(64, membValCanon, membSalt, new Uint8Array([]));
            dup.$forgotten[x3] = encodeCrock(h4);
          }
          delete dup[x3];
          delete dup.$forgettable[x3];
        }
        if (Object.keys(dup.$forgettable).length === 0) {
          delete dup.$forgettable;
        }
      }
      for (const x3 of Object.keys(dup)) {
        if (x3.startsWith("$")) {
          continue;
        }
        dup[x3] = forgetAllImpl(dup[x3], [...path, x3], pred);
      }
    }
    return dup;
  }
  ContractTermsUtil2.forgetAllImpl = forgetAllImpl;
  function scrub(anyJson) {
    return forgetAllImpl(anyJson, [], () => true);
  }
  ContractTermsUtil2.scrub = scrub;
  function forgetAll(anyJson, pred) {
    return forgetAllImpl(anyJson, [], pred);
  }
  ContractTermsUtil2.forgetAll = forgetAll;
  function saltForgettable(anyJson) {
    const dup = JSON.parse(JSON.stringify(anyJson));
    if (Array.isArray(dup)) {
      for (let i4 = 0; i4 < dup.length; i4++) {
        dup[i4] = saltForgettable(dup[i4]);
      }
    } else if (typeof dup === "object" && dup !== null) {
      if (typeof dup.$forgettable === "object") {
        for (const k4 of Object.keys(dup.$forgettable)) {
          if (dup.$forgettable[k4] === true) {
            dup.$forgettable[k4] = encodeCrock(getRandomBytes(32));
          }
        }
      }
      for (const x3 of Object.keys(dup)) {
        if (x3.startsWith("$")) {
          continue;
        }
        dup[x3] = saltForgettable(dup[x3]);
      }
    }
    return dup;
  }
  ContractTermsUtil2.saltForgettable = saltForgettable;
  const nameRegex = /^[0-9A-Za-z_]+$/;
  function validateForgettable(anyJson) {
    if (typeof anyJson === "string") {
      return true;
    }
    if (typeof anyJson === "number") {
      return Number.isInteger(anyJson) && anyJson >= Number.MIN_SAFE_INTEGER && anyJson <= Number.MAX_SAFE_INTEGER;
    }
    if (typeof anyJson === "boolean") {
      return true;
    }
    if (anyJson === null) {
      return true;
    }
    if (Array.isArray(anyJson)) {
      return anyJson.every((x3) => validateForgettable(x3));
    }
    if (typeof anyJson === "object") {
      for (const k4 of Object.keys(anyJson)) {
        if (k4.match(nameRegex)) {
          if (validateForgettable(anyJson[k4])) {
            continue;
          } else {
            return false;
          }
        }
        if (k4 === "$forgettable") {
          const fga = anyJson.$forgettable;
          if (!fga || typeof fga !== "object") {
            return false;
          }
          for (const fk of Object.keys(fga)) {
            if (!fk.match(nameRegex)) {
              return false;
            }
            if (!(fk in anyJson)) {
              return false;
            }
            const fv = anyJson.$forgettable[fk];
            if (typeof fv !== "string") {
              return false;
            }
          }
        } else if (k4 === "$forgotten") {
          const fgo = anyJson.$forgotten;
          if (!fgo || typeof fgo !== "object") {
            return false;
          }
          for (const fk of Object.keys(fgo)) {
            if (!fk.match(nameRegex)) {
              return false;
            }
            if (fk in anyJson) {
              return false;
            }
            const fv = anyJson.$forgotten[fk];
            if (typeof fv !== "string") {
              return false;
            }
            try {
              const decFv = decodeCrock(fv);
              if (decFv.length != 64) {
                return false;
              }
            } catch (e4) {
              return false;
            }
            if (anyJson.$forgettable?.[k4] !== void 0) {
              return false;
            }
          }
        } else {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  ContractTermsUtil2.validateForgettable = validateForgettable;
  function validateNothingForgotten(contractTerms) {
    throw Error("not implemented yet");
  }
  ContractTermsUtil2.validateNothingForgotten = validateNothingForgotten;
  function hashContractTerms(contractTerms) {
    const cleaned = scrub(contractTerms);
    const canon = canonicalJson(cleaned) + "\0";
    const bytes = stringToBytes(canon);
    return encodeCrock(hash2(bytes));
  }
  ContractTermsUtil2.hashContractTerms = hashContractTerms;
})(ContractTermsUtil || (ContractTermsUtil = {}));

// ../taler-util/lib/errors.js
function makeErrorDetail(code, detail, hint) {
  if (!hint && !detail.hint) {
    hint = getDefaultHint(code);
  }
  const when = AbsoluteTime.now();
  return { code, when, hint, ...detail };
}
function getDefaultHint(code) {
  const errName = TalerErrorCode[code];
  if (errName) {
    return `Error (${errName})`;
  } else {
    return `Error (<unknown>)`;
  }
}
var TalerError = class _TalerError extends Error {
  constructor(d4, cause) {
    super(d4.hint ?? `Error (code ${d4.code})`);
    this.errorDetail = d4;
    this.cause = cause;
    Object.setPrototypeOf(this, _TalerError.prototype);
  }
  static fromDetail(code, detail, hint, cause) {
    if (!hint) {
      hint = getDefaultHint(code);
    }
    const when = AbsoluteTime.now();
    return new _TalerError({ code, when, hint, ...detail }, cause);
  }
  static fromUncheckedDetail(d4, c4) {
    return new _TalerError({ ...d4 }, c4);
  }
  static fromException(e4) {
    const errDetail = getErrorDetailFromException(e4);
    return new _TalerError(errDetail, e4);
  }
  hasErrorCode(code) {
    return this.errorDetail.code === code;
  }
  toString() {
    return `TalerError: ${JSON.stringify(this.errorDetail)}`;
  }
};
function getErrorDetailFromException(e4) {
  if (e4 instanceof TalerError) {
    return e4.errorDetail;
  }
  if (e4 instanceof CancellationToken.CancellationError) {
    const err3 = makeErrorDetail(TalerErrorCode.WALLET_CORE_REQUEST_CANCELLED, {});
    return err3;
  }
  if (e4 instanceof Error) {
    const err3 = makeErrorDetail(TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION, {
      stack: e4.stack
    }, `unexpected exception (message: ${e4.message})`);
    return err3;
  }
  let excString;
  try {
    excString = e4.toString();
  } catch (e5) {
    excString = "can't stringify exception";
  }
  const err2 = makeErrorDetail(TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION, {}, `unexpected exception (not an exception, ${excString})`);
  return err2;
}

// ../taler-util/lib/fnutils.js
var fnutil;
(function(fnutil2) {
  function all(arr, f4) {
    for (const x3 of arr) {
      if (!f4(x3)) {
        return false;
      }
    }
    return true;
  }
  fnutil2.all = all;
  function any(arr, f4) {
    for (const x3 of arr) {
      if (f4(x3)) {
        return true;
      }
    }
    return false;
  }
  fnutil2.any = any;
})(fnutil || (fnutil = {}));

// ../taler-util/lib/http-client/utils.js
function addLongPollingParam(url, param) {
  if (!param)
    return;
  if (param.timeoutMs) {
    url.searchParams.set("long_poll_ms", String(param.timeoutMs));
  }
}

// ../taler-util/lib/transactions-types.js
var TransactionMajorState;
(function(TransactionMajorState2) {
  TransactionMajorState2["None"] = "none";
  TransactionMajorState2["Pending"] = "pending";
  TransactionMajorState2["Done"] = "done";
  TransactionMajorState2["Aborting"] = "aborting";
  TransactionMajorState2["Aborted"] = "aborted";
  TransactionMajorState2["Dialog"] = "dialog";
  TransactionMajorState2["Finalizing"] = "finalizing";
  TransactionMajorState2["Suspended"] = "suspended";
  TransactionMajorState2["SuspendedFinalizing"] = "suspended-finalizing";
  TransactionMajorState2["SuspendedAborting"] = "suspended-aborting";
  TransactionMajorState2["Failed"] = "failed";
  TransactionMajorState2["Expired"] = "expired";
  TransactionMajorState2["Deleted"] = "deleted";
})(TransactionMajorState || (TransactionMajorState = {}));
var TransactionMinorState;
(function(TransactionMinorState2) {
  TransactionMinorState2["Unknown"] = "unknown";
  TransactionMinorState2["Deposit"] = "deposit";
  TransactionMinorState2["KycRequired"] = "kyc";
  TransactionMinorState2["AmlRequired"] = "aml";
  TransactionMinorState2["MergeKycRequired"] = "merge-kyc";
  TransactionMinorState2["Track"] = "track";
  TransactionMinorState2["SubmitPayment"] = "submit-payment";
  TransactionMinorState2["RebindSession"] = "rebind-session";
  TransactionMinorState2["Refresh"] = "refresh";
  TransactionMinorState2["Pickup"] = "pickup";
  TransactionMinorState2["AutoRefund"] = "auto-refund";
  TransactionMinorState2["User"] = "user";
  TransactionMinorState2["Bank"] = "bank";
  TransactionMinorState2["Exchange"] = "exchange";
  TransactionMinorState2["ClaimProposal"] = "claim-proposal";
  TransactionMinorState2["CheckRefund"] = "check-refund";
  TransactionMinorState2["CreatePurse"] = "create-purse";
  TransactionMinorState2["DeletePurse"] = "delete-purse";
  TransactionMinorState2["RefreshExpired"] = "refresh-expired";
  TransactionMinorState2["Ready"] = "ready";
  TransactionMinorState2["Merge"] = "merge";
  TransactionMinorState2["Repurchase"] = "repurchase";
  TransactionMinorState2["BankRegisterReserve"] = "bank-register-reserve";
  TransactionMinorState2["BankConfirmTransfer"] = "bank-confirm-transfer";
  TransactionMinorState2["WithdrawCoins"] = "withdraw-coins";
  TransactionMinorState2["ExchangeWaitReserve"] = "exchange-wait-reserve";
  TransactionMinorState2["AbortingBank"] = "aborting-bank";
  TransactionMinorState2["Aborting"] = "aborting";
  TransactionMinorState2["Refused"] = "refused";
  TransactionMinorState2["Withdraw"] = "withdraw";
  TransactionMinorState2["MerchantOrderProposed"] = "merchant-order-proposed";
  TransactionMinorState2["Proposed"] = "proposed";
  TransactionMinorState2["RefundAvailable"] = "refund-available";
  TransactionMinorState2["AcceptRefund"] = "accept-refund";
  TransactionMinorState2["PaidByOther"] = "paid-by-other";
  TransactionMinorState2["CompletedByOtherWallet"] = "completed-by-other-wallet";
})(TransactionMinorState || (TransactionMinorState = {}));
var TransactionAction;
(function(TransactionAction2) {
  TransactionAction2["Delete"] = "delete";
  TransactionAction2["Suspend"] = "suspend";
  TransactionAction2["Resume"] = "resume";
  TransactionAction2["Abort"] = "abort";
  TransactionAction2["Fail"] = "fail";
  TransactionAction2["Retry"] = "retry";
})(TransactionAction || (TransactionAction = {}));
var TransactionType;
(function(TransactionType2) {
  TransactionType2["Withdrawal"] = "withdrawal";
  TransactionType2["InternalWithdrawal"] = "internal-withdrawal";
  TransactionType2["Payment"] = "payment";
  TransactionType2["Refund"] = "refund";
  TransactionType2["Refresh"] = "refresh";
  TransactionType2["Deposit"] = "deposit";
  TransactionType2["PeerPushDebit"] = "peer-push-debit";
  TransactionType2["PeerPushCredit"] = "peer-push-credit";
  TransactionType2["PeerPullDebit"] = "peer-pull-debit";
  TransactionType2["PeerPullCredit"] = "peer-pull-credit";
  TransactionType2["Recoup"] = "recoup";
  TransactionType2["DenomLoss"] = "denom-loss";
})(TransactionType || (TransactionType = {}));
var WithdrawalType;
(function(WithdrawalType2) {
  WithdrawalType2["TalerBankIntegrationApi"] = "taler-bank-integration-api";
  WithdrawalType2["ManualTransfer"] = "manual-transfer";
})(WithdrawalType || (WithdrawalType = {}));
var DenomLossEventType;
(function(DenomLossEventType2) {
  DenomLossEventType2["DenomExpired"] = "denom-expired";
  DenomLossEventType2["DenomVanished"] = "denom-vanished";
  DenomLossEventType2["DenomUnoffered"] = "denom-unoffered";
})(DenomLossEventType || (DenomLossEventType = {}));
var PaymentStatus;
(function(PaymentStatus2) {
  PaymentStatus2["Aborted"] = "aborted";
  PaymentStatus2["Failed"] = "failed";
  PaymentStatus2["Paid"] = "paid";
  PaymentStatus2["Accepted"] = "accepted";
})(PaymentStatus || (PaymentStatus = {}));

// ../taler-util/lib/wallet-types.js
var TransactionAmountMode;
(function(TransactionAmountMode2) {
  TransactionAmountMode2["Effective"] = "effective";
  TransactionAmountMode2["Raw"] = "raw";
})(TransactionAmountMode || (TransactionAmountMode = {}));
var codecForConvertAmountRequest = buildCodecForObject().property("amount", codecForAmountString()).property("depositPaytoUri", codecForPaytoString()).property("type", codecForEither(codecForConstString(TransactionAmountMode.Raw), codecForConstString(TransactionAmountMode.Effective))).build("ConvertAmountRequest");
var codecForGetAmountRequest = buildCodecForObject().property("currency", codecForString()).build("GetAmountRequest");
var codecForGetPlanForWalletInitiatedOperation = () => buildCodecForObject().property("mode", codecForEither(codecForConstString(TransactionAmountMode.Raw), codecForConstString(TransactionAmountMode.Effective))).property("instructedAmount", codecForAmountString());
var codecForGetPlanForWithdrawRequest = codecForGetPlanForWalletInitiatedOperation().property("type", codecForConstString(TransactionType.Withdrawal)).property("exchangeUrl", codecOptional(codecForString())).build("GetPlanForWithdrawRequest");
var codecForGetPlanForDepositRequest = codecForGetPlanForWalletInitiatedOperation().property("type", codecForConstString(TransactionType.Deposit)).property("account", codecForString()).build("GetPlanForDepositRequest");
var codecForGetPlanForPushDebitRequest = codecForGetPlanForWalletInitiatedOperation().property("type", codecForConstString(TransactionType.PeerPushDebit)).build("GetPlanForPushDebitRequest");
var codecForGetPlanForPullCreditRequest = codecForGetPlanForWalletInitiatedOperation().property("type", codecForConstString(TransactionType.PeerPullCredit)).property("exchangeUrl", codecForString()).build("GetPlanForPullCreditRequest");
var codecForGetPlanForPaymentRequest = buildCodecForObject().property("type", codecForConstString(TransactionType.Payment)).property("maxDepositFee", codecForAmountString()).build("GetPlanForPaymentRequest");
var codecForGetPlanForPullDebitRequest = buildCodecForObject().property("type", codecForConstString(TransactionType.PeerPullDebit)).build("GetPlanForPullDebitRequest");
var codecForGetPlanForPushCreditRequest = buildCodecForObject().property("type", codecForConstString(TransactionType.PeerPushCredit)).build("GetPlanForPushCreditRequest");
var BalanceFlag;
(function(BalanceFlag2) {
  BalanceFlag2["IncomingKyc"] = "incoming-kyc";
  BalanceFlag2["IncomingAml"] = "incoming-aml";
  BalanceFlag2["IncomingConfirmation"] = "incoming-confirmation";
  BalanceFlag2["OutgoingKyc"] = "outgoing-kyc";
})(BalanceFlag || (BalanceFlag = {}));
var ScopeType;
(function(ScopeType2) {
  ScopeType2["Global"] = "global";
  ScopeType2["Exchange"] = "exchange";
  ScopeType2["Auditor"] = "auditor";
})(ScopeType || (ScopeType = {}));
var CoinStatus;
(function(CoinStatus2) {
  CoinStatus2["Fresh"] = "fresh";
  CoinStatus2["DenomLoss"] = "denom-loss";
  CoinStatus2["FreshSuspended"] = "fresh-suspended";
  CoinStatus2["Dormant"] = "dormant";
})(CoinStatus || (CoinStatus = {}));
var ConfirmPayResultType;
(function(ConfirmPayResultType2) {
  ConfirmPayResultType2["Done"] = "done";
  ConfirmPayResultType2["Pending"] = "pending";
})(ConfirmPayResultType || (ConfirmPayResultType = {}));
var codecForTalerErrorDetail = () => buildCodecForObject().property("code", codecForNumber()).property("when", codecOptional(codecForAbsoluteTime)).property("hint", codecOptional(codecForString())).build("TalerErrorDetail");
var PreparePayResultType;
(function(PreparePayResultType2) {
  PreparePayResultType2["PaymentPossible"] = "payment-possible";
  PreparePayResultType2["InsufficientBalance"] = "insufficient-balance";
  PreparePayResultType2["AlreadyConfirmed"] = "already-confirmed";
})(PreparePayResultType || (PreparePayResultType = {}));
var RefreshReason;
(function(RefreshReason2) {
  RefreshReason2["Manual"] = "manual";
  RefreshReason2["PayMerchant"] = "pay-merchant";
  RefreshReason2["PayDeposit"] = "pay-deposit";
  RefreshReason2["PayPeerPush"] = "pay-peer-push";
  RefreshReason2["PayPeerPull"] = "pay-peer-pull";
  RefreshReason2["Refund"] = "refund";
  RefreshReason2["AbortPay"] = "abort-pay";
  RefreshReason2["AbortDeposit"] = "abort-deposit";
  RefreshReason2["AbortPeerPushDebit"] = "abort-peer-push-debit";
  RefreshReason2["AbortPeerPullDebit"] = "abort-peer-pull-debit";
  RefreshReason2["Recoup"] = "recoup";
  RefreshReason2["BackupRestored"] = "backup-restored";
  RefreshReason2["Scheduled"] = "scheduled";
})(RefreshReason || (RefreshReason = {}));
var ExchangeTosStatus;
(function(ExchangeTosStatus2) {
  ExchangeTosStatus2["Pending"] = "pending";
  ExchangeTosStatus2["Proposed"] = "proposed";
  ExchangeTosStatus2["Accepted"] = "accepted";
  ExchangeTosStatus2["MissingTos"] = "missing-tos";
})(ExchangeTosStatus || (ExchangeTosStatus = {}));
var ExchangeEntryStatus;
(function(ExchangeEntryStatus2) {
  ExchangeEntryStatus2["Preset"] = "preset";
  ExchangeEntryStatus2["Ephemeral"] = "ephemeral";
  ExchangeEntryStatus2["Used"] = "used";
})(ExchangeEntryStatus || (ExchangeEntryStatus = {}));
var ExchangeUpdateStatus;
(function(ExchangeUpdateStatus2) {
  ExchangeUpdateStatus2["Initial"] = "initial";
  ExchangeUpdateStatus2["InitialUpdate"] = "initial-update";
  ExchangeUpdateStatus2["Suspended"] = "suspended";
  ExchangeUpdateStatus2["UnavailableUpdate"] = "unavailable-update";
  ExchangeUpdateStatus2["Ready"] = "ready";
  ExchangeUpdateStatus2["ReadyUpdate"] = "ready-update";
})(ExchangeUpdateStatus || (ExchangeUpdateStatus = {}));
var RecoveryMergeStrategy;
(function(RecoveryMergeStrategy2) {
  RecoveryMergeStrategy2["Ours"] = "ours";
  RecoveryMergeStrategy2["Theirs"] = "theirs";
})(RecoveryMergeStrategy || (RecoveryMergeStrategy = {}));
var AttentionPriority;
(function(AttentionPriority2) {
  AttentionPriority2["High"] = "high";
  AttentionPriority2["Medium"] = "medium";
  AttentionPriority2["Low"] = "low";
})(AttentionPriority || (AttentionPriority = {}));
var AttentionType;
(function(AttentionType2) {
  AttentionType2["KycWithdrawal"] = "kyc-withdrawal";
  AttentionType2["BackupUnpaid"] = "backup-unpaid";
  AttentionType2["BackupExpiresSoon"] = "backup-expires-soon";
  AttentionType2["MerchantRefund"] = "merchant-refund";
  AttentionType2["ExchangeTosChanged"] = "exchange-tos-changed";
  AttentionType2["ExchangeKeyExpired"] = "exchange-key-expired";
  AttentionType2["ExchangeKeyExpiresSoon"] = "exchange-key-expires-soon";
  AttentionType2["ExchangeDenominationsExpired"] = "exchange-denominations-expired";
  AttentionType2["ExchangeDenominationsExpiresSoon"] = "exchange-denominations-expires-soon";
  AttentionType2["AuditorTosChanged"] = "auditor-tos-changed";
  AttentionType2["AuditorKeyExpires"] = "auditor-key-expires";
  AttentionType2["AuditorDenominationsExpires"] = "auditor-denominations-expires";
  AttentionType2["PullPaymentPaid"] = "pull-payment-paid";
  AttentionType2["PushPaymentReceived"] = "push-payment-withdrawn";
})(AttentionType || (AttentionType = {}));
var UserAttentionPriority = {
  "kyc-withdrawal": AttentionPriority.Medium,
  "backup-unpaid": AttentionPriority.High,
  "backup-expires-soon": AttentionPriority.Medium,
  "merchant-refund": AttentionPriority.Medium,
  "exchange-tos-changed": AttentionPriority.Medium,
  "exchange-key-expired": AttentionPriority.High,
  "exchange-key-expires-soon": AttentionPriority.Medium,
  "exchange-denominations-expired": AttentionPriority.High,
  "exchange-denominations-expires-soon": AttentionPriority.Medium,
  "auditor-tos-changed": AttentionPriority.Medium,
  "auditor-key-expires": AttentionPriority.Medium,
  "auditor-denominations-expires": AttentionPriority.Medium,
  "pull-payment-paid": AttentionPriority.High,
  "push-payment-withdrawn": AttentionPriority.High
};
var ProviderPaymentType;
(function(ProviderPaymentType2) {
  ProviderPaymentType2["Unpaid"] = "unpaid";
  ProviderPaymentType2["Pending"] = "pending";
  ProviderPaymentType2["InsufficientBalance"] = "insufficient-balance";
  ProviderPaymentType2["Paid"] = "paid";
  ProviderPaymentType2["TermsChanged"] = "terms-changed";
})(ProviderPaymentType || (ProviderPaymentType = {}));

// ../taler-util/lib/http-client/bank-conversion.js
var TalerBankConversionCacheEviction;
(function(TalerBankConversionCacheEviction2) {
  TalerBankConversionCacheEviction2[TalerBankConversionCacheEviction2["UPDATE_RATE"] = 0] = "UPDATE_RATE";
})(TalerBankConversionCacheEviction || (TalerBankConversionCacheEviction = {}));

// ../taler-util/lib/http-client/bank-core.js
var TalerCoreBankCacheEviction;
(function(TalerCoreBankCacheEviction2) {
  TalerCoreBankCacheEviction2[TalerCoreBankCacheEviction2["DELETE_ACCOUNT"] = 0] = "DELETE_ACCOUNT";
  TalerCoreBankCacheEviction2[TalerCoreBankCacheEviction2["CREATE_ACCOUNT"] = 1] = "CREATE_ACCOUNT";
  TalerCoreBankCacheEviction2[TalerCoreBankCacheEviction2["UPDATE_ACCOUNT"] = 2] = "UPDATE_ACCOUNT";
  TalerCoreBankCacheEviction2[TalerCoreBankCacheEviction2["UPDATE_PASSWORD"] = 3] = "UPDATE_PASSWORD";
  TalerCoreBankCacheEviction2[TalerCoreBankCacheEviction2["CREATE_TRANSACTION"] = 4] = "CREATE_TRANSACTION";
  TalerCoreBankCacheEviction2[TalerCoreBankCacheEviction2["CONFIRM_WITHDRAWAL"] = 5] = "CONFIRM_WITHDRAWAL";
  TalerCoreBankCacheEviction2[TalerCoreBankCacheEviction2["ABORT_WITHDRAWAL"] = 6] = "ABORT_WITHDRAWAL";
  TalerCoreBankCacheEviction2[TalerCoreBankCacheEviction2["CREATE_WITHDRAWAL"] = 7] = "CREATE_WITHDRAWAL";
  TalerCoreBankCacheEviction2[TalerCoreBankCacheEviction2["CREATE_CASHOUT"] = 8] = "CREATE_CASHOUT";
})(TalerCoreBankCacheEviction || (TalerCoreBankCacheEviction = {}));

// ../taler-util/lib/http-client/bank-integration.js
var logger9 = new Logger("bank-integration.ts");
var TalerBankIntegrationHttpClient = class _TalerBankIntegrationHttpClient {
  constructor(baseUrl, httpClient) {
    this.baseUrl = baseUrl;
    this.PROTOCOL_VERSION = _TalerBankIntegrationHttpClient.PROTOCOL_VERSION;
    this.httpLib = httpClient ?? createPlatformHttpLib();
  }
  isCompatible(version) {
    const compare = LibtoolVersion.compare(this.PROTOCOL_VERSION, version);
    return compare?.compatible ?? false;
  }
  /**
   * https://docs.taler.net/core/api-bank-integration.html#get--config
   *
   */
  async getConfig() {
    const url = new URL(`config`, this.baseUrl);
    const resp = await this.httpLib.fetch(url.href, {
      method: "GET"
    });
    switch (resp.status) {
      case HttpStatusCode.Ok:
        return opSuccessFromHttp(resp, codecForIntegrationBankConfig());
      default:
        logger9.warn(`config request failed, status ${resp.status}`);
        return opUnknownFailure(resp, await readTalerErrorResponse(resp));
    }
  }
  /**
   * https://docs.taler.net/core/api-bank-integration.html#get--withdrawal-operation-$WITHDRAWAL_ID
   *
   */
  async getWithdrawalOperationById(woid, params) {
    const url = new URL(`withdrawal-operation/${woid}`, this.baseUrl);
    addLongPollingParam(url, params);
    if (params) {
      url.searchParams.set("old_state", !params.old_state ? "pending" : params.old_state);
    }
    const resp = await this.httpLib.fetch(url.href, {
      method: "GET"
    });
    switch (resp.status) {
      case HttpStatusCode.Ok:
        return opSuccessFromHttp(resp, codecForBankWithdrawalOperationStatus());
      case HttpStatusCode.NotFound:
        return opKnownHttpFailure(resp.status, resp);
      default:
        return opUnknownFailure(resp, await readTalerErrorResponse(resp));
    }
  }
  /**
   * https://docs.taler.net/core/api-bank-integration.html#post-$BANK_API_BASE_URL-withdrawal-operation-$wopid
   *
   */
  async completeWithdrawalOperationById(woid, body) {
    const url = new URL(`withdrawal-operation/${woid}`, this.baseUrl);
    const resp = await this.httpLib.fetch(url.href, {
      method: "POST",
      body
    });
    switch (resp.status) {
      case HttpStatusCode.Ok:
        return opSuccessFromHttp(resp, codecForBankWithdrawalOperationPostResponse());
      case HttpStatusCode.NotFound:
        return opKnownHttpFailure(resp.status, resp);
      case HttpStatusCode.Conflict: {
        const body2 = await readTalerErrorResponse(resp);
        const details = codecForTalerErrorDetail().decode(body2);
        switch (details.code) {
          case TalerErrorCode.BANK_WITHDRAWAL_OPERATION_RESERVE_SELECTION_CONFLICT:
            return opKnownTalerFailure(details.code, details);
          case TalerErrorCode.BANK_DUPLICATE_RESERVE_PUB_SUBJECT:
            return opKnownTalerFailure(details.code, details);
          case TalerErrorCode.BANK_UNKNOWN_ACCOUNT:
            return opKnownTalerFailure(details.code, details);
          case TalerErrorCode.BANK_ACCOUNT_IS_NOT_EXCHANGE:
            return opKnownTalerFailure(details.code, details);
          case TalerErrorCode.BANK_AMOUNT_DIFFERS:
            return opKnownTalerFailure(details.code, details);
          case TalerErrorCode.BANK_AMOUNT_REQUIRED:
            return opKnownTalerFailure(details.code, details);
          default:
            return opUnknownFailure(resp, details);
        }
      }
      default:
        return opUnknownFailure(resp, await readTalerErrorResponse(resp));
    }
  }
  /**
   * https://docs.taler.net/core/api-bank-integration.html#post-$BANK_API_BASE_URL-withdrawal-operation-$wopid
   *
   */
  async abortWithdrawalOperationById(woid) {
    const url = new URL(`withdrawal-operation/${woid}/abort`, this.baseUrl);
    const resp = await this.httpLib.fetch(url.href, {
      method: "POST"
    });
    switch (resp.status) {
      case HttpStatusCode.NoContent:
        return opEmptySuccess(resp);
      case HttpStatusCode.NotFound:
        return opKnownHttpFailure(resp.status, resp);
      case HttpStatusCode.Conflict:
        return opKnownHttpFailure(resp.status, resp);
      default:
        return opUnknownFailure(resp, await readTalerErrorResponse(resp));
    }
  }
};
TalerBankIntegrationHttpClient.PROTOCOL_VERSION = "2:0:1";

// ../taler-util/lib/http-client/challenger.js
var ChallengerCacheEviction;
(function(ChallengerCacheEviction2) {
  ChallengerCacheEviction2[ChallengerCacheEviction2["CREATE_CHALLENGE"] = 0] = "CREATE_CHALLENGE";
  ChallengerCacheEviction2[ChallengerCacheEviction2["SOLVE_CHALLENGE"] = 1] = "SOLVE_CHALLENGE";
})(ChallengerCacheEviction || (ChallengerCacheEviction = {}));

// ../taler-util/lib/http-client/exchange.js
var TalerExchangeCacheEviction;
(function(TalerExchangeCacheEviction2) {
  TalerExchangeCacheEviction2[TalerExchangeCacheEviction2["CREATE_DESCISION"] = 0] = "CREATE_DESCISION";
})(TalerExchangeCacheEviction || (TalerExchangeCacheEviction = {}));

// ../taler-util/lib/http-client/merchant.js
var TalerMerchantInstanceCacheEviction;
(function(TalerMerchantInstanceCacheEviction2) {
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["CREATE_ORDER"] = 0] = "CREATE_ORDER";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["UPDATE_ORDER"] = 1] = "UPDATE_ORDER";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["DELETE_ORDER"] = 2] = "DELETE_ORDER";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["UPDATE_CURRENT_INSTANCE"] = 3] = "UPDATE_CURRENT_INSTANCE";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["DELETE_CURRENT_INSTANCE"] = 4] = "DELETE_CURRENT_INSTANCE";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["CREATE_BANK_ACCOUNT"] = 5] = "CREATE_BANK_ACCOUNT";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["UPDATE_BANK_ACCOUNT"] = 6] = "UPDATE_BANK_ACCOUNT";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["DELETE_BANK_ACCOUNT"] = 7] = "DELETE_BANK_ACCOUNT";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["CREATE_PRODUCT"] = 8] = "CREATE_PRODUCT";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["UPDATE_PRODUCT"] = 9] = "UPDATE_PRODUCT";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["DELETE_PRODUCT"] = 10] = "DELETE_PRODUCT";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["CREATE_TRANSFER"] = 11] = "CREATE_TRANSFER";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["DELETE_TRANSFER"] = 12] = "DELETE_TRANSFER";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["CREATE_DEVICE"] = 13] = "CREATE_DEVICE";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["UPDATE_DEVICE"] = 14] = "UPDATE_DEVICE";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["DELETE_DEVICE"] = 15] = "DELETE_DEVICE";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["CREATE_TEMPLATE"] = 16] = "CREATE_TEMPLATE";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["UPDATE_TEMPLATE"] = 17] = "UPDATE_TEMPLATE";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["DELETE_TEMPLATE"] = 18] = "DELETE_TEMPLATE";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["CREATE_WEBHOOK"] = 19] = "CREATE_WEBHOOK";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["UPDATE_WEBHOOK"] = 20] = "UPDATE_WEBHOOK";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["DELETE_WEBHOOK"] = 21] = "DELETE_WEBHOOK";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["CREATE_TOKENFAMILY"] = 22] = "CREATE_TOKENFAMILY";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["UPDATE_TOKENFAMILY"] = 23] = "UPDATE_TOKENFAMILY";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["DELETE_TOKENFAMILY"] = 24] = "DELETE_TOKENFAMILY";
  TalerMerchantInstanceCacheEviction2[TalerMerchantInstanceCacheEviction2["LAST"] = 25] = "LAST";
})(TalerMerchantInstanceCacheEviction || (TalerMerchantInstanceCacheEviction = {}));
var TalerMerchantManagementCacheEviction;
(function(TalerMerchantManagementCacheEviction2) {
  TalerMerchantManagementCacheEviction2[TalerMerchantManagementCacheEviction2["CREATE_INSTANCE"] = 26] = "CREATE_INSTANCE";
  TalerMerchantManagementCacheEviction2[TalerMerchantManagementCacheEviction2["UPDATE_INSTANCE"] = 27] = "UPDATE_INSTANCE";
  TalerMerchantManagementCacheEviction2[TalerMerchantManagementCacheEviction2["DELETE_INSTANCE"] = 28] = "DELETE_INSTANCE";
})(TalerMerchantManagementCacheEviction || (TalerMerchantManagementCacheEviction = {}));

// ../taler-util/lib/i18n.js
var jedLib = __toESM(require_jed(), 1);
var logger10 = new Logger("i18n/index.ts");
var jed = void 0;
function setupI18n(lang, strings2) {
  lang = lang.replace("_", "-");
  if (!strings2[lang]) {
    strings2[lang] = {};
  }
  jed = new jedLib.Jed(strings2[lang]);
}
function toI18nString(stringSeq) {
  let s4 = "";
  for (let i4 = 0; i4 < stringSeq.length; i4++) {
    s4 += stringSeq[i4];
    if (i4 < stringSeq.length - 1) {
      s4 += `%${i4 + 1}$s`;
    }
  }
  return s4;
}
function singular(stringSeq, ...values) {
  const s4 = toI18nString(stringSeq);
  const tr = jed.translate(s4).ifPlural(1, s4).fetch(...values);
  return tr;
}
function translate(stringSeq, ...values) {
  const s4 = toI18nString(stringSeq);
  if (!s4)
    return [];
  const translation = jed.ngettext(s4, s4, 1);
  return replacePlaceholderWithValues(translation, values);
}
function Translate({ children, debug }) {
  const c4 = [].concat(children);
  const s4 = stringifyArray(c4);
  if (!s4)
    return [];
  const translation = jed.ngettext(s4, s4, 1);
  if (debug) {
    console.log("looking for ", s4, "got", translation);
  }
  return replacePlaceholderWithValues(translation, c4);
}
function replacePlaceholderWithValues(translation, childArray) {
  const tr = translation.split(/%(\d+)\$s/);
  const placeholderChildren = [];
  for (let i4 = 0; i4 < childArray.length; i4++) {
    const x3 = childArray[i4];
    if (x3 === void 0) {
      continue;
    } else if (typeof x3 === "string") {
      continue;
    } else {
      placeholderChildren.push(x3);
    }
  }
  const result = [];
  for (let i4 = 0; i4 < tr.length; i4++) {
    if (i4 % 2 == 0) {
      result.push(tr[i4]);
    } else {
      const childIdx = Number.parseInt(tr[i4]) - 1;
      result.push(placeholderChildren[childIdx]);
    }
  }
  return result;
}
function stringifyArray(children) {
  let n3 = 1;
  const ss = children.map((c4) => {
    if (typeof c4 === "string") {
      return c4;
    }
    return `%${n3++}$s`;
  });
  const s4 = ss.join("").replace(/ +/g, " ").trim();
  return s4;
}
var i18n = {
  str: singular,
  singular,
  Translate,
  translate
};

// ../taler-util/lib/iban.js
var ccZero = "0".charCodeAt(0);
var ccNine = "9".charCodeAt(0);
var ccA = "A".charCodeAt(0);
var ccZ = "Z".charCodeAt(0);

// ../taler-util/lib/notifications.js
var NotificationType;
(function(NotificationType2) {
  NotificationType2["BalanceChange"] = "balance-change";
  NotificationType2["BackupOperationError"] = "backup-error";
  NotificationType2["TransactionStateTransition"] = "transaction-state-transition";
  NotificationType2["WithdrawalOperationTransition"] = "withdrawal-operation-transition";
  NotificationType2["ExchangeStateTransition"] = "exchange-state-transition";
  NotificationType2["Idle"] = "idle";
  NotificationType2["TaskObservabilityEvent"] = "task-observability-event";
  NotificationType2["RequestObservabilityEvent"] = "request-observability-event";
})(NotificationType || (NotificationType = {}));
var ObservabilityEventType;
(function(ObservabilityEventType2) {
  ObservabilityEventType2["HttpFetchStart"] = "http-fetch-start";
  ObservabilityEventType2["HttpFetchFinishError"] = "http-fetch-finish-error";
  ObservabilityEventType2["HttpFetchFinishSuccess"] = "http-fetch-finish-success";
  ObservabilityEventType2["DbQueryStart"] = "db-query-start";
  ObservabilityEventType2["DbQueryFinishSuccess"] = "db-query-finish-success";
  ObservabilityEventType2["DbQueryFinishError"] = "db-query-finish-error";
  ObservabilityEventType2["RequestStart"] = "request-start";
  ObservabilityEventType2["RequestFinishSuccess"] = "request-finish-success";
  ObservabilityEventType2["RequestFinishError"] = "request-finish-error";
  ObservabilityEventType2["TaskStart"] = "task-start";
  ObservabilityEventType2["TaskStop"] = "task-stop";
  ObservabilityEventType2["TaskReset"] = "task-reset";
  ObservabilityEventType2["ShepherdTaskResult"] = "shepherd-task-result";
  ObservabilityEventType2["DeclareTaskDependency"] = "declare-task-dependency";
  ObservabilityEventType2["CryptoStart"] = "crypto-start";
  ObservabilityEventType2["CryptoFinishSuccess"] = "crypto-finish-success";
  ObservabilityEventType2["CryptoFinishError"] = "crypto-finish-error";
  ObservabilityEventType2["Message"] = "message";
  ObservabilityEventType2["DeclareConcernsTransaction"] = "declare-concerns-transaction";
})(ObservabilityEventType || (ObservabilityEventType = {}));

// ../taler-util/lib/timer.js
var logger11 = new Logger("timer.ts");
var IntervalHandle = class {
  constructor(h4) {
    this.h = h4;
  }
  clear() {
    clearInterval(this.h);
  }
  /**
   * Make sure the event loop exits when the timer is the
   * only event left.  Has no effect in the browser.
   */
  unref() {
    if (typeof this.h === "object" && "unref" in this.h) {
      this.h.unref();
    }
  }
};
var TimeoutHandle = class {
  constructor(h4) {
    this.h = h4;
  }
  clear() {
    clearTimeout(this.h);
  }
  /**
   * Make sure the event loop exits when the timer is the
   * only event left.  Has no effect in the browser.
   */
  unref() {
    if (typeof this.h === "object" && "unref" in this.h) {
      this.h.unref();
    }
  }
};
var performanceNow = (() => {
  if (typeof process !== "undefined" && process.hrtime) {
    return () => {
      return process.hrtime.bigint();
    };
  }
  if (typeof performance !== "undefined") {
    return () => BigInt(Math.floor(performance.now() * 1e3)) * BigInt(1e3);
  }
  return () => BigInt((/* @__PURE__ */ new Date()).getTime()) * BigInt(1e3) * BigInt(1e3);
})();
var SetTimeoutTimerAPI = class {
  /**
   * Call a function every time the delay given in milliseconds passes.
   */
  every(delayMs, callback) {
    return new IntervalHandle(setInterval(callback, delayMs));
  }
  /**
   * Call a function after the delay given in milliseconds passes.
   */
  after(delayMs, callback) {
    return new TimeoutHandle(setTimeout(callback, delayMs));
  }
};
var timer = new SetTimeoutTimerAPI();

// ../taler-util/lib/transaction-test-data.js
var sampleWalletCoreTransactions = [
  {
    type: TransactionType.Payment,
    txState: {
      major: TransactionMajorState.Done
    },
    amountRaw: "KUDOS:10",
    amountEffective: "KUDOS:10",
    totalRefundRaw: "KUDOS:0",
    totalRefundEffective: "KUDOS:0",
    status: PaymentStatus.Paid,
    refundPending: void 0,
    posConfirmation: void 0,
    pending: false,
    refunds: [],
    timestamp: {
      t_s: 1677166045
    },
    transactionId: "txn:payment:NRRD9KJ8970P5HDAGPW1MBA6HZHB1XMFKF5M3CNR6WA0GT98DHY0",
    proposalId: "NRRD9KJ8970P5HDAGPW1MBA6HZHB1XMFKF5M3CNR6WA0GT98DHY0",
    info: {
      merchant: {
        name: "woocommerce",
        website: "woocommerce.demo.taler.net",
        email: "foo@example.com",
        address: {},
        jurisdiction: {}
      },
      orderId: "wc_order_KQCRldghIgDRB-100",
      products: [
        {
          description: "Using GCC",
          quantity: 1,
          price: "KUDOS:10",
          product_id: "28"
        }
      ],
      summary: "WooTalerShop #100",
      contractTermsHash: "A02E1M6ARWKBJ87K2TV4S6WQ4X5YH7BRVR6MYCHCTVAED8MBXTFD6PZ5Q50Y7Z5K18PYBTDA14NQ56XPC1VCQW1EVRWTSB7ZYT65B5G",
      fulfillmentUrl: "https://woocommerce.demo.taler.net/?wc-api=wc_gnutaler_gateway&order_id=wc_order_KQCRldghIgDRB-100"
    },
    refundQueryActive: false,
    frozen: false
  },
  {
    type: TransactionType.Refresh,
    txState: {
      major: TransactionMajorState.Pending
    },
    refreshReason: RefreshReason.PayMerchant,
    amountEffective: "KUDOS:0",
    amountRaw: "KUDOS:0",
    refreshInputAmount: "KUDOS:1.5",
    refreshOutputAmount: "KUDOS:1.4",
    originatingTransactionId: "txn:proposal:ZCGBZFE8KZ1CBYYGSC3ZC8E40KVJWV16VYCTHGC8FFSVZ5HD24BG",
    pending: true,
    timestamp: {
      t_s: 1681376214
    },
    transactionId: "txn:refresh:QQSWHHXCRQ269G0E3RW14JMC6F7NFDYDW26NSFHRTXSKDS6CMCZ0",
    frozen: false,
    error: {
      code: 7029,
      when: {
        t_ms: 1681376473665
      },
      hint: "Error (WALLET_REFRESH_GROUP_INCOMPLETE)",
      numErrors: 1,
      errors: [
        {
          code: 7001,
          when: {
            t_ms: 1681376473189
          },
          hint: "unexpected exception (message: exchange wire fee signature invalid)",
          stack: "    at validateWireInfo (../taler-wallet-core-qjs.mjs:23166)\n"
        }
      ]
    }
  }
];

// ../taler-util/lib/index.browser.js
loadBrowserPrng();

// src/context/translation.ts
init_preact_module();

// ../../node_modules/.pnpm/preact@10.11.3/node_modules/preact/hooks/dist/hooks.module.js
init_preact_module();
var t2;
var r2;
var u2;
var i2;
var o2 = 0;
var f2 = [];
var c2 = [];
var e2 = l.__b;
var a2 = l.__r;
var v2 = l.diffed;
var l2 = l.__c;
var m2 = l.unmount;
function d2(t4, u4) {
  l.__h && l.__h(r2, t4, o2 || u4), o2 = 0;
  var i4 = r2.__H || (r2.__H = { __: [], __h: [] });
  return t4 >= i4.__.length && i4.__.push({ __V: c2 }), i4.__[t4];
}
function p3(n3) {
  return o2 = 1, y2(B2, n3);
}
function y2(n3, u4, i4) {
  var o4 = d2(t2++, 2);
  if (o4.t = n3, !o4.__c && (o4.__ = [i4 ? i4(u4) : B2(void 0, u4), function(n4) {
    var t4 = o4.__N ? o4.__N[0] : o4.__[0], r4 = o4.t(t4, n4);
    t4 !== r4 && (o4.__N = [r4, o4.__[1]], o4.__c.setState({}));
  }], o4.__c = r2, !r2.u)) {
    r2.u = true;
    var f4 = r2.shouldComponentUpdate;
    r2.shouldComponentUpdate = function(n4, t4, r4) {
      if (!o4.__c.__H)
        return true;
      var u5 = o4.__c.__H.__.filter(function(n5) {
        return n5.__c;
      });
      if (u5.every(function(n5) {
        return !n5.__N;
      }))
        return !f4 || f4.call(this, n4, t4, r4);
      var i5 = false;
      return u5.forEach(function(n5) {
        if (n5.__N) {
          var t5 = n5.__[0];
          n5.__ = n5.__N, n5.__N = void 0, t5 !== n5.__[0] && (i5 = true);
        }
      }), !(!i5 && o4.__c.props === n4) && (!f4 || f4.call(this, n4, t4, r4));
    };
  }
  return o4.__N || o4.__;
}
function h2(u4, i4) {
  var o4 = d2(t2++, 3);
  !l.__s && z2(o4.__H, i4) && (o4.__ = u4, o4.i = i4, r2.__H.__h.push(o4));
}
function s2(u4, i4) {
  var o4 = d2(t2++, 4);
  !l.__s && z2(o4.__H, i4) && (o4.__ = u4, o4.i = i4, r2.__h.push(o4));
}
function _2(n3) {
  return o2 = 5, F(function() {
    return { current: n3 };
  }, []);
}
function F(n3, r4) {
  var u4 = d2(t2++, 7);
  return z2(u4.__H, r4) ? (u4.__V = n3(), u4.i = r4, u4.__h = n3, u4.__V) : u4.__;
}
function T2(n3, t4) {
  return o2 = 8, F(function() {
    return n3;
  }, t4);
}
function q2(n3) {
  var u4 = r2.context[n3.__c], i4 = d2(t2++, 9);
  return i4.c = n3, u4 ? (null == i4.__ && (i4.__ = true, u4.sub(r2)), u4.props.value) : n3.__;
}
function P2(n3) {
  var u4 = d2(t2++, 10), i4 = p3();
  return u4.__ = n3, r2.componentDidCatch || (r2.componentDidCatch = function(n4, t4) {
    u4.__ && u4.__(n4, t4), i4[1](n4);
  }), [i4[0], function() {
    i4[1](void 0);
  }];
}
function b2() {
  for (var t4; t4 = f2.shift(); )
    if (t4.__P && t4.__H)
      try {
        t4.__H.__h.forEach(k2), t4.__H.__h.forEach(w2), t4.__H.__h = [];
      } catch (r4) {
        t4.__H.__h = [], l.__e(r4, t4.__v);
      }
}
l.__b = function(n3) {
  r2 = null, e2 && e2(n3);
}, l.__r = function(n3) {
  a2 && a2(n3), t2 = 0;
  var i4 = (r2 = n3.__c).__H;
  i4 && (u2 === r2 ? (i4.__h = [], r2.__h = [], i4.__.forEach(function(n4) {
    n4.__N && (n4.__ = n4.__N), n4.__V = c2, n4.__N = n4.i = void 0;
  })) : (i4.__h.forEach(k2), i4.__h.forEach(w2), i4.__h = [])), u2 = r2;
}, l.diffed = function(t4) {
  v2 && v2(t4);
  var o4 = t4.__c;
  o4 && o4.__H && (o4.__H.__h.length && (1 !== f2.push(o4) && i2 === l.requestAnimationFrame || ((i2 = l.requestAnimationFrame) || j2)(b2)), o4.__H.__.forEach(function(n3) {
    n3.i && (n3.__H = n3.i), n3.__V !== c2 && (n3.__ = n3.__V), n3.i = void 0, n3.__V = c2;
  })), u2 = r2 = null;
}, l.__c = function(t4, r4) {
  r4.some(function(t5) {
    try {
      t5.__h.forEach(k2), t5.__h = t5.__h.filter(function(n3) {
        return !n3.__ || w2(n3);
      });
    } catch (u4) {
      r4.some(function(n3) {
        n3.__h && (n3.__h = []);
      }), r4 = [], l.__e(u4, t5.__v);
    }
  }), l2 && l2(t4, r4);
}, l.unmount = function(t4) {
  m2 && m2(t4);
  var r4, u4 = t4.__c;
  u4 && u4.__H && (u4.__H.__.forEach(function(n3) {
    try {
      k2(n3);
    } catch (n4) {
      r4 = n4;
    }
  }), u4.__H = void 0, r4 && l.__e(r4, u4.__v));
};
var g2 = "function" == typeof requestAnimationFrame;
function j2(n3) {
  var t4, r4 = function() {
    clearTimeout(u4), g2 && cancelAnimationFrame(t4), setTimeout(n3);
  }, u4 = setTimeout(r4, 100);
  g2 && (t4 = requestAnimationFrame(r4));
}
function k2(n3) {
  var t4 = r2, u4 = n3.__c;
  "function" == typeof u4 && (n3.__c = void 0, u4()), r2 = t4;
}
function w2(n3) {
  var t4 = r2;
  n3.__c = n3.__(), r2 = t4;
}
function z2(n3, t4) {
  return !n3 || n3.length !== t4.length || t4.some(function(t5, r4) {
    return t5 !== n3[r4];
  });
}
function B2(n3, t4) {
  return "function" == typeof t4 ? t4(n3) : t4;
}

// src/hooks/useLocalStorage.ts
function useNotNullLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = p3(() => {
    return typeof window !== "undefined" ? window.localStorage.getItem(key) || initialValue : initialValue;
  });
  const setValue = (value) => {
    const valueToStore = value instanceof Function ? value(storedValue) : value;
    setStoredValue(valueToStore);
    if (typeof window !== "undefined") {
      if (!valueToStore) {
        window.localStorage.removeItem(key);
      } else {
        window.localStorage.setItem(key, valueToStore);
      }
    }
  };
  const isSaved = window.localStorage.getItem(key) !== null;
  return [storedValue, setValue, isSaved];
}

// src/hooks/useLang.ts
function getBrowserLang() {
  if (window.navigator.languages)
    return window.navigator.languages[0];
  if (window.navigator.language)
    return window.navigator.language;
  return void 0;
}
function useLang(initial3) {
  const defaultLang = (getBrowserLang() || initial3 || "en").substring(0, 2);
  return useNotNullLocalStorage("lang-preference", defaultLang);
}

// src/i18n/strings.ts
var strings = {};
strings["de"] = {
  domain: "messages",
  locale_data: {
    messages: {
      "": {
        domain: "messages",
        plural_forms: "nplurals=2; plural=(n != 1);",
        lang: ""
      }
    }
  }
};
strings["en"] = {
  domain: "messages",
  locale_data: {
    messages: {
      "": {
        domain: "messages",
        plural_forms: "nplurals=2; plural=(n != 1);",
        lang: ""
      }
    }
  }
};

// src/context/translation.ts
var supportedLang = {
  es: "Espa\xF1ol [es]",
  ja: "\u65E5\u672C\u8A9E [ja]",
  en: "English [en]",
  fr: "Fran\xE7ais [fr]",
  de: "Deutsch [de]",
  sv: "Svenska [sv]",
  it: "Italiano [it]",
  // ko: "한국어 [ko]",
  // ru: "Ру́сский язы́к [ru]",
  tr: "T\xFCrk [tr]",
  navigator: "Defined by navigator"
};
var initial = {
  lang: "en",
  supportedLang,
  changeLanguage: () => {
  },
  i18n,
  isSaved: false
};
var Context = B(initial);
var TranslationProvider = ({
  initial: initial3,
  children,
  forceLang
}) => {
  const [lang, changeLanguage, isSaved] = useLang(initial3);
  h2(() => {
    if (forceLang) {
      changeLanguage(forceLang);
    }
  });
  h2(() => {
    setupI18n(lang, strings);
  }, [lang]);
  if (forceLang) {
    setupI18n(forceLang, strings);
  } else {
    setupI18n(lang, strings);
  }
  return h(Context.Provider, {
    value: { lang, changeLanguage, supportedLang, i18n, isSaved },
    children
  });
};
var useTranslationContext = () => q2(Context);

// ../anastasis-core/lib/anastasis-data.js
var anastasisData = {
  providersList: {
    license: "GPLv3+",
    "SPDX-License-Identifier": "GPL3.0-or-later",
    anastasis_provider: [
      {
        url: "https://v1.anastasis.taler.net/",
        name: "Bern University of Applied Sciences, Switzerland"
      },
      //      {
      //        url: "https://v1.anastasis.codeblau.de/",
      //        name: "Codeblau GmbH, Germany",
      //      },
      {
        url: "https://v1.anastasis.lu/",
        name: "Anastasis SARL, Luxembourg"
      },
      {
        url: "https://v1.anastasis.taler.net/",
        restricted: "xx"
      },
      {
        url: "https://v1.anastasis.lu/",
        restricted: "xx"
      }
      // {
      //   url: "http://localhost:8086/",
      //   restricted: "xx",
      // },
      // {
      //   url: "http://localhost:8087/",
      //   restricted: "xx",
      // },
      // {
      //   url: "http://localhost:8088/",
      //   restricted: "xx",
      // },
      // {
      //   url: "http://localhost:8089/",
      //   restricted: "xx",
      // },
    ]
  },
  countriesList: {
    license: "GPLv3+",
    "SPDX-License-Identifier": "GPL3.0-or-later",
    countries: [
      {
        code: "al",
        name: "Albania",
        continent: "Europe",
        name_i18n: {
          de_DE: "Albanien",
          en_UK: "Albania"
        },
        call_code: "+355"
      },
      {
        code: "be",
        name: "Belgium",
        continent: "Europe",
        name_i18n: {
          de_DE: "Belgien",
          en_UK: "Belgium"
        },
        call_code: "+32"
      },
      {
        code: "ch",
        name: "Switzerland",
        continent: "Europe",
        name_i18n: {
          de_DE: "Schweiz",
          de_CH: "Schwiiz",
          fr_FR: "Suisse",
          en_UK: "Swiss"
        },
        call_code: "+41"
      },
      {
        code: "cz",
        name: "Czech Republic",
        continent: "Europe",
        name_i18n: {
          en_UK: "Czech Republic"
        },
        call_code: "+420"
      },
      {
        code: "de",
        name: "Germany",
        continent: "Europe",
        continent_i18n: { de_DE: "Europa" },
        name_i18n: {
          de_DE: "Deutschland",
          de_CH: "Deutschland",
          fr_FR: "Allemagne",
          en_UK: "Germany"
        },
        call_code: "+49"
      },
      {
        code: "dk",
        name: "Denmark",
        continent: "Europe",
        continent_i18n: { de_DE: "Europa" },
        name_i18n: {
          en_UK: "Denmark"
        },
        call_code: "+45"
      },
      {
        code: "es",
        name: "Spain",
        continent: "Europe",
        continent_i18n: { es_ES: "Europa" },
        name_i18n: {
          es_ES: "Espa\xF1a"
        },
        call_code: "+44"
      },
      {
        code: "fr",
        name: "France",
        continent: "Europe",
        name_i18n: {
          de_DE: "Frankreich",
          fr_FR: "La France"
        },
        call_code: "+33"
      },
      {
        code: "in",
        name: "India",
        continent: "India",
        continent_i18n: { en_EN: "India" },
        name_i18n: {
          de_DE: "Indien",
          de_CH: "Indien",
          fr_FR: "l'Inde",
          en_UK: "India"
        },
        call_code: "+91"
      },
      {
        code: "it",
        name: "Italy",
        continent: "Europe",
        name_i18n: {
          de_DE: "Italien",
          en_UK: "Italy"
        },
        call_code: "+39"
      },
      {
        code: "jp",
        name: "Japan",
        continent: "Asia",
        continent_i18n: { en_EN: "Japan" },
        name_i18n: {
          de_DE: "Japan",
          de_CH: "Japan",
          en_UK: "Japan"
        },
        call_code: "+81"
      },
      {
        code: "nl",
        name: "Netherlands",
        continent: "Europe",
        name_i18n: {
          de_DE: "Niederlande",
          nl_NL: "Nederland",
          en_UK: "Netherlands"
        },
        call_code: "+31"
      },
      {
        code: "sk",
        name: "Slovakia",
        continent: "Europe",
        name_i18n: {
          en_UK: "Slovakia"
        },
        call_code: "+421"
      },
      {
        code: "us",
        name: "United States of America (USA)",
        continent: "North America",
        continent_i18n: { de_DE: "Nordamerika" },
        name_i18n: {
          de_DE: "Vereinigte Staaten von Amerika (USA)",
          de_CH: "Vereinigte Staaten von Amerika (USA)",
          fr_FR: "\xC9tats-Unis d'Am\xE9rique (USA)",
          en_UK: "United States of America (USA)"
        },
        call_code: "+1"
      }
      // {
      //   code: "xx",
      //   name: "Testland",
      //   continent: "Demoworld",
      //   name_i18n: {
      //     de_DE: "Testlandt",
      //     de_CH: "Testlandi",
      //     fr_FR: "Testpais",
      //     en_UK: "Testland",
      //   },
      //   call_code: "+00",
      // },
    ].sort((a4, b4) => a4.name > b4.name ? 1 : a4.name < b4.name ? -1 : 0)
  },
  countryDetails: {
    al: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "nid_number",
          label: "Numri i Identitetit",
          label_i18n: {
            en: "Identity Number",
            al: "Numri i Identitetit"
          },
          widget: "anastasis_gtk_ia_nid_al",
          uuid: "256e5d30-d65e-481b-9ac4-55f5ac03b24a",
          "validation-regex": "^[0-9A-T][0-9](((0|5)[0-9])|10|11|51|52)[0-9]{3}[A-W]$",
          "validation-logic": "AL_NID_check"
        }
      ]
    },
    be: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "date",
          name: "birthdate",
          label: "Birthdate",
          widget: "anastasis_gtk_ia_birthdate",
          uuid: "83d655c7-bdb6-484d-904e-80c1058c8854"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "nrn_number",
          label: "National Register Number",
          label_i18n: {
            en: "National Register Number"
          },
          widget: "anastasis_gtk_ia_nid_be",
          uuid: "0452f99a-06f7-48bd-8ac0-2e4ed9a24560",
          "validation-regex": "^[0-9]{11}$",
          "validation-logic": "BE_NRN_check"
        }
      ]
    },
    ch: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "date",
          name: "birthdate",
          label: "Birthdate",
          widget: "anastasis_gtk_ia_birthdate",
          uuid: "83d655c7-bdb6-484d-904e-80c1058c8854"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "ahv_number",
          label: "AHV number",
          label_i18n: {
            de_DE: "AHV-Nummer",
            de_CH: "AHV-Nummer"
          },
          widget: "anastasis_gtk_ia_ahv",
          uuid: "1da87570-ba16-4f62-8a7e-cbda92f51591",
          "validation-regex": "^(756)\\.[0-9]{4}\\.[0-9]{4}\\.[0-9]{2}|(756)[0-9]{10}$",
          "validation-logic": "CH_AHV_check",
          autocomplete: "???.????.????.??"
        }
      ]
    },
    cz: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "birth_number",
          label: "Birth Number",
          label_i18n: {
            en: "Birth Number",
            cz: "rodn\xE9 \u010D\xEDslo"
          },
          widget: "anastasis_gtk_ia_birthnumber_cz",
          uuid: "03e3a05b-1192-44f1-ac36-7425512eee1a",
          "validation-regex": "^[0-9]{2}(((0|2|5|7)[0-9])|10|11|31|32|51|52|81|82)/[0-9]{3}[0-9]?$",
          "validation-logic": "CZ_BN_check"
        }
      ]
    },
    de: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "date",
          name: "birthdate",
          label: "Birthdate",
          widget: "anastasis_gtk_ia_birthdate",
          uuid: "83d655c7-bdb6-484d-904e-80c1058c8854"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "social_security_number",
          label: "Social security number",
          label_i18n: {
            de_DE: "Deutsche Sozialversicherungsnummer",
            en: "German Social security number"
          },
          widget: "anastasis_gtk_ia_ssn_de",
          uuid: "d5e2aa79-1c88-4cf4-a4d2-252508b38e05",
          "validation-regex": "^[0-9]{8}[[:upper:]][0-9]{3}$",
          "validation-logic": "DE_SVN_check",
          optional: true
        },
        {
          type: "string",
          name: "tax_number",
          label: "Taxpayer identification number",
          label_i18n: {
            de_DE: "Steuerliche Identifikationsnummer",
            en: "German taxpayer identification number"
          },
          widget: "anastasis_gtk_ia_tin_de",
          uuid: "dae48f85-e3ff-47a4-a4a3-ed981ed8c3c6",
          "validation-regex": "^[0-9]{11}$",
          "validation-logic": "DE_TIN_check"
        }
      ]
    },
    dk: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "cpr_number",
          label: "CPR-nummer",
          label_i18n: {
            en: "CPR Number",
            dk: "CPR-nummer"
          },
          widget: "anastasis_gtk_ia_cpr_dk",
          uuid: "38f13a4d-4302-4ada-ada1-c3ff4a8ff689",
          "validation-regex": "^(0[1-9]|[1-2][0-9]|30|31)((0[1-9]|10|11|12))[0-9]{2}-[0-9A-Z]{4}$"
        }
      ]
    },
    es: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "date",
          name: "birthdate",
          label: "Birthdate",
          widget: "anastasis_gtk_ia_birthdate",
          uuid: "83d655c7-bdb6-484d-904e-80c1058c8854"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "tax_number",
          label: "Tax number",
          label_i18n: {
            es_ES: "N\xFAmero de Identificaci\xF3n Fiscal (DNI, NIE)"
          },
          widget: "anastasis_gtk_ia_es_dni",
          uuid: "ac8bd865-6be8-445c-b650-6a18eef16a49",
          "validation-regex": "^[0-9MXYZ][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$",
          "validation-logic": "ES_DNI_check"
        },
        {
          type: "string",
          name: "ssn_number",
          label: "Social security number",
          label_i18n: {
            es_ES: "N\xFAmero de Seguridad Social"
          },
          widget: "anastasis_gtk_ia_es_ssn",
          uuid: "22396a19-f3bb-497e-b63a-961fd639140e",
          "validation-regex": "^[0-9]{11}$"
        }
      ]
    },
    fr: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "date",
          name: "birthdate",
          label: "Birthdate",
          widget: "anastasis_gtk_ia_birthdate",
          uuid: "83d655c7-bdb6-484d-904e-80c1058c8854"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "social_security_number",
          label: "Code Insee",
          label_i18n: {
            fr_FR: "Code Insee",
            en: "INSEE code"
          },
          widget: "anastasis_gtk_ia_insee_fr",
          uuid: "2f36a81c-3f6d-41f3-97ee-9c885bc41873",
          "validation-regex": "^[0-9]{15}$",
          "validation-logic": "FR_INSEE_check"
        }
      ]
    },
    in: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "date",
          name: "birthdate",
          label: "Birthdate",
          widget: "anastasis_gtk_ia_birthdate",
          uuid: "83d655c7-bdb6-484d-904e-80c1058c8854"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "aadhar_number",
          label: "Aadhar number",
          label_i18n: {
            en: "Aadhar number"
          },
          widget: "anastasis_gtk_ia_aadhar_in",
          uuid: "55afe97a-98bc-48d1-bb37-a9658be3fdc9",
          "validation-regex": "^[2-9]{1}[0-9]{3}\\s[0-9]{4}\\s[0-9]{4}$",
          "validation-logic": "IN_AADHAR_check"
        }
      ]
    },
    it: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "fiscal_code",
          label: "Codice fiscale",
          label_i18n: {
            it: "Codice fiscale",
            en: "Fiscal code"
          },
          widget: "anastasis_gtk_ia_cf_it",
          uuid: "88f53c51-52ad-4d63-a163-ec042589f925",
          "validation-regex": "^[[:upper:]]{6}[0-9]{2}[A-EHLMPRT](([0-24-6][0-9])|(30|31|70|71))[A-MZ][0-9]{3}[A-Z]$",
          "validation-logic": "IT_CF_check"
        }
      ]
    },
    jp: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "date",
          name: "birthdate",
          label: "Birthdate",
          widget: "anastasis_gtk_ia_birthdate",
          uuid: "83d655c7-bdb6-484d-904e-80c1058c8854"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "my_number",
          label: "My number",
          label_i18n: {
            en: "My number",
            jp: "\u30DE\u30A4\u30CA\u30F3\u30D0\u30FC"
          },
          widget: "anastasis_gtk_ia_my_jp",
          uuid: "90848f42-a83e-4226-8186-329696c14152",
          "validation-regex": "^[0-9]{12}$"
        }
      ]
    },
    nl: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "date",
          name: "birthdate",
          label: "Birthdate",
          widget: "anastasis_gtk_ia_birthdate",
          uuid: "83d655c7-bdb6-484d-904e-80c1058c8854"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "social_security_number",
          label: "Citizen Service Number",
          label_i18n: {
            nl_NL: "Burgerservicenummer (BSN)",
            en: "Citizen Service Number"
          },
          widget: "anastasis_gtk_ia_ssn_nl",
          uuid: "b6bf1f14-1f85-4afb-af21-f54b88490bdc",
          "validation-regex": "^[1-9][0-9]{8}$",
          "validation-logic": "NL_BSN_check"
        }
      ]
    },
    sk: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "birth_number",
          label: "Birth Number",
          label_i18n: {
            en: "Birth Number",
            sk: "rodn\xE9 \u010D\xEDslo"
          },
          widget: "anastasis_gtk_ia_birthnumber_sk",
          uuid: "1cd372fe-2cea-4928-9f29-66f2bdd8555c",
          "validation-regex": "^[0-9]{2}(((0|2|5|7)[0-9])|10|11|31|32|51|52|81|82)/[0-9]{3}[0-9]?$",
          "validation-logic": "CZ_BN_check"
        }
      ]
    },
    us: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "date",
          name: "birthdate",
          label: "Birthdate",
          widget: "anastasis_gtk_ia_birthdate",
          uuid: "83d655c7-bdb6-484d-904e-80c1058c8854"
        },
        {
          type: "string",
          name: "birthplace",
          label: "Birthplace",
          widget: "anastasis_gtk_ia_birthplace",
          uuid: "4c822e8e-89c6-11eb-95c4-8b077ad8489f"
        },
        {
          type: "string",
          name: "social_security_number",
          label: "Social security number",
          label_i18n: {
            en: "US Social security number"
          },
          widget: "anastasis_gtk_ia_ssn_us",
          uuid: "310a138c-b0b7-4985-b8b8-d00e765e9f9b",
          "validation-regex": "^[0-9]{3}-[0-9]{2}-[0-9]{4}$",
          autocomplete: "???-??-????"
        }
      ]
    },
    xx: {
      license: "GPLv3+",
      "SPDX-License-Identifier": "GPL3.0-or-later",
      restricted: "xx",
      required_attributes: [
        {
          type: "string",
          name: "full_name",
          label: "Full name",
          widget: "anastasis_gtk_ia_full_name",
          uuid: "9e8f463f-575f-42cb-85f3-759559997331"
        },
        {
          type: "date",
          name: "birthdate",
          label: "Birthdate",
          widget: "anastasis_gtk_ia_birthdate",
          uuid: "83d655c7-bdb6-484d-904e-80c1058c8854"
        },
        {
          type: "string",
          name: "prime_number",
          label: "Prime number",
          widget: "anastasis_gtk_xx_prime",
          uuid: "39190a95-cacb-4412-8bae-1f7da3f980b4",
          "validation-regex": "^[0-9]+$",
          "validation-logic": "XY_PRIME_check",
          optional: true
        },
        {
          type: "string",
          name: "sq_number",
          label: "Square number",
          widget: "anastasis_gtk_xx_square",
          uuid: "ed790bca-89bf-11eb-96f2-233996cf644e",
          "validation-regex": "^[0-9]+$",
          "validation-logic": "XX_SQUARE_check"
        }
      ]
    }
  }
};

// ../anastasis-core/lib/provider-types.js
var codecForFileChallengeInstructionMessage = () => buildCodecForObject().property("challenge_type", codecForConstString("FILE_WRITTEN")).property("filename", codecForString()).build("FileChallengeInstructionMessage");
var codecForPinChallengeInstructionMessage = () => buildCodecForObject().property("challenge_type", codecForConstString("TAN_SENT")).property("tan_address_hint", codecForString()).build("PinChallengeInstructionMessage");
var codecForIbanChallengeInstructionMessage = () => buildCodecForObject().property("challenge_type", codecForConstString("IBAN_WIRE")).property("wire_details", codecForAny()).build("IbanChallengeInstructionMessage");
var codecForChallengeInstructionMessage = () => buildCodecForUnion().discriminateOn("challenge_type").alternative("FILE_WRITTEN", codecForFileChallengeInstructionMessage()).alternative("IBAN_WIRE", codecForIbanChallengeInstructionMessage()).alternative("TAN_SENT", codecForPinChallengeInstructionMessage()).build("ChallengeInstructionMessage");

// ../anastasis-core/lib/reducer-types.js
var BackupStates;
(function(BackupStates2) {
  BackupStates2["ContinentSelecting"] = "CONTINENT_SELECTING";
  BackupStates2["CountrySelecting"] = "COUNTRY_SELECTING";
  BackupStates2["UserAttributesCollecting"] = "USER_ATTRIBUTES_COLLECTING";
  BackupStates2["AuthenticationsEditing"] = "AUTHENTICATIONS_EDITING";
  BackupStates2["PoliciesReviewing"] = "POLICIES_REVIEWING";
  BackupStates2["SecretEditing"] = "SECRET_EDITING";
  BackupStates2["TruthsPaying"] = "TRUTHS_PAYING";
  BackupStates2["PoliciesPaying"] = "POLICIES_PAYING";
  BackupStates2["BackupFinished"] = "BACKUP_FINISHED";
})(BackupStates || (BackupStates = {}));
var RecoveryStates;
(function(RecoveryStates2) {
  RecoveryStates2["ContinentSelecting"] = "CONTINENT_SELECTING";
  RecoveryStates2["CountrySelecting"] = "COUNTRY_SELECTING";
  RecoveryStates2["UserAttributesCollecting"] = "USER_ATTRIBUTES_COLLECTING";
  RecoveryStates2["SecretSelecting"] = "SECRET_SELECTING";
  RecoveryStates2["ChallengeSelecting"] = "CHALLENGE_SELECTING";
  RecoveryStates2["ChallengePaying"] = "CHALLENGE_PAYING";
  RecoveryStates2["ChallengeSolving"] = "CHALLENGE_SOLVING";
  RecoveryStates2["RecoveryFinished"] = "RECOVERY_FINISHED";
})(RecoveryStates || (RecoveryStates = {}));
var codecForActionArgsEnterUserAttributes = () => buildCodecForObject().property("identity_attributes", codecForAny()).build("ActionArgsEnterUserAttributes");
var codecForActionArgSelectContinent = () => buildCodecForObject().property("continent", codecForString()).build("ActionArgSelectContinent");
var codecForActionArgsChangeVersion = codecForAny;
var codecForPolicyMember = () => buildCodecForObject().property("authentication_method", codecForNumber()).property("provider", codecForString()).build("PolicyMember");
var codecForActionArgsAddPolicy = () => buildCodecForObject().property("policy", codecForList(codecForPolicyMember())).build("ActionArgsAddPolicy");
var codecForActionArgsUpdateExpiration = () => buildCodecForObject().property("expiration", codecForTimestamp).build("ActionArgsUpdateExpiration");
var codecForActionArgsSelectChallenge = () => buildCodecForObject().property("uuid", codecForString()).build("ActionArgsSelectChallenge");
var codecForActionArgSelectCountry = () => buildCodecForObject().property("country_code", codecForString()).build("ActionArgSelectCountry");

// ../anastasis-core/lib/crypto.js
var nonceSize = 24;
var masterKeySize = 64;
async function userIdentifierDerive(idData, serverSalt) {
  const canonIdData = canonicalJson(idData);
  const hashInput = stringToBytes(canonIdData);
  const result = await hashArgon2id2(
    hashInput,
    // password
    decodeCrock(serverSalt),
    // salt
    3,
    // iterations
    1024,
    // memoryLimit (kibibytes)
    64
  );
  return encodeCrock(result);
}
function accountKeypairDerive(userId) {
  const d4 = kdfKw({
    outputLength: 32,
    ikm: decodeCrock(userId),
    info: stringToBytes("ver")
  });
  const pair = crypto_sign_keyPair_fromSeed(d4);
  return {
    priv: encodeCrock(d4),
    pub: encodeCrock(pair.publicKey)
  };
}
async function encryptRecoveryDocument(userId, recoveryDocData) {
  const nonce = encodeCrock(getRandomBytes(nonceSize));
  return anastasisEncrypt(nonce, asOpaque(userId), recoveryDocData, "erd");
}
async function decryptRecoveryDocument(userId, recoveryDocData) {
  return anastasisDecrypt(asOpaque(userId), recoveryDocData, "erd");
}
async function encryptPolicyMetadata(userId, metadata) {
  const metadataBytes = typedArrayConcat2([
    decodeCrock(metadata.policy_hash),
    stringToBytes(metadata.secret_name)
  ]);
  const nonce = encodeCrock(getRandomBytes(nonceSize));
  return anastasisEncrypt(nonce, asOpaque(userId), encodeCrock(metadataBytes), "rmd");
}
async function decryptPolicyMetadata(userId, metadataEnc) {
  console.log("metadataEnc", metadataEnc);
  const plain = await anastasisDecrypt(asOpaque(userId), metadataEnc, "rmd");
  console.log("plain:", plain);
  const metadataBytes = decodeCrock(plain);
  const policyHash = encodeCrock(metadataBytes.slice(0, 64));
  const secretName = bytesToString(metadataBytes.slice(64));
  return {
    policy_hash: policyHash,
    secret_name: secretName
  };
}
function typedArrayConcat2(chunks) {
  let payloadLen = 0;
  for (const c4 of chunks) {
    payloadLen += c4.byteLength;
  }
  const buf = new ArrayBuffer(payloadLen);
  const u8buf = new Uint8Array(buf);
  let p5 = 0;
  for (const c4 of chunks) {
    u8buf.set(c4, p5);
    p5 += c4.byteLength;
  }
  return u8buf;
}
async function policyKeyDerive(keyShares, policySalt) {
  const chunks = keyShares.map((x3) => decodeCrock(x3));
  const polKey = kdfKw({
    outputLength: 64,
    ikm: typedArrayConcat2(chunks),
    salt: decodeCrock(policySalt),
    info: stringToBytes("anastasis-policy-key-derive")
  });
  return encodeCrock(polKey);
}
async function deriveKey(keySeed, nonce, salt) {
  return kdfKw({
    outputLength: 32,
    salt: decodeCrock(nonce),
    ikm: decodeCrock(keySeed),
    info: stringToBytes(salt)
  });
}
async function anastasisEncrypt(nonce, keySeed, plaintext, salt) {
  const key = await deriveKey(keySeed, nonce, salt);
  const nonceBuf = decodeCrock(nonce);
  const cipherText = secretbox(decodeCrock(plaintext), decodeCrock(nonce), key);
  return encodeCrock(typedArrayConcat2([nonceBuf, cipherText]));
}
async function anastasisDecrypt(keySeed, ciphertext, salt) {
  const ctBuf = decodeCrock(ciphertext);
  const nonceBuf = ctBuf.slice(0, nonceSize);
  const enc = ctBuf.slice(nonceSize);
  const key = await deriveKey(keySeed, encodeCrock(nonceBuf), salt);
  const clearText = secretbox_open(enc, nonceBuf, key);
  if (!clearText) {
    throw Error("could not decrypt");
  }
  return encodeCrock(clearText);
}
var asOpaque = (x3) => x3;
var asEncryptedKeyShare = (x3) => x3;
var asEncryptedTruth = (x3) => x3;
var asKeyShare = (x3) => x3;
async function encryptKeyshare(keyShare, userId, answerSalt) {
  const s4 = answerSalt ?? "eks";
  const nonce = encodeCrock(getRandomBytes(24));
  return asEncryptedKeyShare(await anastasisEncrypt(nonce, asOpaque(userId), asOpaque(keyShare), s4));
}
async function decryptKeyShare(encKeyShare, userId, answerSalt) {
  const s4 = answerSalt ?? "eks";
  return asKeyShare(await anastasisDecrypt(asOpaque(userId), asOpaque(encKeyShare), s4));
}
async function encryptTruth(nonce, truthEncKey, truth) {
  const salt = "ect";
  return asEncryptedTruth(await anastasisEncrypt(nonce, asOpaque(truthEncKey), truth, salt));
}
async function coreSecretRecover(args) {
  const masterKey = await anastasisDecrypt(asOpaque(args.policyKey), args.encryptedMasterKey, "emk");
  return await anastasisDecrypt(masterKey, args.encryptedCoreSecret, "cse");
}
async function coreSecretEncrypt(policyKeys, coreSecret) {
  const masterKey = getRandomBytes(masterKeySize);
  const nonce = encodeCrock(getRandomBytes(nonceSize));
  const coreSecretEncSalt = "cse";
  const masterKeyEncSalt = "emk";
  const encCoreSecret = await anastasisEncrypt(nonce, encodeCrock(masterKey), coreSecret, coreSecretEncSalt);
  const encMasterKeys = [];
  for (let i4 = 0; i4 < policyKeys.length; i4++) {
    const polNonce = encodeCrock(getRandomBytes(nonceSize));
    const encMasterKey = await anastasisEncrypt(polNonce, asOpaque(policyKeys[i4]), encodeCrock(masterKey), masterKeyEncSalt);
    encMasterKeys.push(encMasterKey);
  }
  return {
    encCoreSecret,
    encMasterKeys
  };
}
async function pinAnswerHash(pin) {
  return encodeCrock(hash2(stringToBytes(pin.toString())));
}
async function secureAnswerHash(answer, truthUuid, questionSalt) {
  const powResult = await hashArgon2id2(
    stringToBytes(answer),
    // password
    decodeCrock(questionSalt),
    // salt
    3,
    // iterations
    1024,
    // memorySize (kibibytes)
    64
  );
  const kdfResult = kdfKw({
    outputLength: 64,
    salt: decodeCrock(truthUuid),
    ikm: powResult,
    info: stringToBytes("anastasis-secure-question-hashing")
  });
  return encodeCrock(kdfResult);
}

// ../anastasis-core/lib/recovery-document-types.js
var ChallengeType;
(function(ChallengeType2) {
  ChallengeType2["Question"] = "question";
  ChallengeType2["Sms"] = "sms";
  ChallengeType2["Email"] = "email";
  ChallengeType2["Post"] = "post";
  ChallengeType2["Totp"] = "totp";
  ChallengeType2["Iban"] = "iban";
})(ChallengeType || (ChallengeType = {}));

// ../anastasis-core/lib/policy-suggestion.js
var logger12 = new Logger("anastasis-core:policy-suggestion.ts");
var maxMethodSelections = 200;
var maxPolicyEvaluations = 1e4;
function suggestPolicies(methods, providers) {
  const numMethods = methods.length;
  if (numMethods === 0) {
    throw Error("no methods");
  }
  let numSel;
  if (numMethods <= 2) {
    numSel = numMethods;
  } else if (numMethods <= 4) {
    numSel = numMethods - 1;
  } else if (numMethods <= 6) {
    numSel = numMethods - 2;
  } else if (numMethods == 7) {
    numSel = numMethods - 3;
  } else {
    numSel = 4;
  }
  const policies = [];
  const selections = enumerateMethodSelections(numSel, numMethods, maxMethodSelections);
  logger12.info(`selections: ${j2s(selections)}`);
  for (const sel of selections) {
    const p5 = assignProviders(policies, methods, providers, sel);
    if (p5) {
      policies.push(p5);
    }
  }
  logger12.info(`suggesting policies ${j2s(policies)}`);
  return {
    policies,
    policy_providers: providers.map((x3) => ({
      provider_url: x3.url
    }))
  };
}
function assignProviders(existingPolicies, methods, providers, methodSelection) {
  const providerSelections = enumerateProviderMappings(methodSelection.length, providers.length, maxPolicyEvaluations);
  let bestProvSel;
  let bestDiversity = 0;
  let bestDuplication = Number.MAX_SAFE_INTEGER;
  for (const provSel of providerSelections) {
    let possible = true;
    for (const methSelIndex in provSel) {
      const provIndex = provSel[methSelIndex];
      if (typeof provIndex !== "number") {
        throw Error("invariant failed");
      }
      const methIndex = methodSelection[methSelIndex];
      const meth = methods[methIndex];
      if (!meth) {
        throw Error("invariant failed");
      }
      const prov = providers[provIndex];
      if (!prov.methodCost[meth.type]) {
        possible = false;
        break;
      }
    }
    if (!possible) {
      continue;
    }
    const providerSet = /* @__PURE__ */ new Set();
    for (const provIndex of provSel) {
      const prov = providers[provIndex];
      providerSet.add(prov.url);
    }
    const diversity = providerSet.size;
    const provPerMethod = [];
    for (let i4 = 0; i4 < methods.length; i4++) {
      provPerMethod[i4] = /* @__PURE__ */ new Set();
    }
    for (const pol of existingPolicies) {
      for (const m4 of pol.methods) {
        provPerMethod[m4.authentication_method].add(m4.provider);
      }
    }
    for (const methSelIndex in provSel) {
      const prov = providers[provSel[methSelIndex]];
      provPerMethod[methodSelection[methSelIndex]].add(prov.url);
    }
    let duplication = 0;
    for (const provSet of provPerMethod) {
      duplication += provSet.size;
    }
    logger12.info(`diversity ${diversity}, duplication ${duplication}`);
    if (!bestProvSel || diversity > bestDiversity) {
      bestProvSel = provSel;
      bestDiversity = diversity;
      bestDuplication = duplication;
      logger12.info(`taking based on diversity`);
    } else if (diversity == bestDiversity && duplication < bestDuplication) {
      bestProvSel = provSel;
      bestDiversity = diversity;
      bestDuplication = duplication;
      logger12.info(`taking based on duplication`);
    }
  }
  if (!bestProvSel) {
    return void 0;
  }
  return {
    methods: bestProvSel.map((x3, i4) => ({
      authentication_method: methodSelection[i4],
      provider: providers[x3].url
    }))
  };
}
function enumerateProviderMappings(n3, m4, limit) {
  const selections = [];
  const a4 = new Array(n3);
  const sel = (i4, start = 0) => {
    if (i4 === n3) {
      selections.push([...a4]);
      return;
    }
    for (let j4 = start; j4 < m4; j4++) {
      a4[i4] = j4;
      sel(i4 + 1, 0);
      if (limit && selections.length >= limit) {
        break;
      }
    }
  };
  sel(0);
  return selections;
}
function enumerateMethodSelections(n3, m4, limit) {
  const selections = [];
  const a4 = new Array(n3);
  const sel = (i4, start = 0) => {
    if (i4 === n3) {
      selections.push([...a4]);
      return;
    }
    for (let j4 = start; j4 < m4; j4++) {
      a4[i4] = j4;
      sel(i4 + 1, j4 + 1);
      if (limit && selections.length >= limit) {
        break;
      }
    }
  };
  sel(0);
  return selections;
}

// ../anastasis-core/lib/challenge-feedback-types.js
var ChallengeFeedbackStatus;
(function(ChallengeFeedbackStatus2) {
  ChallengeFeedbackStatus2["Solved"] = "solved";
  ChallengeFeedbackStatus2["CodeInFile"] = "code-in-file";
  ChallengeFeedbackStatus2["CodeSent"] = "code-sent";
  ChallengeFeedbackStatus2["ServerFailure"] = "server-failure";
  ChallengeFeedbackStatus2["TruthUnknown"] = "truth-unknown";
  ChallengeFeedbackStatus2["TalerPayment"] = "taler-payment";
  ChallengeFeedbackStatus2["Unsupported"] = "unsupported";
  ChallengeFeedbackStatus2["RateLimitExceeded"] = "rate-limit-exceeded";
  ChallengeFeedbackStatus2["IbanInstructions"] = "iban-instructions";
  ChallengeFeedbackStatus2["IncorrectAnswer"] = "incorrect-answer";
})(ChallengeFeedbackStatus || (ChallengeFeedbackStatus = {}));

// ../anastasis-core/lib/validators.js
var validators_exports = {};
__export(validators_exports, {
  AL_NID_check: () => AL_NID_check,
  BE_NRN_check: () => BE_NRN_check,
  CH_AHV_check: () => CH_AHV_check,
  CZ_BN_check: () => CZ_BN_check,
  DE_SVN_check: () => DE_SVN_check,
  DE_TIN_check: () => DE_TIN_check,
  ES_DNI_check: () => ES_DNI_check,
  IN_AADHAR_check: () => IN_AADHAR_check,
  IT_CF_check: () => IT_CF_check,
  XX_SQUARE_check: () => XX_SQUARE_check,
  XY_PRIME_check: () => XY_PRIME_check
});
function isPrime(num) {
  for (let i4 = 2, s4 = Math.sqrt(num); i4 <= s4; i4++)
    if (num % i4 === 0)
      return false;
  return num > 1;
}
function AL_NID_check(s4) {
  return true;
}
function BE_NRN_check(s4) {
  return true;
}
function CH_AHV_check(s4) {
  return true;
}
function CZ_BN_check(s4) {
  return true;
}
function DE_TIN_check(s4) {
  return true;
}
function DE_SVN_check(s4) {
  return true;
}
function ES_DNI_check(s4) {
  return true;
}
function IN_AADHAR_check(s4) {
  return true;
}
function IT_CF_check(s4) {
  return true;
}
function XX_SQUARE_check(s4) {
  const n3 = parseInt(s4, 10);
  const r4 = Math.sqrt(n3);
  return n3 === r4 * r4;
}
function XY_PRIME_check(s4) {
  const n3 = parseInt(s4, 10);
  return isPrime(n3);
}

// ../anastasis-core/lib/index.js
var logger13 = new Logger("anastasis-core:index.ts");
var http = createPlatformHttpLib({
  enableThrottling: true,
  requireTls: false
});
var ANASTASIS_HTTP_HEADER_POLICY_META_DATA = "Anastasis-Policy-Meta-Data";
function getContinents() {
  const continentSet = /* @__PURE__ */ new Set();
  const continents = [];
  for (const country of anastasisData.countriesList.countries) {
    if (continentSet.has(country.continent)) {
      continue;
    }
    continentSet.add(country.continent);
    continents.push({
      ...{ name_i18n: country.continent_i18n },
      name: country.continent
    });
  }
  return continents;
}
var ReducerError = class _ReducerError extends Error {
  constructor(errorJson) {
    super(errorJson.message ?? errorJson.hint ?? `${TalerErrorCode[errorJson.code]}`);
    this.errorJson = errorJson;
    Object.setPrototypeOf(this, _ReducerError.prototype);
  }
};
function getCountries(continent) {
  const countries = anastasisData.countriesList.countries.filter((x3) => x3.continent === continent);
  if (countries.length <= 0) {
    throw new ReducerError({
      code: TalerErrorCode.ANASTASIS_REDUCER_INPUT_INVALID,
      hint: `continent ${continent} not found`
    });
  }
  return countries;
}
async function getBackupStartState() {
  return {
    reducer_type: "backup",
    backup_state: BackupStates.ContinentSelecting,
    continents: getContinents()
  };
}
async function getRecoveryStartState() {
  return {
    reducer_type: "recovery",
    recovery_state: RecoveryStates.ContinentSelecting,
    continents: getContinents()
  };
}
async function selectCountry(selectedContinent, args) {
  const countryCode = args.country_code;
  const country = anastasisData.countriesList.countries.find((x3) => x3.code === countryCode);
  if (!country) {
    throw new ReducerError({
      code: TalerErrorCode.ANASTASIS_REDUCER_ACTION_INVALID,
      hint: "invalid country selected"
    });
  }
  if (country.continent !== selectedContinent) {
    throw new ReducerError({
      code: TalerErrorCode.ANASTASIS_REDUCER_ACTION_INVALID,
      hint: "selected country is not in selected continent"
    });
  }
  const providers = {};
  for (const prov of anastasisData.providersList.anastasis_provider) {
    let shouldAdd = country.code === prov.restricted || country.code !== "xx" && !prov.restricted;
    if (shouldAdd) {
      providers[prov.url] = {
        status: "not-contacted"
      };
    }
  }
  const ra = anastasisData.countryDetails[countryCode].required_attributes;
  return {
    selected_country: countryCode,
    required_attributes: ra,
    authentication_providers: providers
  };
}
async function backupSelectCountry(state, args) {
  return {
    ...state,
    ...await selectCountry(state.selected_continent, args),
    backup_state: BackupStates.UserAttributesCollecting
  };
}
async function recoverySelectCountry(state, args) {
  return {
    ...state,
    recovery_state: RecoveryStates.UserAttributesCollecting,
    ...await selectCountry(state.selected_continent, args)
  };
}
async function getProviderInfo(providerBaseUrl) {
  let resp;
  try {
    resp = await http.fetch(new URL2("config", providerBaseUrl).href);
  } catch (e4) {
    console.warn("Encountered an HTTP error whilst trying to get the provider's config: ", e4);
    return {
      status: "error",
      code: TalerErrorCode.ANASTASIS_REDUCER_NETWORK_FAILED,
      hint: "request to anastasis provider failed"
    };
  }
  if (resp.status < 200 || resp.status > 299) {
    console.warn("Got bad response code whilst getting provider config", resp);
    return {
      status: "error",
      code: TalerErrorCode.ANASTASIS_REDUCER_NETWORK_FAILED,
      hint: "unexpected status",
      http_status: resp.status
    };
  }
  try {
    const jsonResp = await resp.json();
    if (!jsonResp.provider_salt) {
      return {
        status: "error",
        code: TalerErrorCode.ANASTASIS_REDUCER_PROVIDER_CONFIG_FAILED,
        hint: "provider did not have provider salt"
      };
    }
    return {
      status: "ok",
      http_status: 200,
      annual_fee: jsonResp.annual_fee,
      business_name: jsonResp.business_name,
      currency: jsonResp.currency,
      liability_limit: jsonResp.liability_limit,
      methods: jsonResp.methods.map((x3) => ({
        type: x3.type,
        usage_fee: x3.cost
      })),
      provider_salt: jsonResp.provider_salt,
      storage_limit_in_megabytes: jsonResp.storage_limit_in_megabytes,
      truth_upload_fee: jsonResp.truth_upload_fee
    };
  } catch (e4) {
    return {
      status: "error",
      code: TalerErrorCode.ANASTASIS_REDUCER_NETWORK_FAILED,
      hint: "provider did not return JSON"
    };
  }
}
async function backupEnterUserAttributes(state, args) {
  const attributes = args.identity_attributes;
  const newState = {
    ...state,
    backup_state: BackupStates.AuthenticationsEditing,
    identity_attributes: attributes
  };
  return newState;
}
async function getTruthValue(authMethod, truthUuid, questionSalt) {
  switch (authMethod.type) {
    case "question": {
      return asOpaque(await secureAnswerHash(bytesToString(decodeCrock(authMethod.challenge)), truthUuid, questionSalt));
    }
    case "sms":
    case "email":
    case "totp":
    case "iban":
    case "post":
      return authMethod.challenge;
    default:
      throw Error(`unknown auth type '${authMethod.type}'`);
  }
}
async function compressRecoveryDoc(rd) {
  const docBytes = stringToBytes(JSON.stringify(rd));
  const sizeHeaderBuf = new ArrayBuffer(4);
  const dvbuf = new DataView(sizeHeaderBuf);
  dvbuf.setUint32(0, docBytes.length, false);
  const zippedDoc = zlibSync(docBytes);
  return typedArrayConcat2([new Uint8Array(sizeHeaderBuf), zippedDoc]);
}
async function uncompressRecoveryDoc(zippedRd) {
  const header = zippedRd.slice(0, 4);
  const data = zippedRd.slice(4);
  const res = unzlibSync(data);
  return JSON.parse(bytesToString(res));
}
async function prepareRecoveryData(state) {
  const policies = state.policies;
  const secretName = state.secret_name;
  const coreSecret = encodeCrock(stringToBytes(JSON.stringify(state.core_secret)));
  const truthMetadataMap = {};
  const policyKeys = [];
  const policySalts = [];
  const policyUuids = [];
  for (let policyIndex = 0; policyIndex < policies.length; policyIndex++) {
    const pol = policies[policyIndex];
    const policySalt = encodeCrock(getRandomBytes(64));
    const keyShares = [];
    const methUuids = [];
    for (let methIndex = 0; methIndex < pol.methods.length; methIndex++) {
      const meth = pol.methods[methIndex];
      const truthReference = `${meth.authentication_method}:${meth.provider}`;
      let tm = truthMetadataMap[truthReference];
      if (!tm) {
        tm = {
          key_share: encodeCrock(getRandomBytes(32)),
          nonce: encodeCrock(getRandomBytes(24)),
          master_salt: encodeCrock(getRandomBytes(16)),
          truth_key: encodeCrock(getRandomBytes(64)),
          uuid: encodeCrock(getRandomBytes(32)),
          pol_method_index: methIndex,
          policy_index: policyIndex
        };
        truthMetadataMap[truthReference] = tm;
      }
      keyShares.push(tm.key_share);
      methUuids.push(tm.uuid);
    }
    const policyKey = await policyKeyDerive(keyShares, policySalt);
    policyUuids.push(methUuids);
    policyKeys.push(policyKey);
    policySalts.push(policySalt);
  }
  const csr = await coreSecretEncrypt(policyKeys, coreSecret);
  const escrowMethods = [];
  for (const truthKey of Object.keys(truthMetadataMap)) {
    const tm = truthMetadataMap[truthKey];
    const pol = state.policies[tm.policy_index];
    const meth = pol.methods[tm.pol_method_index];
    const authMethod = state.authentication_methods[meth.authentication_method];
    const provider = state.authentication_providers[meth.provider];
    escrowMethods.push({
      escrow_type: authMethod.type,
      instructions: authMethod.instructions,
      provider_salt: provider.provider_salt,
      question_salt: tm.master_salt,
      truth_key: tm.truth_key,
      url: meth.provider,
      uuid: tm.uuid
    });
  }
  const rd = {
    secret_name: secretName,
    encrypted_core_secret: csr.encCoreSecret,
    escrow_methods: escrowMethods,
    policies: policies.map((x3, i4) => {
      return {
        master_key: csr.encMasterKeys[i4],
        uuids: policyUuids[i4],
        salt: policySalts[i4]
      };
    })
  };
  return {
    ...state,
    recovery_data: {
      recovery_document: rd,
      truth_metadata: truthMetadataMap
    }
  };
}
async function uploadSecret(state) {
  if (!state.recovery_data) {
    state = await prepareRecoveryData(state);
  }
  const recoveryData = state.recovery_data;
  if (!recoveryData) {
    throw Error("invariant failed");
  }
  const truthMetadataMap = recoveryData.truth_metadata;
  const rd = recoveryData.recovery_document;
  const truthPayUris = [];
  const truthPaySecrets = {};
  const userIdCache = {};
  const getUserIdCaching = async (providerUrl) => {
    let userId = userIdCache[providerUrl];
    if (!userId) {
      const provider = state.authentication_providers[providerUrl];
      userId = userIdCache[providerUrl] = await userIdentifierDerive(state.identity_attributes, provider.provider_salt);
    }
    return userId;
  };
  for (const truthKey of Object.keys(truthMetadataMap)) {
    const tm = truthMetadataMap[truthKey];
    const pol = state.policies[tm.policy_index];
    const meth = pol.methods[tm.pol_method_index];
    const authMethod = state.authentication_methods[meth.authentication_method];
    const truthValue = await getTruthValue(authMethod, tm.uuid, tm.master_salt);
    const encryptedTruth = await encryptTruth(tm.nonce, tm.truth_key, truthValue);
    logger13.info(`uploading truth to ${meth.provider}`);
    const userId = await getUserIdCaching(meth.provider);
    const encryptedKeyShare = await encryptKeyshare(tm.key_share, userId, authMethod.type === "question" ? bytesToString(decodeCrock(authMethod.challenge)) : void 0);
    const tur = {
      encrypted_truth: encryptedTruth,
      key_share_data: encryptedKeyShare,
      storage_duration_years: 5,
      type: authMethod.type,
      truth_mime: authMethod.mime_type
    };
    const reqUrl = new URL2(`truth/${tm.uuid}`, meth.provider);
    const paySecret = (state.truth_upload_payment_secrets ?? {})[meth.provider];
    if (paySecret) {
      reqUrl.searchParams.set("timeout_ms", "500");
    }
    const resp = await http.fetch(reqUrl.href, {
      method: "POST",
      headers: {
        "content-type": "application/json",
        ...paySecret ? {
          "Anastasis-Payment-Identifier": paySecret
        } : {}
      },
      body: JSON.stringify(tur)
    });
    if (resp.status === HttpStatusCode.NoContent) {
      continue;
    }
    if (resp.status === HttpStatusCode.PaymentRequired) {
      const talerPayUri = resp.headers.get("Taler");
      if (!talerPayUri) {
        return {
          reducer_type: "error",
          code: TalerErrorCode.ANASTASIS_REDUCER_BACKEND_FAILURE,
          hint: `payment requested, but no taler://pay URI given`
        };
      }
      truthPayUris.push(talerPayUri);
      const parsedUri = parsePayUri(talerPayUri);
      if (!parsedUri) {
        return {
          reducer_type: "error",
          code: TalerErrorCode.ANASTASIS_REDUCER_BACKEND_FAILURE,
          hint: `payment requested, but no taler://pay URI given`
        };
      }
      truthPaySecrets[meth.provider] = parsedUri.orderId;
      continue;
    }
    return {
      reducer_type: "error",
      code: TalerErrorCode.ANASTASIS_REDUCER_NETWORK_FAILED,
      hint: `could not upload truth (HTTP status ${resp.status})`
    };
  }
  if (truthPayUris.length > 0) {
    return {
      ...state,
      backup_state: BackupStates.TruthsPaying,
      truth_upload_payment_secrets: truthPaySecrets,
      payments: truthPayUris
    };
  }
  const successDetails = {};
  const policyPayUris = [];
  const policyPayUriMap = {};
  for (const prov of state.policy_providers) {
    const userId = await getUserIdCaching(prov.provider_url);
    const acctKeypair = accountKeypairDerive(userId);
    const zippedDoc = await compressRecoveryDoc(rd);
    const recoveryDocHash = encodeCrock(hash2(zippedDoc));
    const encRecoveryDoc = await encryptRecoveryDocument(userId, encodeCrock(zippedDoc));
    const bodyHash = hash2(decodeCrock(encRecoveryDoc));
    const sigPS = buildSigPS(TalerSignaturePurpose.ANASTASIS_POLICY_UPLOAD).put(bodyHash).build();
    const sig = eddsaSign(sigPS, decodeCrock(acctKeypair.priv));
    const metadataEnc = await encryptPolicyMetadata(userId, {
      policy_hash: recoveryDocHash,
      secret_name: state.secret_name ?? "<unnamed secret>"
    });
    const talerPayUri = state.policy_payment_requests?.find((x3) => x3.provider === prov.provider_url)?.payto;
    let paySecret;
    if (talerPayUri) {
      paySecret = parsePayUri(talerPayUri).orderId;
    }
    const reqUrl = new URL2(`policy/${acctKeypair.pub}`, prov.provider_url);
    if (paySecret) {
      reqUrl.searchParams.set("timeout_ms", "500");
    }
    logger13.info(`uploading policy to ${prov.provider_url}`);
    const resp = await http.fetch(reqUrl.href, {
      method: "POST",
      headers: {
        "Anastasis-Policy-Signature": encodeCrock(sig),
        "If-None-Match": JSON.stringify(encodeCrock(bodyHash)),
        [ANASTASIS_HTTP_HEADER_POLICY_META_DATA]: metadataEnc,
        ...paySecret ? {
          "Anastasis-Payment-Identifier": paySecret
        } : {}
      },
      body: decodeCrock(encRecoveryDoc)
    });
    logger13.info(`got response for policy upload (http status ${resp.status})`);
    if (resp.status === HttpStatusCode.NoContent) {
      let policyVersion = 0;
      let policyExpiration = { t_s: 0 };
      try {
        policyVersion = Number(resp.headers.get("Anastasis-Version") ?? "0");
      } catch (e4) {
      }
      try {
        policyExpiration = {
          t_s: Number(resp.headers.get("Anastasis-Policy-Expiration") ?? "0")
        };
      } catch (e4) {
      }
      successDetails[prov.provider_url] = {
        policy_version: policyVersion,
        policy_expiration: policyExpiration
      };
      continue;
    }
    if (resp.status === HttpStatusCode.PaymentRequired) {
      const talerPayUri2 = resp.headers.get("Taler");
      if (!talerPayUri2) {
        return {
          reducer_type: "error",
          code: TalerErrorCode.ANASTASIS_REDUCER_BACKEND_FAILURE,
          hint: `payment requested, but no taler://pay URI given`
        };
      }
      policyPayUris.push(talerPayUri2);
      const parsedUri = parsePayUri(talerPayUri2);
      if (!parsedUri) {
        return {
          reducer_type: "error",
          code: TalerErrorCode.ANASTASIS_REDUCER_BACKEND_FAILURE,
          hint: `payment requested, but no taler://pay URI given`
        };
      }
      policyPayUriMap[prov.provider_url] = talerPayUri2;
      continue;
    }
    return {
      reducer_type: "error",
      code: TalerErrorCode.ANASTASIS_REDUCER_NETWORK_FAILED,
      hint: `could not upload policy (http status ${resp.status})`
    };
  }
  if (policyPayUris.length > 0) {
    return {
      ...state,
      backup_state: BackupStates.PoliciesPaying,
      payments: policyPayUris,
      policy_payment_requests: Object.keys(policyPayUriMap).map((x3) => {
        return {
          payto: policyPayUriMap[x3],
          provider: x3
        };
      })
    };
  }
  logger13.info("backup finished");
  return {
    ...state,
    core_secret: void 0,
    backup_state: BackupStates.BackupFinished,
    success_details: successDetails,
    payments: void 0
  };
}
async function downloadPolicyFromProvider(state, providerUrl, version) {
  logger13.info(`trying to download policy from ${providerUrl}`);
  const userAttributes = state.identity_attributes;
  let pi = state.authentication_providers?.[providerUrl];
  if (!pi || pi.status !== "ok") {
    logger13.info(`fetching provider info for ${providerUrl}`);
    pi = await getProviderInfo(providerUrl);
  }
  logger13.info(`new provider status is ${pi.status}`);
  if (pi.status !== "ok") {
    return void 0;
  }
  const userId = await userIdentifierDerive(userAttributes, pi.provider_salt);
  const acctKeypair = accountKeypairDerive(userId);
  const reqUrl = new URL2(`policy/${acctKeypair.pub}`, providerUrl);
  reqUrl.searchParams.set("version", `${version}`);
  const resp = await http.fetch(reqUrl.href);
  if (resp.status !== 200) {
    logger13.info(`Could not download policy from provider ${providerUrl}, status ${resp.status}`);
    return void 0;
  }
  const body = await resp.bytes();
  const bodyDecrypted = await decryptRecoveryDocument(userId, encodeCrock(body));
  const rd = await uncompressRecoveryDoc(decodeCrock(bodyDecrypted));
  let policyVersion = 0;
  try {
    policyVersion = Number(resp.headers.get("Anastasis-Version") ?? "0");
  } catch (e4) {
    logger13.warn("Could not read policy version header");
    policyVersion = version;
  }
  return {
    recoveryDoc: rd,
    recoveryData: {
      provider_url: providerUrl,
      secret_name: rd.secret_name ?? "<unknown>",
      version: policyVersion
    }
  };
}
async function downloadPolicy(state) {
  logger13.info("downloading policy");
  if (!state.selected_version) {
    throw Error("invalid state");
  }
  let policyDownloadResult = void 0;
  for (const prov of state.selected_version.providers) {
    const res = await downloadPolicyFromProvider(state, prov.url, prov.version);
    if (res) {
      policyDownloadResult = res;
      break;
    }
  }
  if (!policyDownloadResult) {
    return {
      reducer_type: "error",
      code: TalerErrorCode.ANASTASIS_REDUCER_POLICY_LOOKUP_FAILED,
      hint: "No backups found at any provider for your identity information."
    };
  }
  const challenges = [];
  const recoveryDoc = policyDownloadResult.recoveryDoc;
  for (const x3 of recoveryDoc.escrow_methods) {
    challenges.push({
      instructions: x3.instructions,
      type: x3.escrow_type,
      uuid: x3.uuid
    });
  }
  const recoveryInfo = {
    challenges,
    policies: recoveryDoc.policies.map((x3) => {
      return x3.uuids.map((m4) => {
        return {
          uuid: m4
        };
      });
    })
  };
  return {
    ...state,
    recovery_state: RecoveryStates.ChallengeSelecting,
    recovery_document: policyDownloadResult.recoveryData,
    recovery_information: recoveryInfo,
    verbatim_recovery_document: recoveryDoc
  };
}
async function tryRecoverSecret(state) {
  const rd = state.verbatim_recovery_document;
  for (const p5 of rd.policies) {
    const keyShares = [];
    let missing = false;
    for (const truthUuid of p5.uuids) {
      const ks = (state.recovered_key_shares ?? {})[truthUuid];
      if (!ks) {
        missing = true;
        break;
      }
      keyShares.push(ks);
    }
    if (missing) {
      continue;
    }
    const policyKey = await policyKeyDerive(keyShares, p5.salt);
    const coreSecretBytes = await coreSecretRecover({
      encryptedCoreSecret: rd.encrypted_core_secret,
      encryptedMasterKey: p5.master_key,
      policyKey
    });
    return {
      ...state,
      recovery_state: RecoveryStates.RecoveryFinished,
      selected_challenge_uuid: void 0,
      core_secret: JSON.parse(bytesToString(decodeCrock(coreSecretBytes)))
    };
  }
  return { ...state };
}
async function pollChallenges(state, args) {
  for (const truthUuid in state.challenge_feedback) {
    if (state.recovery_state === RecoveryStates.RecoveryFinished) {
      break;
    }
    const feedback = state.challenge_feedback[truthUuid];
    const truth = state.verbatim_recovery_document.escrow_methods.find((x3) => x3.uuid === truthUuid);
    if (!truth) {
      logger13.warn("truth for challenge feedback entry not found in recovery document");
      continue;
    }
    if (feedback.state === ChallengeFeedbackStatus.IbanInstructions) {
      const s22 = await requestTruth(state, truth, {
        pin: feedback.answer_code
      });
      if (s22.reducer_type === "recovery") {
        state = s22;
      }
    }
  }
  return state;
}
async function getResponseHash(truth, solveRequest) {
  let respHash;
  switch (truth.escrow_type) {
    case ChallengeType.Question: {
      if ("answer" in solveRequest) {
        respHash = await secureAnswerHash(solveRequest.answer, truth.uuid, truth.question_salt);
      } else {
        throw Error("unsupported answer request");
      }
      break;
    }
    case ChallengeType.Email:
    case ChallengeType.Sms:
    case ChallengeType.Post:
    case ChallengeType.Iban:
    case ChallengeType.Totp: {
      if ("answer" in solveRequest) {
        const s4 = solveRequest.answer.trim().replace(/^A-/, "");
        let pin;
        try {
          pin = Number.parseInt(s4);
        } catch (e4) {
          throw Error("invalid pin format");
        }
        respHash = await pinAnswerHash(pin);
      } else if ("pin" in solveRequest) {
        respHash = await pinAnswerHash(solveRequest.pin);
      } else {
        throw Error("unsupported answer request");
      }
      break;
    }
    default:
      throw Error(`unsupported challenge type "${truth.escrow_type}""`);
  }
  return respHash;
}
async function requestTruth(state, truth, solveRequest) {
  const url = new URL2(`/truth/${truth.uuid}/solve`, truth.url);
  const hresp = await getResponseHash(truth, solveRequest);
  let resp;
  try {
    resp = await http.fetch(url.href, {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        truth_decryption_key: truth.truth_key,
        h_response: hresp
      })
    });
  } catch (e4) {
    return {
      reducer_type: "error",
      code: TalerErrorCode.ANASTASIS_TRUTH_CHALLENGE_FAILED,
      hint: "network error"
    };
  }
  logger13.info(`got POST /truth/.../solve response from ${truth.url}, http status ${resp.status}`);
  if (resp.status === HttpStatusCode.Ok) {
    let answerSalt = void 0;
    if (solveRequest && truth.escrow_type === "question" && "answer" in solveRequest) {
      answerSalt = solveRequest.answer;
    }
    const userId = await userIdentifierDerive(state.identity_attributes, truth.provider_salt);
    const respBody = new Uint8Array(await resp.bytes());
    const keyShare = await decryptKeyShare(encodeCrock(respBody), userId, answerSalt);
    const recoveredKeyShares = {
      ...state.recovered_key_shares ?? {},
      [truth.uuid]: keyShare
    };
    const challengeFeedback = {
      ...state.challenge_feedback,
      [truth.uuid]: {
        state: ChallengeFeedbackStatus.Solved
      }
    };
    const newState = {
      ...state,
      recovery_state: RecoveryStates.ChallengeSelecting,
      challenge_feedback: challengeFeedback,
      recovered_key_shares: recoveredKeyShares
    };
    return tryRecoverSecret(newState);
  }
  if (resp.status === HttpStatusCode.Forbidden) {
    const challengeFeedback = {
      ...state.challenge_feedback,
      [truth.uuid]: {
        state: ChallengeFeedbackStatus.IncorrectAnswer
      }
    };
    return {
      ...state,
      challenge_feedback: challengeFeedback
    };
  }
  return {
    reducer_type: "error",
    code: TalerErrorCode.ANASTASIS_TRUTH_CHALLENGE_FAILED,
    hint: "got unexpected /truth/ response status",
    http_status: resp.status
  };
}
async function solveChallenge(state, ta) {
  const recDoc = state.verbatim_recovery_document;
  const truth = recDoc.escrow_methods.find((x3) => x3.uuid === state.selected_challenge_uuid);
  if (!truth) {
    throw Error("truth for challenge not found");
  }
  return requestTruth(state, truth, ta);
}
async function recoveryEnterUserAttributes(state, args) {
  const st = {
    ...state,
    recovery_state: RecoveryStates.SecretSelecting,
    identity_attributes: args.identity_attributes
  };
  return st;
}
async function changeVersion(state, args) {
  const st = {
    ...state,
    selected_version: args
  };
  return downloadPolicy(st);
}
async function selectChallenge(state, ta) {
  const recDoc = state.verbatim_recovery_document;
  const truth = recDoc.escrow_methods.find((x3) => x3.uuid === ta.uuid);
  if (!truth) {
    throw "truth for challenge not found";
  }
  const url = new URL2(`/truth/${truth.uuid}/challenge`, truth.url);
  const newFeedback = { ...state.challenge_feedback };
  delete newFeedback[truth.uuid];
  switch (truth.escrow_type) {
    case ChallengeType.Question:
    case ChallengeType.Totp: {
      return {
        ...state,
        recovery_state: RecoveryStates.ChallengeSolving,
        selected_challenge_uuid: truth.uuid,
        challenge_feedback: newFeedback
      };
    }
  }
  let resp;
  try {
    resp = await http.fetch(url.href, {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        truth_decryption_key: truth.truth_key
      })
    });
  } catch (e4) {
    const feedback = {
      state: ChallengeFeedbackStatus.ServerFailure,
      http_status: 0
    };
    return {
      ...state,
      recovery_state: RecoveryStates.ChallengeSelecting,
      selected_challenge_uuid: truth.uuid,
      challenge_feedback: {
        ...state.challenge_feedback,
        [truth.uuid]: feedback
      }
    };
  }
  logger13.info(`got GET /truth/.../challenge response from ${truth.url}, http status ${resp.status}`);
  if (resp.status === HttpStatusCode.Ok) {
    const respBodyJson = await resp.json();
    logger13.info(`validating ${j2s(respBodyJson)}`);
    const instr = codecForChallengeInstructionMessage().decode(respBodyJson);
    let feedback;
    switch (instr.challenge_type) {
      case "FILE_WRITTEN": {
        feedback = {
          state: ChallengeFeedbackStatus.CodeInFile,
          display_hint: "TAN code is in file (for debugging)",
          filename: instr.filename
        };
        break;
      }
      case "IBAN_WIRE": {
        feedback = {
          state: ChallengeFeedbackStatus.IbanInstructions,
          answer_code: instr.wire_details.answer_code,
          target_business_name: instr.wire_details.business_name,
          challenge_amount: instr.wire_details.challenge_amount,
          target_iban: instr.wire_details.credit_iban,
          wire_transfer_subject: instr.wire_details.wire_transfer_subject
        };
        break;
      }
      case "TAN_SENT": {
        feedback = {
          state: ChallengeFeedbackStatus.CodeSent,
          address_hint: instr.tan_address_hint,
          display_hint: "Code sent to address"
        };
      }
    }
    return {
      ...state,
      recovery_state: RecoveryStates.ChallengeSolving,
      selected_challenge_uuid: truth.uuid,
      challenge_feedback: {
        ...state.challenge_feedback,
        [truth.uuid]: feedback
      }
    };
  }
  return {
    reducer_type: "error",
    code: TalerErrorCode.ANASTASIS_TRUTH_CHALLENGE_FAILED,
    hint: `got unexpected /truth/.../challenge response status (${resp.status})`,
    http_status: resp.status
  };
}
async function backupSelectContinent(state, args) {
  const countries = getCountries(args.continent);
  if (countries.length <= 0) {
    return {
      reducer_type: "error",
      code: TalerErrorCode.ANASTASIS_REDUCER_INPUT_INVALID,
      hint: "continent not found"
    };
  }
  return {
    ...state,
    backup_state: BackupStates.CountrySelecting,
    countries,
    selected_continent: args.continent
  };
}
async function recoverySelectContinent(state, args) {
  const countries = getCountries(args.continent);
  return {
    ...state,
    recovery_state: RecoveryStates.CountrySelecting,
    countries,
    selected_continent: args.continent
  };
}
function transition(action, argCodec, handler) {
  return {
    [action]: {
      argCodec,
      handler
    }
  };
}
function transitionBackupJump(action, st) {
  return {
    [action]: {
      argCodec: codecForAny(),
      handler: async (s4, a4) => ({ ...s4, backup_state: st })
    }
  };
}
function transitionRecoveryJump(action, st) {
  return {
    [action]: {
      argCodec: codecForAny(),
      handler: async (s4, a4) => ({ ...s4, recovery_state: st })
    }
  };
}
async function addProviderBackup(state, args) {
  const info = await getProviderInfo(args.provider_url);
  return {
    ...state,
    authentication_providers: {
      ...state.authentication_providers ?? {},
      [args.provider_url]: info
    }
  };
}
async function deleteProviderBackup(state, args) {
  const authentication_providers = {
    ...state.authentication_providers ?? {}
  };
  delete authentication_providers[args.provider_url];
  return {
    ...state,
    authentication_providers
  };
}
async function addProviderRecovery(state, args) {
  const info = await getProviderInfo(args.provider_url);
  return {
    ...state,
    authentication_providers: {
      ...state.authentication_providers ?? {},
      [args.provider_url]: info
    }
  };
}
async function deleteProviderRecovery(state, args) {
  const authentication_providers = {
    ...state.authentication_providers ?? {}
  };
  delete authentication_providers[args.provider_url];
  return {
    ...state,
    authentication_providers
  };
}
async function addAuthentication(state, args) {
  return {
    ...state,
    authentication_methods: [
      ...state.authentication_methods ?? [],
      args.authentication_method
    ]
  };
}
async function deleteAuthentication(state, args) {
  const m4 = state.authentication_methods ?? [];
  m4.splice(args.authentication_method, 1);
  return {
    ...state,
    authentication_methods: m4
  };
}
async function deletePolicy(state, args) {
  const policies = [...state.policies ?? []];
  policies.splice(args.policy_index, 1);
  return {
    ...state,
    policies
  };
}
async function updatePolicy(state, args) {
  const policies = [...state.policies ?? []];
  policies[args.policy_index] = { methods: args.policy };
  return {
    ...state,
    policies
  };
}
async function addPolicy(state, args) {
  return {
    ...state,
    policies: [
      ...state.policies ?? [],
      {
        methods: args.policy
      }
    ]
  };
}
async function nextFromAuthenticationsEditing(state, args) {
  const methods = state.authentication_methods ?? [];
  const providers = [];
  for (const provUrl of Object.keys(state.authentication_providers ?? {})) {
    const prov = state.authentication_providers[provUrl];
    if (prov.status !== "ok") {
      continue;
    }
    const methodCost = {};
    for (const meth of prov.methods) {
      methodCost[meth.type] = meth.usage_fee;
    }
    providers.push({
      methodCost,
      url: provUrl
    });
  }
  const pol = suggestPolicies(methods, providers);
  if (pol.policies.length === 0) {
    return {
      reducer_type: "error",
      code: TalerErrorCode.ANASTASIS_REDUCER_ACTION_INVALID,
      detail: "Unable to suggest any policies.  Check if providers are available and reachable."
    };
  }
  return {
    ...state,
    backup_state: BackupStates.PoliciesReviewing,
    ...pol
  };
}
async function updateUploadFees(state) {
  const expiration = state.expiration;
  if (!expiration) {
    return { ...state };
  }
  logger13.info("updating upload fees");
  const feePerCurrency = {};
  const addFee = (x3) => {
    x3 = Amounts.jsonifyAmount(x3);
    feePerCurrency[x3.currency] = Amounts.add(feePerCurrency[x3.currency] ?? Amounts.zeroOfAmount(x3), x3).amount;
  };
  const expirationTime = AbsoluteTime.fromProtocolTimestamp(expiration);
  const years = Duration.toIntegerYears(Duration.getRemaining(expirationTime));
  logger13.info(`computing fees for ${years} years`);
  for (const provUrl in state.authentication_providers ?? {}) {
    const prov = state.authentication_providers[provUrl];
    if ("annual_fee" in prov) {
      const annualFee = Amounts.mult(prov.annual_fee, years).amount;
      logger13.info(`adding annual fee ${Amounts.stringify(annualFee)}`);
      addFee(annualFee);
    }
  }
  const coveredProvTruth = /* @__PURE__ */ new Set();
  for (const x3 of state.policies ?? []) {
    for (const m4 of x3.methods) {
      const prov = state.authentication_providers[m4.provider];
      const authMethod = state.authentication_methods[m4.authentication_method];
      const key = `${m4.authentication_method}@${m4.provider}`;
      if (coveredProvTruth.has(key)) {
        continue;
      }
      logger13.info(`adding cost for auth method ${authMethod.challenge} / "${authMethod.instructions}" at ${m4.provider}`);
      coveredProvTruth.add(key);
      addFee(prov.truth_upload_fee);
    }
  }
  return {
    ...state,
    upload_fees: Object.values(feePerCurrency).map((x3) => ({
      fee: Amounts.stringify(x3)
    }))
  };
}
async function enterSecret(state, args) {
  return updateUploadFees({
    ...state,
    expiration: args.expiration,
    core_secret: {
      mime: args.secret.mime ?? "text/plain",
      value: args.secret.value,
      filename: args.secret.filename
    },
    // A new secret invalidates the existing recovery data.
    recovery_data: void 0
  });
}
async function nextFromChallengeSelecting(state, args) {
  const s22 = await tryRecoverSecret(state);
  if (s22.reducer_type === "recovery" && s22.recovery_state === RecoveryStates.RecoveryFinished) {
    return s22;
  }
  return {
    reducer_type: "error",
    code: TalerErrorCode.ANASTASIS_REDUCER_ACTION_INVALID,
    hint: "Not enough challenges solved"
  };
}
async function syncOneProviderRecoveryTransition(state, args) {
  const escrowMethods = state.verbatim_recovery_document?.escrow_methods ?? [];
  if (escrowMethods.length === 0) {
    return {
      reducer_type: "error",
      code: TalerErrorCode.ANASTASIS_REDUCER_ACTION_INVALID,
      hint: "Can't sync, no escrow methods in recovery doc."
    };
  }
  for (const x3 of escrowMethods) {
    const pi = state.authentication_providers?.[x3.url];
    if (pi?.status === "ok") {
      logger13.info(`provider ${x3.url} is synced`);
      continue;
    }
    const newPi = await getProviderInfo(x3.url);
    return {
      ...state,
      authentication_providers: {
        ...state.authentication_providers,
        [x3.url]: newPi
      }
    };
  }
  for (const [provUrl, pi] of Object.entries(state.authentication_providers ?? {})) {
    if (pi.status === "ok" || pi.status === "disabled" || pi.status === "error") {
      continue;
    }
    const newPi = await getProviderInfo(provUrl);
    return {
      ...state,
      authentication_providers: {
        ...state.authentication_providers,
        [provUrl]: newPi
      }
    };
  }
  return {
    reducer_type: "error",
    code: TalerErrorCode.ANASTASIS_REDUCER_PROVIDERS_ALREADY_SYNCED,
    hint: "all providers are already synced"
  };
}
async function syncOneProviderBackupTransition(state, args) {
  for (const [provUrl, pi] of Object.entries(state.authentication_providers ?? {})) {
    if (pi.status === "ok" || pi.status === "disabled" || pi.status === "error") {
      continue;
    }
    const newPi = await getProviderInfo(provUrl);
    return {
      ...state,
      authentication_providers: {
        ...state.authentication_providers,
        [provUrl]: newPi
      }
    };
  }
  return {
    reducer_type: "error",
    code: TalerErrorCode.ANASTASIS_REDUCER_PROVIDERS_ALREADY_SYNCED,
    hint: "all providers are already synced"
  };
}
async function enterSecretName(state, args) {
  return {
    ...state,
    secret_name: args.name
  };
}
async function updateSecretExpiration(state, args) {
  return updateUploadFees({
    ...state,
    expiration: args.expiration
  });
}
function mergeDiscoveryAggregate(newPolicies, oldAgg) {
  const aggregatedPolicies = [...oldAgg];
  const polHashToIndex = {};
  for (const pol of newPolicies) {
    const oldIndex = polHashToIndex[pol.policy_hash];
    if (oldIndex != null) {
      aggregatedPolicies[oldIndex].providers.push({
        url: pol.provider_url,
        version: pol.version
      });
    } else {
      aggregatedPolicies.push({
        attribute_mask: pol.attribute_mask,
        policy_hash: pol.policy_hash,
        providers: [
          {
            url: pol.provider_url,
            version: pol.version
          }
        ],
        secret_name: pol.secret_name
      });
      polHashToIndex[pol.policy_hash] = aggregatedPolicies.length - 1;
    }
  }
  return aggregatedPolicies;
}
var backupTransitions = {
  [BackupStates.ContinentSelecting]: {
    ...transition("select_continent", codecForActionArgSelectContinent(), backupSelectContinent)
  },
  [BackupStates.CountrySelecting]: {
    ...transitionBackupJump("back", BackupStates.ContinentSelecting),
    ...transition("select_country", codecForActionArgSelectCountry(), backupSelectCountry),
    ...transition("select_continent", codecForActionArgSelectContinent(), backupSelectContinent)
  },
  [BackupStates.UserAttributesCollecting]: {
    ...transitionBackupJump("back", BackupStates.CountrySelecting),
    ...transition("enter_user_attributes", codecForActionArgsEnterUserAttributes(), backupEnterUserAttributes),
    ...transition("sync_providers", codecForAny(), syncOneProviderBackupTransition)
  },
  [BackupStates.AuthenticationsEditing]: {
    ...transitionBackupJump("back", BackupStates.UserAttributesCollecting),
    ...transition("add_authentication", codecForAny(), addAuthentication),
    ...transition("delete_authentication", codecForAny(), deleteAuthentication),
    ...transition("add_provider", codecForAny(), addProviderBackup),
    ...transition("delete_provider", codecForAny(), deleteProviderBackup),
    ...transition("sync_providers", codecForAny(), syncOneProviderBackupTransition),
    ...transition("next", codecForAny(), nextFromAuthenticationsEditing)
  },
  [BackupStates.PoliciesReviewing]: {
    ...transitionBackupJump("back", BackupStates.AuthenticationsEditing),
    ...transitionBackupJump("next", BackupStates.SecretEditing),
    ...transition("add_policy", codecForActionArgsAddPolicy(), addPolicy),
    ...transition("delete_policy", codecForAny(), deletePolicy),
    ...transition("update_policy", codecForAny(), updatePolicy)
  },
  [BackupStates.SecretEditing]: {
    ...transitionBackupJump("back", BackupStates.PoliciesReviewing),
    ...transition("next", codecForAny(), uploadSecret),
    ...transition("enter_secret", codecForAny(), enterSecret),
    ...transition("update_expiration", codecForActionArgsUpdateExpiration(), updateSecretExpiration),
    ...transition("enter_secret_name", codecForAny(), enterSecretName)
  },
  [BackupStates.PoliciesPaying]: {
    ...transitionBackupJump("back", BackupStates.SecretEditing),
    ...transition("pay", codecForAny(), uploadSecret)
  },
  [BackupStates.TruthsPaying]: {
    ...transitionBackupJump("back", BackupStates.SecretEditing),
    ...transition("pay", codecForAny(), uploadSecret)
  },
  [BackupStates.BackupFinished]: {
    ...transitionBackupJump("back", BackupStates.SecretEditing)
  }
};
var recoveryTransitions = {
  [RecoveryStates.ContinentSelecting]: {
    ...transition("select_continent", codecForActionArgSelectContinent(), recoverySelectContinent)
  },
  [RecoveryStates.CountrySelecting]: {
    ...transitionRecoveryJump("back", RecoveryStates.ContinentSelecting),
    ...transition("select_country", codecForActionArgSelectCountry(), recoverySelectCountry),
    ...transition("select_continent", codecForActionArgSelectContinent(), recoverySelectContinent)
  },
  [RecoveryStates.UserAttributesCollecting]: {
    ...transitionRecoveryJump("back", RecoveryStates.CountrySelecting),
    ...transition("enter_user_attributes", codecForActionArgsEnterUserAttributes(), recoveryEnterUserAttributes)
  },
  [RecoveryStates.SecretSelecting]: {
    ...transitionRecoveryJump("back", RecoveryStates.UserAttributesCollecting),
    ...transitionRecoveryJump("next", RecoveryStates.ChallengeSelecting),
    ...transition("add_provider", codecForAny(), addProviderRecovery),
    ...transition("delete_provider", codecForAny(), deleteProviderRecovery),
    ...transition("select_version", codecForActionArgsChangeVersion(), changeVersion)
  },
  [RecoveryStates.ChallengeSelecting]: {
    ...transitionRecoveryJump("back", RecoveryStates.SecretSelecting),
    ...transition("select_challenge", codecForActionArgsSelectChallenge(), selectChallenge),
    ...transition("poll", codecForAny(), pollChallenges),
    ...transition("next", codecForAny(), nextFromChallengeSelecting),
    ...transition("sync_providers", codecForAny(), syncOneProviderRecoveryTransition)
  },
  [RecoveryStates.ChallengeSolving]: {
    ...transitionRecoveryJump("back", RecoveryStates.ChallengeSelecting),
    ...transition("solve_challenge", codecForAny(), solveChallenge)
  },
  [RecoveryStates.ChallengePaying]: {},
  [RecoveryStates.RecoveryFinished]: {
    ...transitionRecoveryJump("back", RecoveryStates.ChallengeSelecting)
  }
};
async function discoverPolicies(state, cursor) {
  if (state.reducer_type !== "recovery") {
    throw Error("can only discover providers in recovery state");
  }
  const policies = [];
  const providerUrls = Object.keys(state.authentication_providers || {});
  for (const providerUrl of providerUrls) {
    const providerInfo = await getProviderInfo(providerUrl);
    if (providerInfo.status !== "ok") {
      continue;
    }
    const userId = await userIdentifierDerive(state.identity_attributes, providerInfo.provider_salt);
    const acctKeypair = accountKeypairDerive(userId);
    const reqUrl = new URL2(`policy/${acctKeypair.pub}/meta`, providerUrl);
    const resp = await http.fetch(reqUrl.href);
    if (resp.status !== 200) {
      logger13.warn(`Could not fetch policy metadate from ${reqUrl.href}`);
      continue;
    }
    const respJson = await resp.json();
    const versions = Object.keys(respJson);
    for (const version of versions) {
      const item = respJson[version];
      if (!item.meta) {
        continue;
      }
      const metaData = await decryptPolicyMetadata(userId, item.meta);
      policies.push({
        attribute_mask: 0,
        provider_url: providerUrl,
        server_time: item.upload_time,
        version: Number.parseInt(version, 10),
        secret_name: metaData.secret_name,
        policy_hash: metaData.policy_hash
      });
    }
  }
  return {
    policies,
    cursor: void 0
  };
}
async function reduceAction(state, action, args) {
  let h4;
  let stateName;
  if ("backup_state" in state && state.backup_state) {
    stateName = state.backup_state;
    h4 = backupTransitions[state.backup_state][action];
  } else if ("recovery_state" in state && state.recovery_state) {
    stateName = state.recovery_state;
    h4 = recoveryTransitions[state.recovery_state][action];
  } else {
    return {
      reducer_type: "error",
      code: TalerErrorCode.ANASTASIS_REDUCER_ACTION_INVALID,
      hint: `Invalid state (needs backup_state or recovery_state)`
    };
  }
  if (!h4) {
    return {
      reducer_type: "error",
      code: TalerErrorCode.ANASTASIS_REDUCER_ACTION_INVALID,
      hint: `Unsupported action '${action}' in state '${stateName}'`
    };
  }
  let parsedArgs;
  try {
    parsedArgs = h4.argCodec.decode(args);
  } catch (e4) {
    return {
      reducer_type: "error",
      code: TalerErrorCode.ANASTASIS_REDUCER_INPUT_INVALID,
      hint: "argument validation failed",
      detail: e4.toString()
    };
  }
  try {
    return await h4.handler(state, parsedArgs);
  } catch (e4) {
    logger13.error("action handler failed");
    logger13.error(`${e4?.stack ?? e4}`);
    if (e4 instanceof ReducerError) {
      return {
        reducer_type: "error",
        ...e4.errorJson
      };
    }
    throw e4;
  }
}
async function completeProviderStatus(providerMap) {
  const updateTasks = [];
  for (const [provUrl, pi] of Object.entries(providerMap)) {
    switch (pi.status) {
      case "ok":
      case "error":
      case "disabled":
      default:
        continue;
      case "not-contacted":
        updateTasks.push((async () => {
          return [provUrl, await getProviderInfo(provUrl)];
        })());
    }
  }
  if (updateTasks.length === 0) {
    return {};
  }
  const [firstUrl, firstStatus] = await Promise.race(updateTasks);
  return {
    [firstUrl]: firstStatus
  };
}

// src/pages/home/index.tsx
init_preact_module();

// src/components/AsyncButton.tsx
init_preact_module();

// src/hooks/async.ts
function useIsMounted() {
  const isMountedRef = _2(true);
  const isMounted = T2(() => isMountedRef.current, []);
  h2(() => {
    return () => void (isMountedRef.current = false);
  }, []);
  return isMounted;
}
function useAsync(fn, { slowTolerance: tooLong } = { slowTolerance: 1e3 }) {
  const [data, setData] = p3(void 0);
  const [isLoading, setLoading] = p3(false);
  const [error2, setError] = p3(void 0);
  const [isSlow, setSlow] = p3(false);
  const isMounted = useIsMounted();
  const request = async (...args) => {
    if (!fn)
      return;
    setLoading(true);
    const handler = setTimeout(() => {
      if (!isMounted()) {
        return;
      }
      setSlow(true);
    }, tooLong);
    try {
      const result = await fn(...args);
      if (!isMounted()) {
        return;
      }
      setData(result);
    } catch (error3) {
      setError(error3);
    }
    setLoading(false);
    setSlow(false);
    clearTimeout(handler);
  };
  function cancel() {
    setLoading(false);
    setSlow(false);
  }
  return {
    request,
    cancel,
    data,
    isSlow,
    isLoading,
    error: error2
  };
}

// src/components/AsyncButton.tsx
function AsyncButton({
  onClick,
  grabFocus,
  disabled,
  children,
  ...rest
}) {
  const { isLoading, request } = useAsync(onClick);
  const buttonRef = _2(null);
  s2(() => {
    if (grabFocus) {
      buttonRef.current?.focus();
    }
  }, [grabFocus]);
  if (isLoading) {
    return /* @__PURE__ */ h("button", { class: "button" }, "Loading...");
  }
  return /* @__PURE__ */ h("span", { "data-tooltip": rest["data-tooltip"], style: { marginLeft: 5 } }, /* @__PURE__ */ h("button", { ...rest, ref: buttonRef, onClick: request, disabled }, children));
}

// src/components/menu/index.tsx
init_preact_module();
var import_match = __toESM(require_match(), 1);

// src/components/menu/NavigationBar.tsx
init_preact_module();
function NavigationBar({ onMobileMenu, title }) {
  return /* @__PURE__ */ h(
    "nav",
    {
      class: "navbar is-fixed-top",
      role: "navigation",
      "aria-label": "main navigation"
    },
    /* @__PURE__ */ h("div", { class: "navbar-brand" }, /* @__PURE__ */ h("span", { class: "navbar-item", style: { fontSize: 24, fontWeight: 900 } }, title), /* @__PURE__ */ h(
      "a",
      {
        href: "mailto:contact@anastasis.lu",
        style: { alignSelf: "center", padding: "0.5em" }
      },
      "Contact us"
    ), /* @__PURE__ */ h(
      "a",
      {
        href: "https://bugs.anastasis.lu/",
        style: { alignSelf: "center", padding: "0.5em" }
      },
      "Report a bug"
    )),
    /* @__PURE__ */ h("div", { class: "navbar-menu " }, /* @__PURE__ */ h("div", { class: "navbar-end" }, /* @__PURE__ */ h("div", { class: "navbar-item", style: { paddingTop: 4, paddingBottom: 4 } })))
  );
}

// src/components/menu/SideBar.tsx
init_preact_module();

// src/context/anastasis.ts
init_preact_module();
var initial2 = void 0;
var Context2 = B(initial2);
var AnastasisProvider = ({ value, children }) => {
  return h(Context2.Provider, { value, children });
};
var useAnastasisContext = () => q2(Context2);

// src/components/menu/SideBar.tsx
var VERSION = true ? "0.12.2" : "dev";
var GIT_HASH = true ? "7d4548d490487f9475b87f449166441561d97bd3".substring(0, 7) : void 0;
var VERSION_WITH_HASH = GIT_HASH ? `${VERSION}-${GIT_HASH}` : VERSION;
function Sidebar({ mobile }) {
  const reducer = useAnastasisContext();
  const { i18n: i18n2 } = useTranslationContext();
  function saveSession() {
    const state = reducer.exportState();
    const link = document.createElement("a");
    link.download = "anastasis.json";
    link.href = `data:text/plain,${state}`;
    link.click();
  }
  return /* @__PURE__ */ h("aside", { class: "aside is-placed-left is-expanded" }, /* @__PURE__ */ h("div", { class: "aside-tools" }, /* @__PURE__ */ h("div", { class: "aside-tools-label" }, /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("b", null, "Anastasis")), /* @__PURE__ */ h(
    "div",
    {
      class: "is-size-7 has-text-right",
      style: { lineHeight: 0, marginTop: -10 }
    },
    "Version ",
    VERSION_WITH_HASH
  ))), /* @__PURE__ */ h("div", { class: "menu is-menu-main" }, !reducer.currentReducerState && /* @__PURE__ */ h("p", { class: "menu-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Backup or Recorver")), /* @__PURE__ */ h("ul", { class: "menu-list" }, !reducer.currentReducerState && /* @__PURE__ */ h("li", null, /* @__PURE__ */ h("div", { class: "ml-4" }, /* @__PURE__ */ h("span", { class: "menu-item-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Select one option")))), reducer.currentReducerState?.reducer_type === "backup" ? /* @__PURE__ */ h(p, null, /* @__PURE__ */ h(
    "li",
    {
      class: reducer.currentReducerState.backup_state === BackupStates.ContinentSelecting || reducer.currentReducerState.backup_state === BackupStates.CountrySelecting ? "is-active" : ""
    },
    /* @__PURE__ */ h("div", { class: "ml-4" }, /* @__PURE__ */ h("span", { class: "menu-item-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Location")))
  ), /* @__PURE__ */ h(
    "li",
    {
      class: reducer.currentReducerState.backup_state === BackupStates.UserAttributesCollecting ? "is-active" : ""
    },
    /* @__PURE__ */ h("div", { class: "ml-4" }, /* @__PURE__ */ h("span", { class: "menu-item-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Personal information")))
  ), /* @__PURE__ */ h(
    "li",
    {
      class: reducer.currentReducerState.backup_state === BackupStates.AuthenticationsEditing ? "is-active" : ""
    },
    /* @__PURE__ */ h("div", { class: "ml-4" }, /* @__PURE__ */ h("span", { class: "menu-item-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Authorization methods")))
  ), /* @__PURE__ */ h(
    "li",
    {
      class: reducer.currentReducerState.backup_state === BackupStates.PoliciesReviewing ? "is-active" : ""
    },
    /* @__PURE__ */ h("div", { class: "ml-4" }, /* @__PURE__ */ h("span", { class: "menu-item-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Policies")))
  ), /* @__PURE__ */ h(
    "li",
    {
      class: reducer.currentReducerState.backup_state === BackupStates.SecretEditing ? "is-active" : ""
    },
    /* @__PURE__ */ h("div", { class: "ml-4" }, /* @__PURE__ */ h("span", { class: "menu-item-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Secret input")))
  ), /* @__PURE__ */ h(
    "li",
    {
      class: reducer.currentReducerState.backup_state === BackupStates.BackupFinished ? "is-active" : ""
    },
    /* @__PURE__ */ h("div", { class: "ml-4" }, /* @__PURE__ */ h("span", { class: "menu-item-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Backup completed")))
  ), reducer.currentReducerState.backup_state !== BackupStates.BackupFinished && /* @__PURE__ */ h("li", null, /* @__PURE__ */ h("div", { class: "buttons ml-4" }, /* @__PURE__ */ h(
    "button",
    {
      class: "button is-primary is-right",
      onClick: saveSession
    },
    "Save backup session"
  ))), reducer.currentReducerState.backup_state !== BackupStates.BackupFinished && /* @__PURE__ */ h("li", null, /* @__PURE__ */ h("div", { class: "buttons ml-4" }, /* @__PURE__ */ h(
    "button",
    {
      class: "button is-danger is-right",
      onClick: () => reducer.reset()
    },
    "Reset session"
  )))) : reducer.currentReducerState?.reducer_type === "recovery" && /* @__PURE__ */ h(p, null, /* @__PURE__ */ h(
    "li",
    {
      class: reducer.currentReducerState.recovery_state === RecoveryStates.ContinentSelecting || reducer.currentReducerState.recovery_state === RecoveryStates.CountrySelecting ? "is-active" : ""
    },
    /* @__PURE__ */ h("div", { class: "ml-4" }, /* @__PURE__ */ h("span", { class: "menu-item-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Location")))
  ), /* @__PURE__ */ h(
    "li",
    {
      class: reducer.currentReducerState.recovery_state === RecoveryStates.UserAttributesCollecting ? "is-active" : ""
    },
    /* @__PURE__ */ h("div", { class: "ml-4" }, /* @__PURE__ */ h("span", { class: "menu-item-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Personal information")))
  ), /* @__PURE__ */ h(
    "li",
    {
      class: reducer.currentReducerState.recovery_state === RecoveryStates.SecretSelecting ? "is-active" : ""
    },
    /* @__PURE__ */ h("div", { class: "ml-4" }, /* @__PURE__ */ h("span", { class: "menu-item-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Secret selection")))
  ), /* @__PURE__ */ h(
    "li",
    {
      class: reducer.currentReducerState.recovery_state === RecoveryStates.ChallengeSelecting || reducer.currentReducerState.recovery_state === RecoveryStates.ChallengeSolving ? "is-active" : ""
    },
    /* @__PURE__ */ h("div", { class: "ml-4" }, /* @__PURE__ */ h("span", { class: "menu-item-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Solve Challenges")))
  ), /* @__PURE__ */ h(
    "li",
    {
      class: reducer.currentReducerState.recovery_state === RecoveryStates.RecoveryFinished ? "is-active" : ""
    },
    /* @__PURE__ */ h("div", { class: "ml-4" }, /* @__PURE__ */ h("span", { class: "menu-item-label" }, /* @__PURE__ */ h(i18n2.Translate, null, "Secret recovered")))
  ), reducer.currentReducerState.recovery_state !== RecoveryStates.RecoveryFinished && /* @__PURE__ */ h("li", null, /* @__PURE__ */ h("div", { class: "buttons ml-4" }, /* @__PURE__ */ h(
    "button",
    {
      class: "button is-primary is-right",
      onClick: saveSession
    },
    "Save recovery session"
  ))), reducer.currentReducerState.recovery_state === RecoveryStates.RecoveryFinished ? /* @__PURE__ */ h(p, null) : /* @__PURE__ */ h("li", null, /* @__PURE__ */ h("div", { class: "buttons ml-4" }, /* @__PURE__ */ h(
    "button",
    {
      class: "button is-danger is-right",
      onClick: () => reducer.reset()
    },
    "Reset session"
  )))))));
}

// src/components/menu/index.tsx
function WithTitle({
  title,
  children
}) {
  h2(() => {
    document.title = `${title}`;
  }, [title]);
  return /* @__PURE__ */ h(p, null, children);
}
function Menu({ title }) {
  const [mobileOpen, setMobileOpen] = p3(false);
  return /* @__PURE__ */ h(import_match.Match, null, ({ path }) => {
    const titleWithSubtitle = title;
    return /* @__PURE__ */ h(WithTitle, { title: titleWithSubtitle }, /* @__PURE__ */ h(
      "div",
      {
        class: mobileOpen ? "has-aside-mobile-expanded" : "",
        onClick: () => setMobileOpen(false)
      },
      /* @__PURE__ */ h(
        NavigationBar,
        {
          onMobileMenu: () => setMobileOpen(!mobileOpen),
          title: titleWithSubtitle
        }
      ),
      /* @__PURE__ */ h(Sidebar, { mobile: mobileOpen })
    ));
  });
}

// src/components/Notifications.tsx
init_preact_module();
function messageStyle(type) {
  switch (type) {
    case "INFO":
      return "message is-info";
    case "WARN":
      return "message is-warning";
    case "ERROR":
      return "message is-danger";
    case "SUCCESS":
      return "message is-success";
    default:
      return "message";
  }
}
function Notifications({
  notifications,
  removeNotification
}) {
  return /* @__PURE__ */ h("div", { class: "block" }, notifications.map((n3, i4) => /* @__PURE__ */ h("article", { key: i4, class: messageStyle(n3.type) }, /* @__PURE__ */ h("div", { class: "message-header" }, /* @__PURE__ */ h("p", null, n3.message), removeNotification && /* @__PURE__ */ h(
    "button",
    {
      class: "delete",
      onClick: () => removeNotification && removeNotification(n3)
    }
  )), n3.description && /* @__PURE__ */ h("div", { class: "message-body" }, n3.description))));
}

// src/hooks/use-anastasis-reducer.ts
var reducerBaseUrl = "http://localhost:5000/";
var remoteReducer = false;
async function getBackupStartStateRemote() {
  let resp;
  try {
    resp = await fetch(new URL("start-backup", reducerBaseUrl).href);
  } catch (e4) {
    return {
      code: TalerErrorCode.ANASTASIS_REDUCER_NETWORK_FAILED,
      message: `Network request to remote reducer ${reducerBaseUrl} failed`
    };
  }
  try {
    return await resp.json();
  } catch (e4) {
    return {
      code: TalerErrorCode.ANASTASIS_REDUCER_NETWORK_FAILED,
      message: `Could not parse response from reducer`
    };
  }
}
async function getRecoveryStartStateRemote() {
  let resp;
  try {
    resp = await fetch(new URL("start-recovery", reducerBaseUrl).href);
  } catch (e4) {
    return {
      code: TalerErrorCode.ANASTASIS_REDUCER_NETWORK_FAILED,
      message: `Network request to remote reducer ${reducerBaseUrl} failed`
    };
  }
  try {
    return await resp.json();
  } catch (e4) {
    return {
      code: TalerErrorCode.ANASTASIS_REDUCER_NETWORK_FAILED,
      message: `Could not parse response from reducer`
    };
  }
}
async function reduceStateRemote(state, action, args) {
  let resp;
  try {
    resp = await fetch(new URL("action", reducerBaseUrl).href, {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        state,
        action,
        arguments: args
      })
    });
  } catch (e4) {
    return {
      code: TalerErrorCode.ANASTASIS_REDUCER_NETWORK_FAILED,
      message: `Network request to remote reducer ${reducerBaseUrl} failed`
    };
  }
  try {
    return await resp.json();
  } catch (e4) {
    return {
      code: TalerErrorCode.ANASTASIS_REDUCER_NETWORK_FAILED,
      message: `Could not parse response from reducer`
    };
  }
}
function storageGet(key) {
  if (typeof localStorage === "object") {
    return localStorage.getItem(key);
  }
  return null;
}
function storageSet(key, value) {
  if (typeof localStorage === "object") {
    return localStorage.setItem(key, value);
  }
}
function getStateFromStorage() {
  let state;
  try {
    const s4 = storageGet("anastasisReducerState");
    if (s4 === "undefined") {
      state = void 0;
    } else if (s4) {
      state = JSON.parse(s4);
    }
  } catch (e4) {
    console.log("ERROR: getStateFromStorage ", e4);
  }
  return state ?? void 0;
}
function useAnastasisReducer() {
  const [anastasisState, setAnastasisStateInternal] = p3(
    () => ({
      reducerState: getStateFromStorage(),
      currentError: void 0,
      discoveryState: {
        state: "none"
      }
    })
  );
  const setAnastasisState = (newState) => {
    try {
      storageSet(
        "anastasisReducerState",
        JSON.stringify(newState.reducerState)
      );
    } catch (e4) {
      console.log("ERROR setAnastasisState", e4);
    }
    setAnastasisStateInternal(newState);
    const tryUpdateProviders = () => {
      const reducerState = newState.reducerState;
      if (reducerState?.reducer_type !== "backup" && reducerState?.reducer_type !== "recovery") {
        return;
      }
      const provMap = reducerState.authentication_providers;
      if (!provMap) {
        return;
      }
      const doUpdate = async () => {
        const updates = await completeProviderStatus(provMap);
        if (Object.keys(updates).length === 0) {
          return;
        }
        const rs2 = reducerState;
        if (rs2.reducer_type !== "backup" && rs2.reducer_type !== "recovery") {
          return;
        }
        setAnastasisState({
          ...anastasisState,
          reducerState: {
            ...rs2,
            authentication_providers: {
              ...rs2.authentication_providers,
              ...updates
            }
          }
        });
      };
      doUpdate().catch((e4) => console.log("ERROR doUpdate", e4));
    };
    tryUpdateProviders();
  };
  async function doTransition(action, args) {
    let s4;
    if (remoteReducer) {
      s4 = await reduceStateRemote(anastasisState.reducerState, action, args);
    } else {
      s4 = await reduceAction(anastasisState.reducerState, action, args);
    }
    if (s4.reducer_type === "error") {
      setAnastasisState({ ...anastasisState, currentError: s4 });
    } else {
      setAnastasisState({
        ...anastasisState,
        currentError: void 0,
        reducerState: s4
      });
    }
  }
  return {
    currentReducerState: anastasisState.reducerState,
    currentError: anastasisState.currentError,
    discoveryState: anastasisState.discoveryState,
    async startBackup() {
      let s4;
      if (remoteReducer) {
        s4 = await getBackupStartStateRemote();
      } else {
        s4 = await getBackupStartState();
      }
      if (s4.reducer_type === "error") {
        setAnastasisState({
          ...anastasisState,
          currentError: s4
        });
      } else {
        setAnastasisState({
          ...anastasisState,
          currentError: void 0,
          reducerState: s4
        });
      }
    },
    exportState() {
      const state = getStateFromStorage();
      return JSON.stringify(state);
    },
    importState(s4) {
      try {
        const state = JSON.parse(s4);
        setAnastasisState({
          reducerState: state,
          currentError: void 0,
          discoveryState: {
            state: "none"
          }
        });
      } catch (e4) {
        throw new Error("could not restore the state");
      }
    },
    async discoverStart() {
      const res = await discoverPolicies(this.currentReducerState, void 0);
      const aggregatedPolicies = mergeDiscoveryAggregate(res.policies, []);
      setAnastasisState({
        ...anastasisState,
        discoveryState: {
          state: "finished",
          aggregatedPolicies,
          cursor: res.cursor
        }
      });
    },
    async discoverMore() {
      return;
    },
    async startRecover() {
      let s4;
      if (remoteReducer) {
        s4 = await getRecoveryStartStateRemote();
      } else {
        s4 = await getRecoveryStartState();
      }
      if (s4.reducer_type === "error") {
        setAnastasisState({
          ...anastasisState,
          currentError: s4
        });
      } else {
        setAnastasisState({
          ...anastasisState,
          currentError: void 0,
          reducerState: s4
        });
      }
    },
    transition(action, args) {
      return doTransition(action, args);
    },
    async back() {
      const reducerState = anastasisState.reducerState;
      if (!reducerState) {
        return;
      }
      if (reducerState.reducer_type === "backup" && reducerState.backup_state === BackupStates.ContinentSelecting || reducerState.reducer_type === "recovery" && reducerState.recovery_state === RecoveryStates.ContinentSelecting) {
        setAnastasisState({
          ...anastasisState,
          currentError: void 0,
          reducerState: void 0
        });
      } else {
        await doTransition("back", {});
      }
    },
    dismissError() {
      setAnastasisState({ ...anastasisState, currentError: void 0 });
    },
    reset() {
      setAnastasisState({
        ...anastasisState,
        currentError: void 0,
        reducerState: void 0
      });
    },
    async runTransaction(f4) {
      const txHandle = new ReducerTxImpl(anastasisState.reducerState);
      try {
        await f4(txHandle);
      } catch (e4) {
        console.log("exception during reducer transaction", e4);
      }
      const s4 = txHandle.transactionState;
      if (s4.reducer_type === "error") {
        setAnastasisState({
          ...anastasisState,
          currentError: txHandle.transactionState
        });
      } else {
        setAnastasisState({
          ...anastasisState,
          reducerState: txHandle.transactionState,
          currentError: void 0
        });
      }
    }
  };
}
var ReducerTxImpl = class {
  constructor(transactionState) {
    this.transactionState = transactionState;
  }
  async transition(action, args) {
    let s4;
    if (remoteReducer) {
      s4 = await reduceStateRemote(this.transactionState, action, args);
    } else {
      s4 = await reduceAction(this.transactionState, action, args);
    }
    this.transactionState = s4;
    if (this.transactionState.reducer_type === "error") {
      throw new Error("transition resulted in error");
    }
    return this.transactionState;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/toInteger/index.js
function toInteger(dirtyNumber) {
  if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
    return NaN;
  }
  var number = Number(dirtyNumber);
  if (isNaN(number)) {
    return number;
  }
  return number < 0 ? Math.ceil(number) : Math.floor(number);
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/requiredArgs/index.js
function requiredArgs(required, args) {
  if (args.length < required) {
    throw new TypeError(required + " argument" + (required > 1 ? "s" : "") + " required, but only " + args.length + " present");
  }
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/toDate/index.js
function toDate(argument) {
  requiredArgs(1, arguments);
  var argStr = Object.prototype.toString.call(argument);
  if (argument instanceof Date || typeof argument === "object" && argStr === "[object Date]") {
    return new Date(argument.getTime());
  } else if (typeof argument === "number" || argStr === "[object Number]") {
    return new Date(argument);
  } else {
    if ((typeof argument === "string" || argStr === "[object String]") && typeof console !== "undefined") {
      console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments");
      console.warn(new Error().stack);
    }
    return /* @__PURE__ */ new Date(NaN);
  }
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/addMonths/index.js
function addMonths(dirtyDate, dirtyAmount) {
  requiredArgs(2, arguments);
  var date = toDate(dirtyDate);
  var amount = toInteger(dirtyAmount);
  if (isNaN(amount)) {
    return /* @__PURE__ */ new Date(NaN);
  }
  if (!amount) {
    return date;
  }
  var dayOfMonth = date.getDate();
  var endOfDesiredMonth = new Date(date.getTime());
  endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0);
  var daysInMonth = endOfDesiredMonth.getDate();
  if (dayOfMonth >= daysInMonth) {
    return endOfDesiredMonth;
  } else {
    date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth);
    return date;
  }
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/addMilliseconds/index.js
function addMilliseconds(dirtyDate, dirtyAmount) {
  requiredArgs(2, arguments);
  var timestamp = toDate(dirtyDate).getTime();
  var amount = toInteger(dirtyAmount);
  return new Date(timestamp + amount);
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/defaultOptions/index.js
var defaultOptions = {};
function getDefaultOptions() {
  return defaultOptions;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js
function getTimezoneOffsetInMilliseconds(date) {
  var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
  utcDate.setUTCFullYear(date.getFullYear());
  return date.getTime() - utcDate.getTime();
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/addYears/index.js
function addYears(dirtyDate, dirtyAmount) {
  requiredArgs(2, arguments);
  var amount = toInteger(dirtyAmount);
  return addMonths(dirtyDate, amount * 12);
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/constants/index.js
var daysInYear = 365.2425;
var maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1e3;
var millisecondsInMinute = 6e4;
var millisecondsInHour = 36e5;
var millisecondsInSecond = 1e3;
var minTime = -maxTime;
var secondsInHour = 3600;
var secondsInDay = secondsInHour * 24;
var secondsInWeek = secondsInDay * 7;
var secondsInYear = secondsInDay * daysInYear;
var secondsInMonth = secondsInYear / 12;
var secondsInQuarter = secondsInMonth * 3;

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/isDate/index.js
function isDate(value) {
  requiredArgs(1, arguments);
  return value instanceof Date || typeof value === "object" && Object.prototype.toString.call(value) === "[object Date]";
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/isValid/index.js
function isValid(dirtyDate) {
  requiredArgs(1, arguments);
  if (!isDate(dirtyDate) && typeof dirtyDate !== "number") {
    return false;
  }
  var date = toDate(dirtyDate);
  return !isNaN(Number(date));
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/subMilliseconds/index.js
function subMilliseconds(dirtyDate, dirtyAmount) {
  requiredArgs(2, arguments);
  var amount = toInteger(dirtyAmount);
  return addMilliseconds(dirtyDate, -amount);
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/getUTCDayOfYear/index.js
var MILLISECONDS_IN_DAY = 864e5;
function getUTCDayOfYear(dirtyDate) {
  requiredArgs(1, arguments);
  var date = toDate(dirtyDate);
  var timestamp = date.getTime();
  date.setUTCMonth(0, 1);
  date.setUTCHours(0, 0, 0, 0);
  var startOfYearTimestamp = date.getTime();
  var difference = timestamp - startOfYearTimestamp;
  return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js
function startOfUTCISOWeek(dirtyDate) {
  requiredArgs(1, arguments);
  var weekStartsOn = 1;
  var date = toDate(dirtyDate);
  var day = date.getUTCDay();
  var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
  date.setUTCDate(date.getUTCDate() - diff);
  date.setUTCHours(0, 0, 0, 0);
  return date;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js
function getUTCISOWeekYear(dirtyDate) {
  requiredArgs(1, arguments);
  var date = toDate(dirtyDate);
  var year = date.getUTCFullYear();
  var fourthOfJanuaryOfNextYear = /* @__PURE__ */ new Date(0);
  fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
  fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
  var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
  var fourthOfJanuaryOfThisYear = /* @__PURE__ */ new Date(0);
  fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
  fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
  var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
  if (date.getTime() >= startOfNextYear.getTime()) {
    return year + 1;
  } else if (date.getTime() >= startOfThisYear.getTime()) {
    return year;
  } else {
    return year - 1;
  }
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/startOfUTCISOWeekYear/index.js
function startOfUTCISOWeekYear(dirtyDate) {
  requiredArgs(1, arguments);
  var year = getUTCISOWeekYear(dirtyDate);
  var fourthOfJanuary = /* @__PURE__ */ new Date(0);
  fourthOfJanuary.setUTCFullYear(year, 0, 4);
  fourthOfJanuary.setUTCHours(0, 0, 0, 0);
  var date = startOfUTCISOWeek(fourthOfJanuary);
  return date;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js
var MILLISECONDS_IN_WEEK = 6048e5;
function getUTCISOWeek(dirtyDate) {
  requiredArgs(1, arguments);
  var date = toDate(dirtyDate);
  var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime();
  return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js
function startOfUTCWeek(dirtyDate, options) {
  var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
  requiredArgs(1, arguments);
  var defaultOptions2 = getDefaultOptions();
  var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions2.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);
  if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
    throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
  }
  var date = toDate(dirtyDate);
  var day = date.getUTCDay();
  var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
  date.setUTCDate(date.getUTCDate() - diff);
  date.setUTCHours(0, 0, 0, 0);
  return date;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js
function getUTCWeekYear(dirtyDate, options) {
  var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
  requiredArgs(1, arguments);
  var date = toDate(dirtyDate);
  var year = date.getUTCFullYear();
  var defaultOptions2 = getDefaultOptions();
  var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
  if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
    throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");
  }
  var firstWeekOfNextYear = /* @__PURE__ */ new Date(0);
  firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
  firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
  var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options);
  var firstWeekOfThisYear = /* @__PURE__ */ new Date(0);
  firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
  firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
  var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options);
  if (date.getTime() >= startOfNextYear.getTime()) {
    return year + 1;
  } else if (date.getTime() >= startOfThisYear.getTime()) {
    return year;
  } else {
    return year - 1;
  }
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/startOfUTCWeekYear/index.js
function startOfUTCWeekYear(dirtyDate, options) {
  var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
  requiredArgs(1, arguments);
  var defaultOptions2 = getDefaultOptions();
  var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
  var year = getUTCWeekYear(dirtyDate, options);
  var firstWeek = /* @__PURE__ */ new Date(0);
  firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
  firstWeek.setUTCHours(0, 0, 0, 0);
  var date = startOfUTCWeek(firstWeek, options);
  return date;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/getUTCWeek/index.js
var MILLISECONDS_IN_WEEK2 = 6048e5;
function getUTCWeek(dirtyDate, options) {
  requiredArgs(1, arguments);
  var date = toDate(dirtyDate);
  var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime();
  return Math.round(diff / MILLISECONDS_IN_WEEK2) + 1;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/addLeadingZeros/index.js
function addLeadingZeros(number, targetLength) {
  var sign2 = number < 0 ? "-" : "";
  var output = Math.abs(number).toString();
  while (output.length < targetLength) {
    output = "0" + output;
  }
  return sign2 + output;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/format/lightFormatters/index.js
var formatters = {
  // Year
  y: function(date, token) {
    var signedYear = date.getUTCFullYear();
    var year = signedYear > 0 ? signedYear : 1 - signedYear;
    return addLeadingZeros(token === "yy" ? year % 100 : year, token.length);
  },
  // Month
  M: function(date, token) {
    var month = date.getUTCMonth();
    return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2);
  },
  // Day of the month
  d: function(date, token) {
    return addLeadingZeros(date.getUTCDate(), token.length);
  },
  // AM or PM
  a: function(date, token) {
    var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? "pm" : "am";
    switch (token) {
      case "a":
      case "aa":
        return dayPeriodEnumValue.toUpperCase();
      case "aaa":
        return dayPeriodEnumValue;
      case "aaaaa":
        return dayPeriodEnumValue[0];
      case "aaaa":
      default:
        return dayPeriodEnumValue === "am" ? "a.m." : "p.m.";
    }
  },
  // Hour [1-12]
  h: function(date, token) {
    return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
  },
  // Hour [0-23]
  H: function(date, token) {
    return addLeadingZeros(date.getUTCHours(), token.length);
  },
  // Minute
  m: function(date, token) {
    return addLeadingZeros(date.getUTCMinutes(), token.length);
  },
  // Second
  s: function(date, token) {
    return addLeadingZeros(date.getUTCSeconds(), token.length);
  },
  // Fraction of second
  S: function(date, token) {
    var numberOfDigits = token.length;
    var milliseconds = date.getUTCMilliseconds();
    var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
    return addLeadingZeros(fractionalSeconds, token.length);
  }
};
var lightFormatters_default = formatters;

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/format/formatters/index.js
var dayPeriodEnum = {
  am: "am",
  pm: "pm",
  midnight: "midnight",
  noon: "noon",
  morning: "morning",
  afternoon: "afternoon",
  evening: "evening",
  night: "night"
};
var formatters2 = {
  // Era
  G: function(date, token, localize2) {
    var era = date.getUTCFullYear() > 0 ? 1 : 0;
    switch (token) {
      case "G":
      case "GG":
      case "GGG":
        return localize2.era(era, {
          width: "abbreviated"
        });
      case "GGGGG":
        return localize2.era(era, {
          width: "narrow"
        });
      case "GGGG":
      default:
        return localize2.era(era, {
          width: "wide"
        });
    }
  },
  // Year
  y: function(date, token, localize2) {
    if (token === "yo") {
      var signedYear = date.getUTCFullYear();
      var year = signedYear > 0 ? signedYear : 1 - signedYear;
      return localize2.ordinalNumber(year, {
        unit: "year"
      });
    }
    return lightFormatters_default.y(date, token);
  },
  // Local week-numbering year
  Y: function(date, token, localize2, options) {
    var signedWeekYear = getUTCWeekYear(date, options);
    var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
    if (token === "YY") {
      var twoDigitYear = weekYear % 100;
      return addLeadingZeros(twoDigitYear, 2);
    }
    if (token === "Yo") {
      return localize2.ordinalNumber(weekYear, {
        unit: "year"
      });
    }
    return addLeadingZeros(weekYear, token.length);
  },
  // ISO week-numbering year
  R: function(date, token) {
    var isoWeekYear = getUTCISOWeekYear(date);
    return addLeadingZeros(isoWeekYear, token.length);
  },
  // Extended year. This is a single number designating the year of this calendar system.
  // The main difference between `y` and `u` localizers are B.C. years:
  // | Year | `y` | `u` |
  // |------|-----|-----|
  // | AC 1 |   1 |   1 |
  // | BC 1 |   1 |   0 |
  // | BC 2 |   2 |  -1 |
  // Also `yy` always returns the last two digits of a year,
  // while `uu` pads single digit years to 2 characters and returns other years unchanged.
  u: function(date, token) {
    var year = date.getUTCFullYear();
    return addLeadingZeros(year, token.length);
  },
  // Quarter
  Q: function(date, token, localize2) {
    var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
    switch (token) {
      case "Q":
        return String(quarter);
      case "QQ":
        return addLeadingZeros(quarter, 2);
      case "Qo":
        return localize2.ordinalNumber(quarter, {
          unit: "quarter"
        });
      case "QQQ":
        return localize2.quarter(quarter, {
          width: "abbreviated",
          context: "formatting"
        });
      case "QQQQQ":
        return localize2.quarter(quarter, {
          width: "narrow",
          context: "formatting"
        });
      case "QQQQ":
      default:
        return localize2.quarter(quarter, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Stand-alone quarter
  q: function(date, token, localize2) {
    var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
    switch (token) {
      case "q":
        return String(quarter);
      case "qq":
        return addLeadingZeros(quarter, 2);
      case "qo":
        return localize2.ordinalNumber(quarter, {
          unit: "quarter"
        });
      case "qqq":
        return localize2.quarter(quarter, {
          width: "abbreviated",
          context: "standalone"
        });
      case "qqqqq":
        return localize2.quarter(quarter, {
          width: "narrow",
          context: "standalone"
        });
      case "qqqq":
      default:
        return localize2.quarter(quarter, {
          width: "wide",
          context: "standalone"
        });
    }
  },
  // Month
  M: function(date, token, localize2) {
    var month = date.getUTCMonth();
    switch (token) {
      case "M":
      case "MM":
        return lightFormatters_default.M(date, token);
      case "Mo":
        return localize2.ordinalNumber(month + 1, {
          unit: "month"
        });
      case "MMM":
        return localize2.month(month, {
          width: "abbreviated",
          context: "formatting"
        });
      case "MMMMM":
        return localize2.month(month, {
          width: "narrow",
          context: "formatting"
        });
      case "MMMM":
      default:
        return localize2.month(month, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Stand-alone month
  L: function(date, token, localize2) {
    var month = date.getUTCMonth();
    switch (token) {
      case "L":
        return String(month + 1);
      case "LL":
        return addLeadingZeros(month + 1, 2);
      case "Lo":
        return localize2.ordinalNumber(month + 1, {
          unit: "month"
        });
      case "LLL":
        return localize2.month(month, {
          width: "abbreviated",
          context: "standalone"
        });
      case "LLLLL":
        return localize2.month(month, {
          width: "narrow",
          context: "standalone"
        });
      case "LLLL":
      default:
        return localize2.month(month, {
          width: "wide",
          context: "standalone"
        });
    }
  },
  // Local week of year
  w: function(date, token, localize2, options) {
    var week = getUTCWeek(date, options);
    if (token === "wo") {
      return localize2.ordinalNumber(week, {
        unit: "week"
      });
    }
    return addLeadingZeros(week, token.length);
  },
  // ISO week of year
  I: function(date, token, localize2) {
    var isoWeek = getUTCISOWeek(date);
    if (token === "Io") {
      return localize2.ordinalNumber(isoWeek, {
        unit: "week"
      });
    }
    return addLeadingZeros(isoWeek, token.length);
  },
  // Day of the month
  d: function(date, token, localize2) {
    if (token === "do") {
      return localize2.ordinalNumber(date.getUTCDate(), {
        unit: "date"
      });
    }
    return lightFormatters_default.d(date, token);
  },
  // Day of year
  D: function(date, token, localize2) {
    var dayOfYear = getUTCDayOfYear(date);
    if (token === "Do") {
      return localize2.ordinalNumber(dayOfYear, {
        unit: "dayOfYear"
      });
    }
    return addLeadingZeros(dayOfYear, token.length);
  },
  // Day of week
  E: function(date, token, localize2) {
    var dayOfWeek = date.getUTCDay();
    switch (token) {
      case "E":
      case "EE":
      case "EEE":
        return localize2.day(dayOfWeek, {
          width: "abbreviated",
          context: "formatting"
        });
      case "EEEEE":
        return localize2.day(dayOfWeek, {
          width: "narrow",
          context: "formatting"
        });
      case "EEEEEE":
        return localize2.day(dayOfWeek, {
          width: "short",
          context: "formatting"
        });
      case "EEEE":
      default:
        return localize2.day(dayOfWeek, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Local day of week
  e: function(date, token, localize2, options) {
    var dayOfWeek = date.getUTCDay();
    var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
    switch (token) {
      case "e":
        return String(localDayOfWeek);
      case "ee":
        return addLeadingZeros(localDayOfWeek, 2);
      case "eo":
        return localize2.ordinalNumber(localDayOfWeek, {
          unit: "day"
        });
      case "eee":
        return localize2.day(dayOfWeek, {
          width: "abbreviated",
          context: "formatting"
        });
      case "eeeee":
        return localize2.day(dayOfWeek, {
          width: "narrow",
          context: "formatting"
        });
      case "eeeeee":
        return localize2.day(dayOfWeek, {
          width: "short",
          context: "formatting"
        });
      case "eeee":
      default:
        return localize2.day(dayOfWeek, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Stand-alone local day of week
  c: function(date, token, localize2, options) {
    var dayOfWeek = date.getUTCDay();
    var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
    switch (token) {
      case "c":
        return String(localDayOfWeek);
      case "cc":
        return addLeadingZeros(localDayOfWeek, token.length);
      case "co":
        return localize2.ordinalNumber(localDayOfWeek, {
          unit: "day"
        });
      case "ccc":
        return localize2.day(dayOfWeek, {
          width: "abbreviated",
          context: "standalone"
        });
      case "ccccc":
        return localize2.day(dayOfWeek, {
          width: "narrow",
          context: "standalone"
        });
      case "cccccc":
        return localize2.day(dayOfWeek, {
          width: "short",
          context: "standalone"
        });
      case "cccc":
      default:
        return localize2.day(dayOfWeek, {
          width: "wide",
          context: "standalone"
        });
    }
  },
  // ISO day of week
  i: function(date, token, localize2) {
    var dayOfWeek = date.getUTCDay();
    var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
    switch (token) {
      case "i":
        return String(isoDayOfWeek);
      case "ii":
        return addLeadingZeros(isoDayOfWeek, token.length);
      case "io":
        return localize2.ordinalNumber(isoDayOfWeek, {
          unit: "day"
        });
      case "iii":
        return localize2.day(dayOfWeek, {
          width: "abbreviated",
          context: "formatting"
        });
      case "iiiii":
        return localize2.day(dayOfWeek, {
          width: "narrow",
          context: "formatting"
        });
      case "iiiiii":
        return localize2.day(dayOfWeek, {
          width: "short",
          context: "formatting"
        });
      case "iiii":
      default:
        return localize2.day(dayOfWeek, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // AM or PM
  a: function(date, token, localize2) {
    var hours = date.getUTCHours();
    var dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
    switch (token) {
      case "a":
      case "aa":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        });
      case "aaa":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        }).toLowerCase();
      case "aaaaa":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "narrow",
          context: "formatting"
        });
      case "aaaa":
      default:
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // AM, PM, midnight, noon
  b: function(date, token, localize2) {
    var hours = date.getUTCHours();
    var dayPeriodEnumValue;
    if (hours === 12) {
      dayPeriodEnumValue = dayPeriodEnum.noon;
    } else if (hours === 0) {
      dayPeriodEnumValue = dayPeriodEnum.midnight;
    } else {
      dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
    }
    switch (token) {
      case "b":
      case "bb":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        });
      case "bbb":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        }).toLowerCase();
      case "bbbbb":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "narrow",
          context: "formatting"
        });
      case "bbbb":
      default:
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // in the morning, in the afternoon, in the evening, at night
  B: function(date, token, localize2) {
    var hours = date.getUTCHours();
    var dayPeriodEnumValue;
    if (hours >= 17) {
      dayPeriodEnumValue = dayPeriodEnum.evening;
    } else if (hours >= 12) {
      dayPeriodEnumValue = dayPeriodEnum.afternoon;
    } else if (hours >= 4) {
      dayPeriodEnumValue = dayPeriodEnum.morning;
    } else {
      dayPeriodEnumValue = dayPeriodEnum.night;
    }
    switch (token) {
      case "B":
      case "BB":
      case "BBB":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        });
      case "BBBBB":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "narrow",
          context: "formatting"
        });
      case "BBBB":
      default:
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Hour [1-12]
  h: function(date, token, localize2) {
    if (token === "ho") {
      var hours = date.getUTCHours() % 12;
      if (hours === 0)
        hours = 12;
      return localize2.ordinalNumber(hours, {
        unit: "hour"
      });
    }
    return lightFormatters_default.h(date, token);
  },
  // Hour [0-23]
  H: function(date, token, localize2) {
    if (token === "Ho") {
      return localize2.ordinalNumber(date.getUTCHours(), {
        unit: "hour"
      });
    }
    return lightFormatters_default.H(date, token);
  },
  // Hour [0-11]
  K: function(date, token, localize2) {
    var hours = date.getUTCHours() % 12;
    if (token === "Ko") {
      return localize2.ordinalNumber(hours, {
        unit: "hour"
      });
    }
    return addLeadingZeros(hours, token.length);
  },
  // Hour [1-24]
  k: function(date, token, localize2) {
    var hours = date.getUTCHours();
    if (hours === 0)
      hours = 24;
    if (token === "ko") {
      return localize2.ordinalNumber(hours, {
        unit: "hour"
      });
    }
    return addLeadingZeros(hours, token.length);
  },
  // Minute
  m: function(date, token, localize2) {
    if (token === "mo") {
      return localize2.ordinalNumber(date.getUTCMinutes(), {
        unit: "minute"
      });
    }
    return lightFormatters_default.m(date, token);
  },
  // Second
  s: function(date, token, localize2) {
    if (token === "so") {
      return localize2.ordinalNumber(date.getUTCSeconds(), {
        unit: "second"
      });
    }
    return lightFormatters_default.s(date, token);
  },
  // Fraction of second
  S: function(date, token) {
    return lightFormatters_default.S(date, token);
  },
  // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
  X: function(date, token, _localize, options) {
    var originalDate = options._originalDate || date;
    var timezoneOffset = originalDate.getTimezoneOffset();
    if (timezoneOffset === 0) {
      return "Z";
    }
    switch (token) {
      case "X":
        return formatTimezoneWithOptionalMinutes(timezoneOffset);
      case "XXXX":
      case "XX":
        return formatTimezone(timezoneOffset);
      case "XXXXX":
      case "XXX":
      default:
        return formatTimezone(timezoneOffset, ":");
    }
  },
  // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
  x: function(date, token, _localize, options) {
    var originalDate = options._originalDate || date;
    var timezoneOffset = originalDate.getTimezoneOffset();
    switch (token) {
      case "x":
        return formatTimezoneWithOptionalMinutes(timezoneOffset);
      case "xxxx":
      case "xx":
        return formatTimezone(timezoneOffset);
      case "xxxxx":
      case "xxx":
      default:
        return formatTimezone(timezoneOffset, ":");
    }
  },
  // Timezone (GMT)
  O: function(date, token, _localize, options) {
    var originalDate = options._originalDate || date;
    var timezoneOffset = originalDate.getTimezoneOffset();
    switch (token) {
      case "O":
      case "OO":
      case "OOO":
        return "GMT" + formatTimezoneShort(timezoneOffset, ":");
      case "OOOO":
      default:
        return "GMT" + formatTimezone(timezoneOffset, ":");
    }
  },
  // Timezone (specific non-location)
  z: function(date, token, _localize, options) {
    var originalDate = options._originalDate || date;
    var timezoneOffset = originalDate.getTimezoneOffset();
    switch (token) {
      case "z":
      case "zz":
      case "zzz":
        return "GMT" + formatTimezoneShort(timezoneOffset, ":");
      case "zzzz":
      default:
        return "GMT" + formatTimezone(timezoneOffset, ":");
    }
  },
  // Seconds timestamp
  t: function(date, token, _localize, options) {
    var originalDate = options._originalDate || date;
    var timestamp = Math.floor(originalDate.getTime() / 1e3);
    return addLeadingZeros(timestamp, token.length);
  },
  // Milliseconds timestamp
  T: function(date, token, _localize, options) {
    var originalDate = options._originalDate || date;
    var timestamp = originalDate.getTime();
    return addLeadingZeros(timestamp, token.length);
  }
};
function formatTimezoneShort(offset, dirtyDelimiter) {
  var sign2 = offset > 0 ? "-" : "+";
  var absOffset = Math.abs(offset);
  var hours = Math.floor(absOffset / 60);
  var minutes = absOffset % 60;
  if (minutes === 0) {
    return sign2 + String(hours);
  }
  var delimiter2 = dirtyDelimiter || "";
  return sign2 + String(hours) + delimiter2 + addLeadingZeros(minutes, 2);
}
function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
  if (offset % 60 === 0) {
    var sign2 = offset > 0 ? "-" : "+";
    return sign2 + addLeadingZeros(Math.abs(offset) / 60, 2);
  }
  return formatTimezone(offset, dirtyDelimiter);
}
function formatTimezone(offset, dirtyDelimiter) {
  var delimiter2 = dirtyDelimiter || "";
  var sign2 = offset > 0 ? "-" : "+";
  var absOffset = Math.abs(offset);
  var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
  var minutes = addLeadingZeros(absOffset % 60, 2);
  return sign2 + hours + delimiter2 + minutes;
}
var formatters_default = formatters2;

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/format/longFormatters/index.js
var dateLongFormatter = function(pattern, formatLong2) {
  switch (pattern) {
    case "P":
      return formatLong2.date({
        width: "short"
      });
    case "PP":
      return formatLong2.date({
        width: "medium"
      });
    case "PPP":
      return formatLong2.date({
        width: "long"
      });
    case "PPPP":
    default:
      return formatLong2.date({
        width: "full"
      });
  }
};
var timeLongFormatter = function(pattern, formatLong2) {
  switch (pattern) {
    case "p":
      return formatLong2.time({
        width: "short"
      });
    case "pp":
      return formatLong2.time({
        width: "medium"
      });
    case "ppp":
      return formatLong2.time({
        width: "long"
      });
    case "pppp":
    default:
      return formatLong2.time({
        width: "full"
      });
  }
};
var dateTimeLongFormatter = function(pattern, formatLong2) {
  var matchResult = pattern.match(/(P+)(p+)?/) || [];
  var datePattern = matchResult[1];
  var timePattern = matchResult[2];
  if (!timePattern) {
    return dateLongFormatter(pattern, formatLong2);
  }
  var dateTimeFormat;
  switch (datePattern) {
    case "P":
      dateTimeFormat = formatLong2.dateTime({
        width: "short"
      });
      break;
    case "PP":
      dateTimeFormat = formatLong2.dateTime({
        width: "medium"
      });
      break;
    case "PPP":
      dateTimeFormat = formatLong2.dateTime({
        width: "long"
      });
      break;
    case "PPPP":
    default:
      dateTimeFormat = formatLong2.dateTime({
        width: "full"
      });
      break;
  }
  return dateTimeFormat.replace("{{date}}", dateLongFormatter(datePattern, formatLong2)).replace("{{time}}", timeLongFormatter(timePattern, formatLong2));
};
var longFormatters = {
  p: timeLongFormatter,
  P: dateTimeLongFormatter
};
var longFormatters_default = longFormatters;

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/protectedTokens/index.js
var protectedDayOfYearTokens = ["D", "DD"];
var protectedWeekYearTokens = ["YY", "YYYY"];
function isProtectedDayOfYearToken(token) {
  return protectedDayOfYearTokens.indexOf(token) !== -1;
}
function isProtectedWeekYearToken(token) {
  return protectedWeekYearTokens.indexOf(token) !== -1;
}
function throwProtectedError(token, format2, input) {
  if (token === "YYYY") {
    throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format2, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
  } else if (token === "YY") {
    throw new RangeError("Use `yy` instead of `YY` (in `".concat(format2, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
  } else if (token === "D") {
    throw new RangeError("Use `d` instead of `D` (in `".concat(format2, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
  } else if (token === "DD") {
    throw new RangeError("Use `dd` instead of `DD` (in `".concat(format2, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
  }
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/locale/en-US/_lib/formatDistance/index.js
var formatDistanceLocale = {
  lessThanXSeconds: {
    one: "less than a second",
    other: "less than {{count}} seconds"
  },
  xSeconds: {
    one: "1 second",
    other: "{{count}} seconds"
  },
  halfAMinute: "half a minute",
  lessThanXMinutes: {
    one: "less than a minute",
    other: "less than {{count}} minutes"
  },
  xMinutes: {
    one: "1 minute",
    other: "{{count}} minutes"
  },
  aboutXHours: {
    one: "about 1 hour",
    other: "about {{count}} hours"
  },
  xHours: {
    one: "1 hour",
    other: "{{count}} hours"
  },
  xDays: {
    one: "1 day",
    other: "{{count}} days"
  },
  aboutXWeeks: {
    one: "about 1 week",
    other: "about {{count}} weeks"
  },
  xWeeks: {
    one: "1 week",
    other: "{{count}} weeks"
  },
  aboutXMonths: {
    one: "about 1 month",
    other: "about {{count}} months"
  },
  xMonths: {
    one: "1 month",
    other: "{{count}} months"
  },
  aboutXYears: {
    one: "about 1 year",
    other: "about {{count}} years"
  },
  xYears: {
    one: "1 year",
    other: "{{count}} years"
  },
  overXYears: {
    one: "over 1 year",
    other: "over {{count}} years"
  },
  almostXYears: {
    one: "almost 1 year",
    other: "almost {{count}} years"
  }
};
var formatDistance = function(token, count, options) {
  var result;
  var tokenValue = formatDistanceLocale[token];
  if (typeof tokenValue === "string") {
    result = tokenValue;
  } else if (count === 1) {
    result = tokenValue.one;
  } else {
    result = tokenValue.other.replace("{{count}}", count.toString());
  }
  if (options !== null && options !== void 0 && options.addSuffix) {
    if (options.comparison && options.comparison > 0) {
      return "in " + result;
    } else {
      return result + " ago";
    }
  }
  return result;
};
var formatDistance_default = formatDistance;

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/locale/_lib/buildFormatLongFn/index.js
function buildFormatLongFn(args) {
  return function() {
    var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    var width = options.width ? String(options.width) : args.defaultWidth;
    var format2 = args.formats[width] || args.formats[args.defaultWidth];
    return format2;
  };
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/locale/en-US/_lib/formatLong/index.js
var dateFormats = {
  full: "EEEE, MMMM do, y",
  long: "MMMM do, y",
  medium: "MMM d, y",
  short: "MM/dd/yyyy"
};
var timeFormats = {
  full: "h:mm:ss a zzzz",
  long: "h:mm:ss a z",
  medium: "h:mm:ss a",
  short: "h:mm a"
};
var dateTimeFormats = {
  full: "{{date}} 'at' {{time}}",
  long: "{{date}} 'at' {{time}}",
  medium: "{{date}}, {{time}}",
  short: "{{date}}, {{time}}"
};
var formatLong = {
  date: buildFormatLongFn({
    formats: dateFormats,
    defaultWidth: "full"
  }),
  time: buildFormatLongFn({
    formats: timeFormats,
    defaultWidth: "full"
  }),
  dateTime: buildFormatLongFn({
    formats: dateTimeFormats,
    defaultWidth: "full"
  })
};
var formatLong_default = formatLong;

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/locale/en-US/_lib/formatRelative/index.js
var formatRelativeLocale = {
  lastWeek: "'last' eeee 'at' p",
  yesterday: "'yesterday at' p",
  today: "'today at' p",
  tomorrow: "'tomorrow at' p",
  nextWeek: "eeee 'at' p",
  other: "P"
};
var formatRelative = function(token, _date, _baseDate, _options) {
  return formatRelativeLocale[token];
};
var formatRelative_default = formatRelative;

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js
function buildLocalizeFn(args) {
  return function(dirtyIndex, options) {
    var context = options !== null && options !== void 0 && options.context ? String(options.context) : "standalone";
    var valuesArray;
    if (context === "formatting" && args.formattingValues) {
      var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
      var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth;
      valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
    } else {
      var _defaultWidth = args.defaultWidth;
      var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth;
      valuesArray = args.values[_width] || args.values[_defaultWidth];
    }
    var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex;
    return valuesArray[index];
  };
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/locale/en-US/_lib/localize/index.js
var eraValues = {
  narrow: ["B", "A"],
  abbreviated: ["BC", "AD"],
  wide: ["Before Christ", "Anno Domini"]
};
var quarterValues = {
  narrow: ["1", "2", "3", "4"],
  abbreviated: ["Q1", "Q2", "Q3", "Q4"],
  wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]
};
var monthValues = {
  narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
  abbreviated: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
  wide: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
};
var dayValues = {
  narrow: ["S", "M", "T", "W", "T", "F", "S"],
  short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
  abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  wide: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
};
var dayPeriodValues = {
  narrow: {
    am: "a",
    pm: "p",
    midnight: "mi",
    noon: "n",
    morning: "morning",
    afternoon: "afternoon",
    evening: "evening",
    night: "night"
  },
  abbreviated: {
    am: "AM",
    pm: "PM",
    midnight: "midnight",
    noon: "noon",
    morning: "morning",
    afternoon: "afternoon",
    evening: "evening",
    night: "night"
  },
  wide: {
    am: "a.m.",
    pm: "p.m.",
    midnight: "midnight",
    noon: "noon",
    morning: "morning",
    afternoon: "afternoon",
    evening: "evening",
    night: "night"
  }
};
var formattingDayPeriodValues = {
  narrow: {
    am: "a",
    pm: "p",
    midnight: "mi",
    noon: "n",
    morning: "in the morning",
    afternoon: "in the afternoon",
    evening: "in the evening",
    night: "at night"
  },
  abbreviated: {
    am: "AM",
    pm: "PM",
    midnight: "midnight",
    noon: "noon",
    morning: "in the morning",
    afternoon: "in the afternoon",
    evening: "in the evening",
    night: "at night"
  },
  wide: {
    am: "a.m.",
    pm: "p.m.",
    midnight: "midnight",
    noon: "noon",
    morning: "in the morning",
    afternoon: "in the afternoon",
    evening: "in the evening",
    night: "at night"
  }
};
var ordinalNumber = function(dirtyNumber, _options) {
  var number = Number(dirtyNumber);
  var rem100 = number % 100;
  if (rem100 > 20 || rem100 < 10) {
    switch (rem100 % 10) {
      case 1:
        return number + "st";
      case 2:
        return number + "nd";
      case 3:
        return number + "rd";
    }
  }
  return number + "th";
};
var localize = {
  ordinalNumber,
  era: buildLocalizeFn({
    values: eraValues,
    defaultWidth: "wide"
  }),
  quarter: buildLocalizeFn({
    values: quarterValues,
    defaultWidth: "wide",
    argumentCallback: function(quarter) {
      return quarter - 1;
    }
  }),
  month: buildLocalizeFn({
    values: monthValues,
    defaultWidth: "wide"
  }),
  day: buildLocalizeFn({
    values: dayValues,
    defaultWidth: "wide"
  }),
  dayPeriod: buildLocalizeFn({
    values: dayPeriodValues,
    defaultWidth: "wide",
    formattingValues: formattingDayPeriodValues,
    defaultFormattingWidth: "wide"
  })
};
var localize_default = localize;

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/locale/_lib/buildMatchFn/index.js
function buildMatchFn(args) {
  return function(string) {
    var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    var width = options.width;
    var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
    var matchResult = string.match(matchPattern);
    if (!matchResult) {
      return null;
    }
    var matchedString = matchResult[0];
    var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
    var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function(pattern) {
      return pattern.test(matchedString);
    }) : findKey(parsePatterns, function(pattern) {
      return pattern.test(matchedString);
    });
    var value;
    value = args.valueCallback ? args.valueCallback(key) : key;
    value = options.valueCallback ? options.valueCallback(value) : value;
    var rest = string.slice(matchedString.length);
    return {
      value,
      rest
    };
  };
}
function findKey(object, predicate) {
  for (var key in object) {
    if (object.hasOwnProperty(key) && predicate(object[key])) {
      return key;
    }
  }
  return void 0;
}
function findIndex(array, predicate) {
  for (var key = 0; key < array.length; key++) {
    if (predicate(array[key])) {
      return key;
    }
  }
  return void 0;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js
function buildMatchPatternFn(args) {
  return function(string) {
    var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    var matchResult = string.match(args.matchPattern);
    if (!matchResult)
      return null;
    var matchedString = matchResult[0];
    var parseResult = string.match(args.parsePattern);
    if (!parseResult)
      return null;
    var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
    value = options.valueCallback ? options.valueCallback(value) : value;
    var rest = string.slice(matchedString.length);
    return {
      value,
      rest
    };
  };
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/locale/en-US/_lib/match/index.js
var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
var parseOrdinalNumberPattern = /\d+/i;
var matchEraPatterns = {
  narrow: /^(b|a)/i,
  abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
  wide: /^(before christ|before common era|anno domini|common era)/i
};
var parseEraPatterns = {
  any: [/^b/i, /^(a|c)/i]
};
var matchQuarterPatterns = {
  narrow: /^[1234]/i,
  abbreviated: /^q[1234]/i,
  wide: /^[1234](th|st|nd|rd)? quarter/i
};
var parseQuarterPatterns = {
  any: [/1/i, /2/i, /3/i, /4/i]
};
var matchMonthPatterns = {
  narrow: /^[jfmasond]/i,
  abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
  wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
};
var parseMonthPatterns = {
  narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i],
  any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i]
};
var matchDayPatterns = {
  narrow: /^[smtwf]/i,
  short: /^(su|mo|tu|we|th|fr|sa)/i,
  abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
  wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
};
var parseDayPatterns = {
  narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
  any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
};
var matchDayPeriodPatterns = {
  narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
  any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
};
var parseDayPeriodPatterns = {
  any: {
    am: /^a/i,
    pm: /^p/i,
    midnight: /^mi/i,
    noon: /^no/i,
    morning: /morning/i,
    afternoon: /afternoon/i,
    evening: /evening/i,
    night: /night/i
  }
};
var match = {
  ordinalNumber: buildMatchPatternFn({
    matchPattern: matchOrdinalNumberPattern,
    parsePattern: parseOrdinalNumberPattern,
    valueCallback: function(value) {
      return parseInt(value, 10);
    }
  }),
  era: buildMatchFn({
    matchPatterns: matchEraPatterns,
    defaultMatchWidth: "wide",
    parsePatterns: parseEraPatterns,
    defaultParseWidth: "any"
  }),
  quarter: buildMatchFn({
    matchPatterns: matchQuarterPatterns,
    defaultMatchWidth: "wide",
    parsePatterns: parseQuarterPatterns,
    defaultParseWidth: "any",
    valueCallback: function(index) {
      return index + 1;
    }
  }),
  month: buildMatchFn({
    matchPatterns: matchMonthPatterns,
    defaultMatchWidth: "wide",
    parsePatterns: parseMonthPatterns,
    defaultParseWidth: "any"
  }),
  day: buildMatchFn({
    matchPatterns: matchDayPatterns,
    defaultMatchWidth: "wide",
    parsePatterns: parseDayPatterns,
    defaultParseWidth: "any"
  }),
  dayPeriod: buildMatchFn({
    matchPatterns: matchDayPeriodPatterns,
    defaultMatchWidth: "any",
    parsePatterns: parseDayPeriodPatterns,
    defaultParseWidth: "any"
  })
};
var match_default = match;

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/locale/en-US/index.js
var locale = {
  code: "en-US",
  formatDistance: formatDistance_default,
  formatLong: formatLong_default,
  formatRelative: formatRelative_default,
  localize: localize_default,
  match: match_default,
  options: {
    weekStartsOn: 0,
    firstWeekContainsDate: 1
  }
};
var en_US_default = locale;

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/defaultLocale/index.js
var defaultLocale_default = en_US_default;

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/format/index.js
var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
var escapedStringRegExp = /^'([^]*?)'?$/;
var doubleQuoteRegExp = /''/g;
var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
function format(dirtyDate, dirtyFormatStr, options) {
  var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4;
  requiredArgs(2, arguments);
  var formatStr = String(dirtyFormatStr);
  var defaultOptions2 = getDefaultOptions();
  var locale2 = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions2.locale) !== null && _ref !== void 0 ? _ref : defaultLocale_default;
  var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions2.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1);
  if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
    throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");
  }
  var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions2.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions2.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0);
  if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
    throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
  }
  if (!locale2.localize) {
    throw new RangeError("locale must contain localize property");
  }
  if (!locale2.formatLong) {
    throw new RangeError("locale must contain formatLong property");
  }
  var originalDate = toDate(dirtyDate);
  if (!isValid(originalDate)) {
    throw new RangeError("Invalid time value");
  }
  var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
  var utcDate = subMilliseconds(originalDate, timezoneOffset);
  var formatterOptions = {
    firstWeekContainsDate,
    weekStartsOn,
    locale: locale2,
    _originalDate: originalDate
  };
  var result = formatStr.match(longFormattingTokensRegExp).map(function(substring) {
    var firstCharacter = substring[0];
    if (firstCharacter === "p" || firstCharacter === "P") {
      var longFormatter = longFormatters_default[firstCharacter];
      return longFormatter(substring, locale2.formatLong);
    }
    return substring;
  }).join("").match(formattingTokensRegExp).map(function(substring) {
    if (substring === "''") {
      return "'";
    }
    var firstCharacter = substring[0];
    if (firstCharacter === "'") {
      return cleanEscapedString(substring);
    }
    var formatter = formatters_default[firstCharacter];
    if (formatter) {
      if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) {
        throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
      }
      if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) {
        throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
      }
      return formatter(utcDate, substring, locale2.localize, formatterOptions);
    }
    if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
      throw new RangeError("Format string contains an unescaped latin alphabet character `" + firstCharacter + "`");
    }
    return substring;
  }).join("");
  return result;
}
function cleanEscapedString(input) {
  var matched = input.match(escapedStringRegExp);
  if (!matched) {
    return input;
  }
  return matched[1].replace(doubleQuoteRegExp, "'");
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/assign/index.js
function assign(target, object) {
  if (target == null) {
    throw new TypeError("assign requires that input parameter not be null or undefined");
  }
  for (var property in object) {
    if (Object.prototype.hasOwnProperty.call(object, property)) {
      ;
      target[property] = object[property];
    }
  }
  return target;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/isAfter/index.js
function isAfter(dirtyDate, dirtyDateToCompare) {
  requiredArgs(2, arguments);
  var date = toDate(dirtyDate);
  var dateToCompare = toDate(dirtyDateToCompare);
  return date.getTime() > dateToCompare.getTime();
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/Setter.js
function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var TIMEZONE_UNIT_PRIORITY = 10;
var Setter = class {
  constructor() {
    _defineProperty(this, "priority", void 0);
    _defineProperty(this, "subPriority", 0);
  }
  validate(_utcDate, _options) {
    return true;
  }
};
var ValueSetter = class extends Setter {
  constructor(value, validateValue, setValue, priority, subPriority) {
    super();
    this.value = value;
    this.validateValue = validateValue;
    this.setValue = setValue;
    this.priority = priority;
    if (subPriority) {
      this.subPriority = subPriority;
    }
  }
  validate(utcDate, options) {
    return this.validateValue(utcDate, this.value, options);
  }
  set(utcDate, flags, options) {
    return this.setValue(utcDate, flags, this.value, options);
  }
};
var DateToSystemTimezoneSetter = class extends Setter {
  constructor() {
    super(...arguments);
    _defineProperty(this, "priority", TIMEZONE_UNIT_PRIORITY);
    _defineProperty(this, "subPriority", -1);
  }
  set(date, flags) {
    if (flags.timestampIsSet) {
      return date;
    }
    var convertedDate = /* @__PURE__ */ new Date(0);
    convertedDate.setFullYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
    convertedDate.setHours(date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
    return convertedDate;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/Parser.js
function _defineProperty2(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var Parser = class {
  constructor() {
    _defineProperty2(this, "incompatibleTokens", void 0);
    _defineProperty2(this, "priority", void 0);
    _defineProperty2(this, "subPriority", void 0);
  }
  run(dateString, token, match2, options) {
    var result = this.parse(dateString, token, match2, options);
    if (!result) {
      return null;
    }
    return {
      setter: new ValueSetter(result.value, this.validate, this.set, this.priority, this.subPriority),
      rest: result.rest
    };
  }
  validate(_utcDate, _value, _options) {
    return true;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/EraParser.js
function _defineProperty3(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var EraParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty3(this, "priority", 140);
    _defineProperty3(this, "incompatibleTokens", ["R", "u", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "G":
      case "GG":
      case "GGG":
        return match2.era(dateString, {
          width: "abbreviated"
        }) || match2.era(dateString, {
          width: "narrow"
        });
      case "GGGGG":
        return match2.era(dateString, {
          width: "narrow"
        });
      case "GGGG":
      default:
        return match2.era(dateString, {
          width: "wide"
        }) || match2.era(dateString, {
          width: "abbreviated"
        }) || match2.era(dateString, {
          width: "narrow"
        });
    }
  }
  set(date, flags, value) {
    flags.era = value;
    date.setUTCFullYear(value, 0, 1);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/constants.js
var numericPatterns = {
  month: /^(1[0-2]|0?\d)/,
  // 0 to 12
  date: /^(3[0-1]|[0-2]?\d)/,
  // 0 to 31
  dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,
  // 0 to 366
  week: /^(5[0-3]|[0-4]?\d)/,
  // 0 to 53
  hour23h: /^(2[0-3]|[0-1]?\d)/,
  // 0 to 23
  hour24h: /^(2[0-4]|[0-1]?\d)/,
  // 0 to 24
  hour11h: /^(1[0-1]|0?\d)/,
  // 0 to 11
  hour12h: /^(1[0-2]|0?\d)/,
  // 0 to 12
  minute: /^[0-5]?\d/,
  // 0 to 59
  second: /^[0-5]?\d/,
  // 0 to 59
  singleDigit: /^\d/,
  // 0 to 9
  twoDigits: /^\d{1,2}/,
  // 0 to 99
  threeDigits: /^\d{1,3}/,
  // 0 to 999
  fourDigits: /^\d{1,4}/,
  // 0 to 9999
  anyDigitsSigned: /^-?\d+/,
  singleDigitSigned: /^-?\d/,
  // 0 to 9, -0 to -9
  twoDigitsSigned: /^-?\d{1,2}/,
  // 0 to 99, -0 to -99
  threeDigitsSigned: /^-?\d{1,3}/,
  // 0 to 999, -0 to -999
  fourDigitsSigned: /^-?\d{1,4}/
  // 0 to 9999, -0 to -9999
};
var timezonePatterns = {
  basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/,
  basic: /^([+-])(\d{2})(\d{2})|Z/,
  basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,
  extended: /^([+-])(\d{2}):(\d{2})|Z/,
  extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/utils.js
function mapValue(parseFnResult, mapFn) {
  if (!parseFnResult) {
    return parseFnResult;
  }
  return {
    value: mapFn(parseFnResult.value),
    rest: parseFnResult.rest
  };
}
function parseNumericPattern(pattern, dateString) {
  var matchResult = dateString.match(pattern);
  if (!matchResult) {
    return null;
  }
  return {
    value: parseInt(matchResult[0], 10),
    rest: dateString.slice(matchResult[0].length)
  };
}
function parseTimezonePattern(pattern, dateString) {
  var matchResult = dateString.match(pattern);
  if (!matchResult) {
    return null;
  }
  if (matchResult[0] === "Z") {
    return {
      value: 0,
      rest: dateString.slice(1)
    };
  }
  var sign2 = matchResult[1] === "+" ? 1 : -1;
  var hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0;
  var minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0;
  var seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0;
  return {
    value: sign2 * (hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * millisecondsInSecond),
    rest: dateString.slice(matchResult[0].length)
  };
}
function parseAnyDigitsSigned(dateString) {
  return parseNumericPattern(numericPatterns.anyDigitsSigned, dateString);
}
function parseNDigits(n3, dateString) {
  switch (n3) {
    case 1:
      return parseNumericPattern(numericPatterns.singleDigit, dateString);
    case 2:
      return parseNumericPattern(numericPatterns.twoDigits, dateString);
    case 3:
      return parseNumericPattern(numericPatterns.threeDigits, dateString);
    case 4:
      return parseNumericPattern(numericPatterns.fourDigits, dateString);
    default:
      return parseNumericPattern(new RegExp("^\\d{1," + n3 + "}"), dateString);
  }
}
function parseNDigitsSigned(n3, dateString) {
  switch (n3) {
    case 1:
      return parseNumericPattern(numericPatterns.singleDigitSigned, dateString);
    case 2:
      return parseNumericPattern(numericPatterns.twoDigitsSigned, dateString);
    case 3:
      return parseNumericPattern(numericPatterns.threeDigitsSigned, dateString);
    case 4:
      return parseNumericPattern(numericPatterns.fourDigitsSigned, dateString);
    default:
      return parseNumericPattern(new RegExp("^-?\\d{1," + n3 + "}"), dateString);
  }
}
function dayPeriodEnumToHours(dayPeriod) {
  switch (dayPeriod) {
    case "morning":
      return 4;
    case "evening":
      return 17;
    case "pm":
    case "noon":
    case "afternoon":
      return 12;
    case "am":
    case "midnight":
    case "night":
    default:
      return 0;
  }
}
function normalizeTwoDigitYear(twoDigitYear, currentYear) {
  var isCommonEra = currentYear > 0;
  var absCurrentYear = isCommonEra ? currentYear : 1 - currentYear;
  var result;
  if (absCurrentYear <= 50) {
    result = twoDigitYear || 100;
  } else {
    var rangeEnd = absCurrentYear + 50;
    var rangeEndCentury = Math.floor(rangeEnd / 100) * 100;
    var isPreviousCentury = twoDigitYear >= rangeEnd % 100;
    result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0);
  }
  return isCommonEra ? result : 1 - result;
}
function isLeapYearIndex(year) {
  return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/YearParser.js
function _defineProperty4(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var YearParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty4(this, "priority", 130);
    _defineProperty4(this, "incompatibleTokens", ["Y", "R", "u", "w", "I", "i", "e", "c", "t", "T"]);
  }
  parse(dateString, token, match2) {
    var valueCallback = function(year) {
      return {
        year,
        isTwoDigitYear: token === "yy"
      };
    };
    switch (token) {
      case "y":
        return mapValue(parseNDigits(4, dateString), valueCallback);
      case "yo":
        return mapValue(match2.ordinalNumber(dateString, {
          unit: "year"
        }), valueCallback);
      default:
        return mapValue(parseNDigits(token.length, dateString), valueCallback);
    }
  }
  validate(_date, value) {
    return value.isTwoDigitYear || value.year > 0;
  }
  set(date, flags, value) {
    var currentYear = date.getUTCFullYear();
    if (value.isTwoDigitYear) {
      var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear);
      date.setUTCFullYear(normalizedTwoDigitYear, 0, 1);
      date.setUTCHours(0, 0, 0, 0);
      return date;
    }
    var year = !("era" in flags) || flags.era === 1 ? value.year : 1 - value.year;
    date.setUTCFullYear(year, 0, 1);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/LocalWeekYearParser.js
function _defineProperty5(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var LocalWeekYearParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty5(this, "priority", 130);
    _defineProperty5(this, "incompatibleTokens", ["y", "R", "u", "Q", "q", "M", "L", "I", "d", "D", "i", "t", "T"]);
  }
  parse(dateString, token, match2) {
    var valueCallback = function(year) {
      return {
        year,
        isTwoDigitYear: token === "YY"
      };
    };
    switch (token) {
      case "Y":
        return mapValue(parseNDigits(4, dateString), valueCallback);
      case "Yo":
        return mapValue(match2.ordinalNumber(dateString, {
          unit: "year"
        }), valueCallback);
      default:
        return mapValue(parseNDigits(token.length, dateString), valueCallback);
    }
  }
  validate(_date, value) {
    return value.isTwoDigitYear || value.year > 0;
  }
  set(date, flags, value, options) {
    var currentYear = getUTCWeekYear(date, options);
    if (value.isTwoDigitYear) {
      var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear);
      date.setUTCFullYear(normalizedTwoDigitYear, 0, options.firstWeekContainsDate);
      date.setUTCHours(0, 0, 0, 0);
      return startOfUTCWeek(date, options);
    }
    var year = !("era" in flags) || flags.era === 1 ? value.year : 1 - value.year;
    date.setUTCFullYear(year, 0, options.firstWeekContainsDate);
    date.setUTCHours(0, 0, 0, 0);
    return startOfUTCWeek(date, options);
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/ISOWeekYearParser.js
function _defineProperty6(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var ISOWeekYearParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty6(this, "priority", 130);
    _defineProperty6(this, "incompatibleTokens", ["G", "y", "Y", "u", "Q", "q", "M", "L", "w", "d", "D", "e", "c", "t", "T"]);
  }
  parse(dateString, token) {
    if (token === "R") {
      return parseNDigitsSigned(4, dateString);
    }
    return parseNDigitsSigned(token.length, dateString);
  }
  set(_date, _flags, value) {
    var firstWeekOfYear = /* @__PURE__ */ new Date(0);
    firstWeekOfYear.setUTCFullYear(value, 0, 4);
    firstWeekOfYear.setUTCHours(0, 0, 0, 0);
    return startOfUTCISOWeek(firstWeekOfYear);
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/ExtendedYearParser.js
function _defineProperty7(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var ExtendedYearParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty7(this, "priority", 130);
    _defineProperty7(this, "incompatibleTokens", ["G", "y", "Y", "R", "w", "I", "i", "e", "c", "t", "T"]);
  }
  parse(dateString, token) {
    if (token === "u") {
      return parseNDigitsSigned(4, dateString);
    }
    return parseNDigitsSigned(token.length, dateString);
  }
  set(date, _flags, value) {
    date.setUTCFullYear(value, 0, 1);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/QuarterParser.js
function _defineProperty8(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var QuarterParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty8(this, "priority", 120);
    _defineProperty8(this, "incompatibleTokens", ["Y", "R", "q", "M", "L", "w", "I", "d", "D", "i", "e", "c", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "Q":
      case "QQ":
        return parseNDigits(token.length, dateString);
      case "Qo":
        return match2.ordinalNumber(dateString, {
          unit: "quarter"
        });
      case "QQQ":
        return match2.quarter(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.quarter(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "QQQQQ":
        return match2.quarter(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "QQQQ":
      default:
        return match2.quarter(dateString, {
          width: "wide",
          context: "formatting"
        }) || match2.quarter(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.quarter(dateString, {
          width: "narrow",
          context: "formatting"
        });
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 4;
  }
  set(date, _flags, value) {
    date.setUTCMonth((value - 1) * 3, 1);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/StandAloneQuarterParser.js
function _defineProperty9(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var StandAloneQuarterParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty9(this, "priority", 120);
    _defineProperty9(this, "incompatibleTokens", ["Y", "R", "Q", "M", "L", "w", "I", "d", "D", "i", "e", "c", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "q":
      case "qq":
        return parseNDigits(token.length, dateString);
      case "qo":
        return match2.ordinalNumber(dateString, {
          unit: "quarter"
        });
      case "qqq":
        return match2.quarter(dateString, {
          width: "abbreviated",
          context: "standalone"
        }) || match2.quarter(dateString, {
          width: "narrow",
          context: "standalone"
        });
      case "qqqqq":
        return match2.quarter(dateString, {
          width: "narrow",
          context: "standalone"
        });
      case "qqqq":
      default:
        return match2.quarter(dateString, {
          width: "wide",
          context: "standalone"
        }) || match2.quarter(dateString, {
          width: "abbreviated",
          context: "standalone"
        }) || match2.quarter(dateString, {
          width: "narrow",
          context: "standalone"
        });
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 4;
  }
  set(date, _flags, value) {
    date.setUTCMonth((value - 1) * 3, 1);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/MonthParser.js
function _defineProperty10(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var MonthParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty10(this, "incompatibleTokens", ["Y", "R", "q", "Q", "L", "w", "I", "D", "i", "e", "c", "t", "T"]);
    _defineProperty10(this, "priority", 110);
  }
  parse(dateString, token, match2) {
    var valueCallback = function(value) {
      return value - 1;
    };
    switch (token) {
      case "M":
        return mapValue(parseNumericPattern(numericPatterns.month, dateString), valueCallback);
      case "MM":
        return mapValue(parseNDigits(2, dateString), valueCallback);
      case "Mo":
        return mapValue(match2.ordinalNumber(dateString, {
          unit: "month"
        }), valueCallback);
      case "MMM":
        return match2.month(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.month(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "MMMMM":
        return match2.month(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "MMMM":
      default:
        return match2.month(dateString, {
          width: "wide",
          context: "formatting"
        }) || match2.month(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.month(dateString, {
          width: "narrow",
          context: "formatting"
        });
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 11;
  }
  set(date, _flags, value) {
    date.setUTCMonth(value, 1);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/StandAloneMonthParser.js
function _defineProperty11(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var StandAloneMonthParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty11(this, "priority", 110);
    _defineProperty11(this, "incompatibleTokens", ["Y", "R", "q", "Q", "M", "w", "I", "D", "i", "e", "c", "t", "T"]);
  }
  parse(dateString, token, match2) {
    var valueCallback = function(value) {
      return value - 1;
    };
    switch (token) {
      case "L":
        return mapValue(parseNumericPattern(numericPatterns.month, dateString), valueCallback);
      case "LL":
        return mapValue(parseNDigits(2, dateString), valueCallback);
      case "Lo":
        return mapValue(match2.ordinalNumber(dateString, {
          unit: "month"
        }), valueCallback);
      case "LLL":
        return match2.month(dateString, {
          width: "abbreviated",
          context: "standalone"
        }) || match2.month(dateString, {
          width: "narrow",
          context: "standalone"
        });
      case "LLLLL":
        return match2.month(dateString, {
          width: "narrow",
          context: "standalone"
        });
      case "LLLL":
      default:
        return match2.month(dateString, {
          width: "wide",
          context: "standalone"
        }) || match2.month(dateString, {
          width: "abbreviated",
          context: "standalone"
        }) || match2.month(dateString, {
          width: "narrow",
          context: "standalone"
        });
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 11;
  }
  set(date, _flags, value) {
    date.setUTCMonth(value, 1);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/setUTCWeek/index.js
function setUTCWeek(dirtyDate, dirtyWeek, options) {
  requiredArgs(2, arguments);
  var date = toDate(dirtyDate);
  var week = toInteger(dirtyWeek);
  var diff = getUTCWeek(date, options) - week;
  date.setUTCDate(date.getUTCDate() - diff * 7);
  return date;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/LocalWeekParser.js
function _defineProperty12(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var LocalWeekParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty12(this, "priority", 100);
    _defineProperty12(this, "incompatibleTokens", ["y", "R", "u", "q", "Q", "M", "L", "I", "d", "D", "i", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "w":
        return parseNumericPattern(numericPatterns.week, dateString);
      case "wo":
        return match2.ordinalNumber(dateString, {
          unit: "week"
        });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 53;
  }
  set(date, _flags, value, options) {
    return startOfUTCWeek(setUTCWeek(date, value, options), options);
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/setUTCISOWeek/index.js
function setUTCISOWeek(dirtyDate, dirtyISOWeek) {
  requiredArgs(2, arguments);
  var date = toDate(dirtyDate);
  var isoWeek = toInteger(dirtyISOWeek);
  var diff = getUTCISOWeek(date) - isoWeek;
  date.setUTCDate(date.getUTCDate() - diff * 7);
  return date;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/ISOWeekParser.js
function _defineProperty13(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var ISOWeekParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty13(this, "priority", 100);
    _defineProperty13(this, "incompatibleTokens", ["y", "Y", "u", "q", "Q", "M", "L", "w", "d", "D", "e", "c", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "I":
        return parseNumericPattern(numericPatterns.week, dateString);
      case "Io":
        return match2.ordinalNumber(dateString, {
          unit: "week"
        });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 53;
  }
  set(date, _flags, value) {
    return startOfUTCISOWeek(setUTCISOWeek(date, value));
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/DateParser.js
function _defineProperty14(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var DateParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty14(this, "priority", 90);
    _defineProperty14(this, "subPriority", 1);
    _defineProperty14(this, "incompatibleTokens", ["Y", "R", "q", "Q", "w", "I", "D", "i", "e", "c", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "d":
        return parseNumericPattern(numericPatterns.date, dateString);
      case "do":
        return match2.ordinalNumber(dateString, {
          unit: "date"
        });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(date, value) {
    var year = date.getUTCFullYear();
    var isLeapYear = isLeapYearIndex(year);
    var month = date.getUTCMonth();
    if (isLeapYear) {
      return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month];
    } else {
      return value >= 1 && value <= DAYS_IN_MONTH[month];
    }
  }
  set(date, _flags, value) {
    date.setUTCDate(value);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/DayOfYearParser.js
function _defineProperty15(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var DayOfYearParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty15(this, "priority", 90);
    _defineProperty15(this, "subpriority", 1);
    _defineProperty15(this, "incompatibleTokens", ["Y", "R", "q", "Q", "M", "L", "w", "I", "d", "E", "i", "e", "c", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "D":
      case "DD":
        return parseNumericPattern(numericPatterns.dayOfYear, dateString);
      case "Do":
        return match2.ordinalNumber(dateString, {
          unit: "date"
        });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(date, value) {
    var year = date.getUTCFullYear();
    var isLeapYear = isLeapYearIndex(year);
    if (isLeapYear) {
      return value >= 1 && value <= 366;
    } else {
      return value >= 1 && value <= 365;
    }
  }
  set(date, _flags, value) {
    date.setUTCMonth(0, value);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/setUTCDay/index.js
function setUTCDay(dirtyDate, dirtyDay, options) {
  var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
  requiredArgs(2, arguments);
  var defaultOptions2 = getDefaultOptions();
  var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions2.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);
  if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
    throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
  }
  var date = toDate(dirtyDate);
  var day = toInteger(dirtyDay);
  var currentDay = date.getUTCDay();
  var remainder = day % 7;
  var dayIndex = (remainder + 7) % 7;
  var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay;
  date.setUTCDate(date.getUTCDate() + diff);
  return date;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/DayParser.js
function _defineProperty16(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var DayParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty16(this, "priority", 90);
    _defineProperty16(this, "incompatibleTokens", ["D", "i", "e", "c", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "E":
      case "EE":
      case "EEE":
        return match2.day(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "short",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "EEEEE":
        return match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "EEEEEE":
        return match2.day(dateString, {
          width: "short",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "EEEE":
      default:
        return match2.day(dateString, {
          width: "wide",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "short",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        });
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 6;
  }
  set(date, _flags, value, options) {
    date = setUTCDay(date, value, options);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/LocalDayParser.js
function _defineProperty17(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var LocalDayParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty17(this, "priority", 90);
    _defineProperty17(this, "incompatibleTokens", ["y", "R", "u", "q", "Q", "M", "L", "I", "d", "D", "E", "i", "c", "t", "T"]);
  }
  parse(dateString, token, match2, options) {
    var valueCallback = function(value) {
      var wholeWeekDays = Math.floor((value - 1) / 7) * 7;
      return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays;
    };
    switch (token) {
      case "e":
      case "ee":
        return mapValue(parseNDigits(token.length, dateString), valueCallback);
      case "eo":
        return mapValue(match2.ordinalNumber(dateString, {
          unit: "day"
        }), valueCallback);
      case "eee":
        return match2.day(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "short",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "eeeee":
        return match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "eeeeee":
        return match2.day(dateString, {
          width: "short",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "eeee":
      default:
        return match2.day(dateString, {
          width: "wide",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "short",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        });
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 6;
  }
  set(date, _flags, value, options) {
    date = setUTCDay(date, value, options);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/StandAloneLocalDayParser.js
function _defineProperty18(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var StandAloneLocalDayParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty18(this, "priority", 90);
    _defineProperty18(this, "incompatibleTokens", ["y", "R", "u", "q", "Q", "M", "L", "I", "d", "D", "E", "i", "e", "t", "T"]);
  }
  parse(dateString, token, match2, options) {
    var valueCallback = function(value) {
      var wholeWeekDays = Math.floor((value - 1) / 7) * 7;
      return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays;
    };
    switch (token) {
      case "c":
      case "cc":
        return mapValue(parseNDigits(token.length, dateString), valueCallback);
      case "co":
        return mapValue(match2.ordinalNumber(dateString, {
          unit: "day"
        }), valueCallback);
      case "ccc":
        return match2.day(dateString, {
          width: "abbreviated",
          context: "standalone"
        }) || match2.day(dateString, {
          width: "short",
          context: "standalone"
        }) || match2.day(dateString, {
          width: "narrow",
          context: "standalone"
        });
      case "ccccc":
        return match2.day(dateString, {
          width: "narrow",
          context: "standalone"
        });
      case "cccccc":
        return match2.day(dateString, {
          width: "short",
          context: "standalone"
        }) || match2.day(dateString, {
          width: "narrow",
          context: "standalone"
        });
      case "cccc":
      default:
        return match2.day(dateString, {
          width: "wide",
          context: "standalone"
        }) || match2.day(dateString, {
          width: "abbreviated",
          context: "standalone"
        }) || match2.day(dateString, {
          width: "short",
          context: "standalone"
        }) || match2.day(dateString, {
          width: "narrow",
          context: "standalone"
        });
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 6;
  }
  set(date, _flags, value, options) {
    date = setUTCDay(date, value, options);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/_lib/setUTCISODay/index.js
function setUTCISODay(dirtyDate, dirtyDay) {
  requiredArgs(2, arguments);
  var day = toInteger(dirtyDay);
  if (day % 7 === 0) {
    day = day - 7;
  }
  var weekStartsOn = 1;
  var date = toDate(dirtyDate);
  var currentDay = date.getUTCDay();
  var remainder = day % 7;
  var dayIndex = (remainder + 7) % 7;
  var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay;
  date.setUTCDate(date.getUTCDate() + diff);
  return date;
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/ISODayParser.js
function _defineProperty19(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var ISODayParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty19(this, "priority", 90);
    _defineProperty19(this, "incompatibleTokens", ["y", "Y", "u", "q", "Q", "M", "L", "w", "d", "D", "E", "e", "c", "t", "T"]);
  }
  parse(dateString, token, match2) {
    var valueCallback = function(value) {
      if (value === 0) {
        return 7;
      }
      return value;
    };
    switch (token) {
      case "i":
      case "ii":
        return parseNDigits(token.length, dateString);
      case "io":
        return match2.ordinalNumber(dateString, {
          unit: "day"
        });
      case "iii":
        return mapValue(match2.day(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "short",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        }), valueCallback);
      case "iiiii":
        return mapValue(match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        }), valueCallback);
      case "iiiiii":
        return mapValue(match2.day(dateString, {
          width: "short",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        }), valueCallback);
      case "iiii":
      default:
        return mapValue(match2.day(dateString, {
          width: "wide",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "short",
          context: "formatting"
        }) || match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        }), valueCallback);
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 7;
  }
  set(date, _flags, value) {
    date = setUTCISODay(date, value);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/AMPMParser.js
function _defineProperty20(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var AMPMParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty20(this, "priority", 80);
    _defineProperty20(this, "incompatibleTokens", ["b", "B", "H", "k", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "a":
      case "aa":
      case "aaa":
        return match2.dayPeriod(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "aaaaa":
        return match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "aaaa":
      default:
        return match2.dayPeriod(dateString, {
          width: "wide",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
    }
  }
  set(date, _flags, value) {
    date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/AMPMMidnightParser.js
function _defineProperty21(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var AMPMMidnightParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty21(this, "priority", 80);
    _defineProperty21(this, "incompatibleTokens", ["a", "B", "H", "k", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "b":
      case "bb":
      case "bbb":
        return match2.dayPeriod(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "bbbbb":
        return match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "bbbb":
      default:
        return match2.dayPeriod(dateString, {
          width: "wide",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
    }
  }
  set(date, _flags, value) {
    date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/DayPeriodParser.js
function _defineProperty22(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var DayPeriodParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty22(this, "priority", 80);
    _defineProperty22(this, "incompatibleTokens", ["a", "b", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "B":
      case "BB":
      case "BBB":
        return match2.dayPeriod(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "BBBBB":
        return match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "BBBB":
      default:
        return match2.dayPeriod(dateString, {
          width: "wide",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
    }
  }
  set(date, _flags, value) {
    date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/Hour1to12Parser.js
function _defineProperty23(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var Hour1to12Parser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty23(this, "priority", 70);
    _defineProperty23(this, "incompatibleTokens", ["H", "K", "k", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "h":
        return parseNumericPattern(numericPatterns.hour12h, dateString);
      case "ho":
        return match2.ordinalNumber(dateString, {
          unit: "hour"
        });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 12;
  }
  set(date, _flags, value) {
    var isPM = date.getUTCHours() >= 12;
    if (isPM && value < 12) {
      date.setUTCHours(value + 12, 0, 0, 0);
    } else if (!isPM && value === 12) {
      date.setUTCHours(0, 0, 0, 0);
    } else {
      date.setUTCHours(value, 0, 0, 0);
    }
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/Hour0to23Parser.js
function _defineProperty24(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var Hour0to23Parser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty24(this, "priority", 70);
    _defineProperty24(this, "incompatibleTokens", ["a", "b", "h", "K", "k", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "H":
        return parseNumericPattern(numericPatterns.hour23h, dateString);
      case "Ho":
        return match2.ordinalNumber(dateString, {
          unit: "hour"
        });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 23;
  }
  set(date, _flags, value) {
    date.setUTCHours(value, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/Hour0To11Parser.js
function _defineProperty25(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var Hour0To11Parser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty25(this, "priority", 70);
    _defineProperty25(this, "incompatibleTokens", ["h", "H", "k", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "K":
        return parseNumericPattern(numericPatterns.hour11h, dateString);
      case "Ko":
        return match2.ordinalNumber(dateString, {
          unit: "hour"
        });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 11;
  }
  set(date, _flags, value) {
    var isPM = date.getUTCHours() >= 12;
    if (isPM && value < 12) {
      date.setUTCHours(value + 12, 0, 0, 0);
    } else {
      date.setUTCHours(value, 0, 0, 0);
    }
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/Hour1To24Parser.js
function _defineProperty26(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var Hour1To24Parser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty26(this, "priority", 70);
    _defineProperty26(this, "incompatibleTokens", ["a", "b", "h", "H", "K", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "k":
        return parseNumericPattern(numericPatterns.hour24h, dateString);
      case "ko":
        return match2.ordinalNumber(dateString, {
          unit: "hour"
        });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 24;
  }
  set(date, _flags, value) {
    var hours = value <= 24 ? value % 24 : value;
    date.setUTCHours(hours, 0, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/MinuteParser.js
function _defineProperty27(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var MinuteParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty27(this, "priority", 60);
    _defineProperty27(this, "incompatibleTokens", ["t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "m":
        return parseNumericPattern(numericPatterns.minute, dateString);
      case "mo":
        return match2.ordinalNumber(dateString, {
          unit: "minute"
        });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 59;
  }
  set(date, _flags, value) {
    date.setUTCMinutes(value, 0, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/SecondParser.js
function _defineProperty28(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var SecondParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty28(this, "priority", 50);
    _defineProperty28(this, "incompatibleTokens", ["t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "s":
        return parseNumericPattern(numericPatterns.second, dateString);
      case "so":
        return match2.ordinalNumber(dateString, {
          unit: "second"
        });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 59;
  }
  set(date, _flags, value) {
    date.setUTCSeconds(value, 0);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/FractionOfSecondParser.js
function _defineProperty29(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var FractionOfSecondParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty29(this, "priority", 30);
    _defineProperty29(this, "incompatibleTokens", ["t", "T"]);
  }
  parse(dateString, token) {
    var valueCallback = function(value) {
      return Math.floor(value * Math.pow(10, -token.length + 3));
    };
    return mapValue(parseNDigits(token.length, dateString), valueCallback);
  }
  set(date, _flags, value) {
    date.setUTCMilliseconds(value);
    return date;
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/ISOTimezoneWithZParser.js
function _defineProperty30(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var ISOTimezoneWithZParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty30(this, "priority", 10);
    _defineProperty30(this, "incompatibleTokens", ["t", "T", "x"]);
  }
  parse(dateString, token) {
    switch (token) {
      case "X":
        return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, dateString);
      case "XX":
        return parseTimezonePattern(timezonePatterns.basic, dateString);
      case "XXXX":
        return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, dateString);
      case "XXXXX":
        return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, dateString);
      case "XXX":
      default:
        return parseTimezonePattern(timezonePatterns.extended, dateString);
    }
  }
  set(date, flags, value) {
    if (flags.timestampIsSet) {
      return date;
    }
    return new Date(date.getTime() - value);
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/ISOTimezoneParser.js
function _defineProperty31(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var ISOTimezoneParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty31(this, "priority", 10);
    _defineProperty31(this, "incompatibleTokens", ["t", "T", "X"]);
  }
  parse(dateString, token) {
    switch (token) {
      case "x":
        return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, dateString);
      case "xx":
        return parseTimezonePattern(timezonePatterns.basic, dateString);
      case "xxxx":
        return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, dateString);
      case "xxxxx":
        return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, dateString);
      case "xxx":
      default:
        return parseTimezonePattern(timezonePatterns.extended, dateString);
    }
  }
  set(date, flags, value) {
    if (flags.timestampIsSet) {
      return date;
    }
    return new Date(date.getTime() - value);
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/TimestampSecondsParser.js
function _defineProperty32(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var TimestampSecondsParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty32(this, "priority", 40);
    _defineProperty32(this, "incompatibleTokens", "*");
  }
  parse(dateString) {
    return parseAnyDigitsSigned(dateString);
  }
  set(_date, _flags, value) {
    return [new Date(value * 1e3), {
      timestampIsSet: true
    }];
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/TimestampMillisecondsParser.js
function _defineProperty33(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
var TimestampMillisecondsParser = class extends Parser {
  constructor() {
    super(...arguments);
    _defineProperty33(this, "priority", 20);
    _defineProperty33(this, "incompatibleTokens", "*");
  }
  parse(dateString) {
    return parseAnyDigitsSigned(dateString);
  }
  set(_date, _flags, value) {
    return [new Date(value), {
      timestampIsSet: true
    }];
  }
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/_lib/parsers/index.js
var parsers2 = {
  G: new EraParser(),
  y: new YearParser(),
  Y: new LocalWeekYearParser(),
  R: new ISOWeekYearParser(),
  u: new ExtendedYearParser(),
  Q: new QuarterParser(),
  q: new StandAloneQuarterParser(),
  M: new MonthParser(),
  L: new StandAloneMonthParser(),
  w: new LocalWeekParser(),
  I: new ISOWeekParser(),
  d: new DateParser(),
  D: new DayOfYearParser(),
  E: new DayParser(),
  e: new LocalDayParser(),
  c: new StandAloneLocalDayParser(),
  i: new ISODayParser(),
  a: new AMPMParser(),
  b: new AMPMMidnightParser(),
  B: new DayPeriodParser(),
  h: new Hour1to12Parser(),
  H: new Hour0to23Parser(),
  K: new Hour0To11Parser(),
  k: new Hour1To24Parser(),
  m: new MinuteParser(),
  s: new SecondParser(),
  S: new FractionOfSecondParser(),
  X: new ISOTimezoneWithZParser(),
  x: new ISOTimezoneParser(),
  t: new TimestampSecondsParser(),
  T: new TimestampMillisecondsParser()
};

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/parse/index.js
var formattingTokensRegExp2 = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
var longFormattingTokensRegExp2 = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
var escapedStringRegExp2 = /^'([^]*?)'?$/;
var doubleQuoteRegExp2 = /''/g;
var notWhitespaceRegExp = /\S/;
var unescapedLatinCharacterRegExp2 = /[a-zA-Z]/;
function parse(dirtyDateString, dirtyFormatString, dirtyReferenceDate, options) {
  var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4;
  requiredArgs(3, arguments);
  var dateString = String(dirtyDateString);
  var formatString = String(dirtyFormatString);
  var defaultOptions2 = getDefaultOptions();
  var locale2 = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions2.locale) !== null && _ref !== void 0 ? _ref : defaultLocale_default;
  if (!locale2.match) {
    throw new RangeError("locale must contain match property");
  }
  var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions2.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1);
  if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
    throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");
  }
  var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions2.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions2.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0);
  if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
    throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
  }
  if (formatString === "") {
    if (dateString === "") {
      return toDate(dirtyReferenceDate);
    } else {
      return /* @__PURE__ */ new Date(NaN);
    }
  }
  var subFnOptions = {
    firstWeekContainsDate,
    weekStartsOn,
    locale: locale2
  };
  var setters = [new DateToSystemTimezoneSetter()];
  var tokens = formatString.match(longFormattingTokensRegExp2).map(function(substring) {
    var firstCharacter = substring[0];
    if (firstCharacter in longFormatters_default) {
      var longFormatter = longFormatters_default[firstCharacter];
      return longFormatter(substring, locale2.formatLong);
    }
    return substring;
  }).join("").match(formattingTokensRegExp2);
  var usedTokens = [];
  var _loop = function(_token) {
    if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(_token)) {
      throwProtectedError(_token, formatString, dirtyDateString);
    }
    if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(_token)) {
      throwProtectedError(_token, formatString, dirtyDateString);
    }
    var firstCharacter = _token[0];
    var parser = parsers2[firstCharacter];
    if (parser) {
      var incompatibleTokens = parser.incompatibleTokens;
      if (Array.isArray(incompatibleTokens)) {
        var incompatibleToken = usedTokens.find(function(usedToken) {
          return incompatibleTokens.includes(usedToken.token) || usedToken.token === firstCharacter;
        });
        if (incompatibleToken) {
          throw new RangeError("The format string mustn't contain `".concat(incompatibleToken.fullToken, "` and `").concat(_token, "` at the same time"));
        }
      } else if (parser.incompatibleTokens === "*" && usedTokens.length > 0) {
        throw new RangeError("The format string mustn't contain `".concat(_token, "` and any other token at the same time"));
      }
      usedTokens.push({
        token: firstCharacter,
        fullToken: _token
      });
      var parseResult = parser.run(dateString, _token, locale2.match, subFnOptions);
      if (!parseResult) {
        token = _token;
        return {
          v: /* @__PURE__ */ new Date(NaN)
        };
      }
      setters.push(parseResult.setter);
      dateString = parseResult.rest;
    } else {
      if (firstCharacter.match(unescapedLatinCharacterRegExp2)) {
        throw new RangeError("Format string contains an unescaped latin alphabet character `" + firstCharacter + "`");
      }
      if (_token === "''") {
        _token = "'";
      } else if (firstCharacter === "'") {
        _token = cleanEscapedString2(_token);
      }
      if (dateString.indexOf(_token) === 0) {
        dateString = dateString.slice(_token.length);
      } else {
        token = _token;
        return {
          v: /* @__PURE__ */ new Date(NaN)
        };
      }
    }
    token = _token;
  };
  for (var token of tokens) {
    var _ret = _loop(token);
    if (typeof _ret === "object")
      return _ret.v;
  }
  if (dateString.length > 0 && notWhitespaceRegExp.test(dateString)) {
    return /* @__PURE__ */ new Date(NaN);
  }
  var uniquePrioritySetters = setters.map(function(setter2) {
    return setter2.priority;
  }).sort(function(a4, b4) {
    return b4 - a4;
  }).filter(function(priority, index, array) {
    return array.indexOf(priority) === index;
  }).map(function(priority) {
    return setters.filter(function(setter2) {
      return setter2.priority === priority;
    }).sort(function(a4, b4) {
      return b4.subPriority - a4.subPriority;
    });
  }).map(function(setterArray) {
    return setterArray[0];
  });
  var date = toDate(dirtyReferenceDate);
  if (isNaN(date.getTime())) {
    return /* @__PURE__ */ new Date(NaN);
  }
  var utcDate = subMilliseconds(date, getTimezoneOffsetInMilliseconds(date));
  var flags = {};
  for (var setter of uniquePrioritySetters) {
    if (!setter.validate(utcDate, subFnOptions)) {
      return /* @__PURE__ */ new Date(NaN);
    }
    var result = setter.set(utcDate, flags, subFnOptions);
    if (Array.isArray(result)) {
      utcDate = result[0];
      assign(flags, result[1]);
    } else {
      utcDate = result;
    }
  }
  return utcDate;
}
function cleanEscapedString2(input) {
  return input.match(escapedStringRegExp2)[1].replace(doubleQuoteRegExp2, "'");
}

// ../../node_modules/.pnpm/date-fns@2.29.2/node_modules/date-fns/esm/subYears/index.js
function subYears(dirtyDate, dirtyAmount) {
  requiredArgs(2, arguments);
  var amount = toInteger(dirtyAmount);
  return addYears(dirtyDate, -amount);
}

// src/pages/home/AttributeEntryScreen.tsx
init_preact_module();

// src/components/fields/DateInput.tsx
init_preact_module();

// src/components/picker/DatePicker.tsx
init_preact_module();
var now = /* @__PURE__ */ new Date();
var monthArrShortFull = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
];
var monthArrShort = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec"
];
var dayArr = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var yearArr = [];
var DatePicker = class extends d {
  closeDatePicker() {
    this.props.closeFunction && this.props.closeFunction();
  }
  /**
   * Gets fired when a day gets clicked.
   * @param {object} e The event thrown by the <span /> element clicked
   */
  dayClicked(e4) {
    const element = e4.target;
    if (element.innerHTML === "")
      return false;
    const date = new Date(element.getAttribute("data-value"));
    this.setState({ currentDate: date });
    this.passDateToParent(date);
  }
  /**
   * returns days in month as array
   * @param {number} month the month to display
   * @param {number} year the year to display
   */
  getDaysByMonth(month, year) {
    const calendar = [];
    const date = new Date(year, month, 1);
    const firstDay = new Date(year, month, 1).getDay();
    const lastDate = new Date(year, month + 1, 0).getDate();
    let day = 0;
    for (let i4 = 0; i4 < 42; i4++) {
      if (i4 >= firstDay && day !== null)
        day = day + 1;
      if (day !== null && day > lastDate)
        day = null;
      calendar.push({
        day: day === 0 || day === null ? null : day,
        // null or number
        date: day === 0 || day === null ? null : new Date(year, month, day),
        // null or Date()
        today: day === now.getDate() && month === now.getMonth() && year === now.getFullYear()
        // boolean
      });
    }
    return calendar;
  }
  /**
   * Display previous month by updating state
   */
  displayPrevMonth() {
    if (this.state.displayedMonth <= 0) {
      this.setState({
        displayedMonth: 11,
        displayedYear: this.state.displayedYear - 1
      });
    } else {
      this.setState({
        displayedMonth: this.state.displayedMonth - 1
      });
    }
  }
  /**
   * Display next month by updating state
   */
  displayNextMonth() {
    if (this.state.displayedMonth >= 11) {
      this.setState({
        displayedMonth: 0,
        displayedYear: this.state.displayedYear + 1
      });
    } else {
      this.setState({
        displayedMonth: this.state.displayedMonth + 1
      });
    }
  }
  /**
   * Display the selected month (gets fired when clicking on the date string)
   */
  displaySelectedMonth() {
    if (this.state.selectYearMode) {
      this.toggleYearSelector();
    } else {
      if (!this.state.currentDate)
        return false;
      this.setState({
        displayedMonth: this.state.currentDate.getMonth(),
        displayedYear: this.state.currentDate.getFullYear()
      });
    }
  }
  toggleYearSelector() {
    this.setState({ selectYearMode: !this.state.selectYearMode });
  }
  changeDisplayedYear(e4) {
    const element = e4.target;
    this.toggleYearSelector();
    this.setState({
      displayedYear: parseInt(element.innerHTML, 10),
      displayedMonth: 0
    });
  }
  /**
   * Pass the selected date to parent when 'OK' is clicked
   */
  passSavedDateDateToParent() {
    this.passDateToParent(this.state.currentDate);
  }
  passDateToParent(date) {
    if (typeof this.props.dateReceiver === "function")
      this.props.dateReceiver(date);
    this.closeDatePicker();
  }
  componentDidUpdate() {
  }
  constructor(props) {
    super(props);
    this.closeDatePicker = this.closeDatePicker.bind(this);
    this.dayClicked = this.dayClicked.bind(this);
    this.displayNextMonth = this.displayNextMonth.bind(this);
    this.displayPrevMonth = this.displayPrevMonth.bind(this);
    this.getDaysByMonth = this.getDaysByMonth.bind(this);
    this.changeDisplayedYear = this.changeDisplayedYear.bind(this);
    this.passDateToParent = this.passDateToParent.bind(this);
    this.toggleYearSelector = this.toggleYearSelector.bind(this);
    this.displaySelectedMonth = this.displaySelectedMonth.bind(this);
    const initial3 = props.initialDate || now;
    this.state = {
      currentDate: initial3,
      displayedMonth: initial3.getMonth(),
      displayedYear: initial3.getFullYear(),
      selectYearMode: false
    };
  }
  render() {
    const { currentDate, displayedMonth, displayedYear, selectYearMode } = this.state;
    return /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("div", { class: `datePicker ${this.props.opened && "datePicker--opened"}` }, /* @__PURE__ */ h("div", { class: "datePicker--titles" }, /* @__PURE__ */ h(
      "h3",
      {
        style: {
          color: selectYearMode ? "rgba(255,255,255,.87)" : "rgba(255,255,255,.57)"
        },
        onClick: this.toggleYearSelector
      },
      currentDate.getFullYear()
    ), /* @__PURE__ */ h(
      "h2",
      {
        style: {
          color: !selectYearMode ? "rgba(255,255,255,.87)" : "rgba(255,255,255,.57)"
        },
        onClick: this.displaySelectedMonth
      },
      dayArr[currentDate.getDay()],
      ",",
      " ",
      monthArrShort[currentDate.getMonth()],
      " ",
      currentDate.getDate()
    )), !selectYearMode && /* @__PURE__ */ h("nav", null, /* @__PURE__ */ h("span", { onClick: this.displayPrevMonth, class: "icon" }, /* @__PURE__ */ h(
      "i",
      {
        style: { transform: "rotate(180deg)" },
        class: "mdi mdi-forward"
      }
    )), /* @__PURE__ */ h("h4", null, monthArrShortFull[displayedMonth], " ", displayedYear), /* @__PURE__ */ h("span", { onClick: this.displayNextMonth, class: "icon" }, /* @__PURE__ */ h("i", { class: "mdi mdi-forward" }))), /* @__PURE__ */ h("div", { class: "datePicker--scroll" }, !selectYearMode && /* @__PURE__ */ h("div", { class: "datePicker--calendar" }, /* @__PURE__ */ h("div", { class: "datePicker--dayNames" }, ["S", "M", "T", "W", "T", "F", "S"].map((day, i4) => /* @__PURE__ */ h("span", { key: i4 }, day))), /* @__PURE__ */ h("div", { onClick: this.dayClicked, class: "datePicker--days" }, this.getDaysByMonth(
      this.state.displayedMonth,
      this.state.displayedYear
    ).map((day) => {
      let selected = false;
      if (currentDate && day.date)
        selected = currentDate.toLocaleDateString() === day.date.toLocaleDateString();
      return /* @__PURE__ */ h(
        "span",
        {
          key: day.day,
          class: (day.today ? "datePicker--today " : "") + (selected ? "datePicker--selected" : ""),
          disabled: !day.date,
          "data-value": day.date
        },
        day.day
      );
    }))), selectYearMode && /* @__PURE__ */ h("div", { class: "datePicker--selectYear" }, (this.props.years || yearArr).map((year) => /* @__PURE__ */ h(
      "span",
      {
        key: year,
        class: year === displayedYear ? "selected" : "",
        onClick: this.changeDisplayedYear
      },
      year
    ))))), /* @__PURE__ */ h(
      "div",
      {
        class: "datePicker--background",
        onClick: this.closeDatePicker,
        style: {
          display: this.props.opened ? "block" : "none"
        }
      }
    ));
  }
};
for (let i4 = 2010; i4 <= now.getFullYear() + 10; i4++) {
  yearArr.push(i4);
}

// src/components/fields/DateInput.tsx
function DateInput(props) {
  const inputRef = _2(null);
  s2(() => {
    if (props.grabFocus) {
      inputRef.current?.focus();
    }
  }, [props.grabFocus]);
  const [opened, setOpened] = p3(false);
  const value = props.bind[0] || "";
  const [dirty, setDirty] = p3(false);
  const showError = dirty && props.error;
  const calendar = subYears(/* @__PURE__ */ new Date(), 30);
  return /* @__PURE__ */ h("div", { class: "field" }, /* @__PURE__ */ h("label", { class: "label" }, props.label, props.tooltip && /* @__PURE__ */ h("span", { class: "icon has-tooltip-right", "data-tooltip": props.tooltip }, /* @__PURE__ */ h("i", { class: "mdi mdi-information" }))), /* @__PURE__ */ h("div", { class: "control" }, /* @__PURE__ */ h("div", { class: "field has-addons" }, /* @__PURE__ */ h("p", { class: "control" }, /* @__PURE__ */ h(
    "input",
    {
      type: "text",
      class: showError ? "input is-danger" : "input",
      value,
      onKeyPress: (e4) => {
        if (e4.key === "Enter" && props.onConfirm) {
          props.onConfirm();
        }
      },
      onInput: (e4) => {
        const text = e4.currentTarget.value;
        setDirty(true);
        props.bind[1](text);
      },
      ref: inputRef
    }
  )), /* @__PURE__ */ h("p", { class: "control" }, /* @__PURE__ */ h(
    "a",
    {
      class: "button",
      onClick: () => {
        setOpened(true);
      }
    },
    /* @__PURE__ */ h("span", { class: "icon" }, /* @__PURE__ */ h("i", { class: "mdi mdi-calendar" }))
  )))), /* @__PURE__ */ h("p", { class: "help" }, "Using the format yyyy-mm-dd"), showError && /* @__PURE__ */ h("p", { class: "help is-danger" }, props.error), /* @__PURE__ */ h(
    DatePicker,
    {
      opened,
      initialDate: calendar,
      years: props.years,
      closeFunction: () => setOpened(false),
      dateReceiver: (d4) => {
        setDirty(true);
        const v4 = format(d4, "yyyy-MM-dd");
        props.bind[1](v4);
      }
    }
  ));
}

// src/components/fields/NumberInput.tsx
init_preact_module();
function PhoneNumberInput(props) {
  const inputRef = _2(null);
  s2(() => {
    if (props.grabFocus) {
      inputRef.current?.focus();
    }
  }, [props.grabFocus]);
  const value = props.bind[0];
  const [dirty, setDirty] = p3(false);
  const showError = dirty && props.error;
  return /* @__PURE__ */ h("div", { class: "field" }, /* @__PURE__ */ h("label", { class: "label" }, props.label, props.tooltip && /* @__PURE__ */ h("span", { class: "icon has-tooltip-right", "data-tooltip": props.tooltip }, /* @__PURE__ */ h("i", { class: "mdi mdi-information" }))), /* @__PURE__ */ h("div", { class: "control has-icons-right" }, /* @__PURE__ */ h(
    "input",
    {
      value,
      type: "tel",
      placeholder: props.placeholder,
      class: showError ? "input is-danger" : "input",
      onKeyPress: (e4) => {
        if (e4.key === "Enter" && props.onConfirm) {
          props.onConfirm();
        }
      },
      onInput: (e4) => {
        setDirty(true);
        props.bind[1](e4.target.value);
      },
      ref: inputRef,
      style: { display: "block" }
    }
  )), showError && /* @__PURE__ */ h("p", { class: "help is-danger" }, props.error));
}

// src/components/fields/TextInput.tsx
init_preact_module();
var TextInputType = function({ inputType, grabFocus, ...rest }) {
  const inputRef = _2(null);
  s2(() => {
    if (grabFocus) {
      inputRef.current?.focus();
    }
  }, [grabFocus]);
  return inputType === "multiline" ? /* @__PURE__ */ h("textarea", { ...rest, rows: 5, ref: inputRef, style: { height: "unset" } }) : /* @__PURE__ */ h("input", { ...rest, type: inputType, ref: inputRef });
};
function TextInput(props) {
  const value = props.bind[0];
  const [dirty, setDirty] = p3(false);
  const showError = dirty && props.error;
  return /* @__PURE__ */ h("div", { class: "field" }, /* @__PURE__ */ h("label", { class: "label" }, props.label, props.tooltip && /* @__PURE__ */ h("span", { class: "icon has-tooltip-right", "data-tooltip": props.tooltip }, /* @__PURE__ */ h("i", { class: "mdi mdi-information" }))), /* @__PURE__ */ h("div", { class: "control has-icons-right" }, /* @__PURE__ */ h(
    TextInputType,
    {
      inputType: props.inputType,
      value,
      grabFocus: props.grabFocus,
      disabled: props.disabled,
      placeholder: props.placeholder,
      class: showError ? "input is-danger" : "input",
      onKeyPress: (e4) => {
        if (e4.key === "Enter" && props.onConfirm) {
          props.onConfirm();
        }
      },
      onInput: (e4) => {
        setDirty(true);
        props.bind[1](e4.target.value);
      },
      style: { display: "block" }
    }
  )), showError && /* @__PURE__ */ h("p", { class: "help is-danger" }, props.error));
}

// src/pages/home/ConfirmModal.tsx
init_preact_module();
function ConfirmModal({
  active,
  description,
  onCancel,
  onConfirm,
  children,
  danger,
  disabled,
  label = "Confirm",
  cancelLabel = "Dismiss"
}) {
  return /* @__PURE__ */ h("div", { class: active ? "modal is-active" : "modal" }, /* @__PURE__ */ h("div", { class: "modal-background ", onClick: onCancel }), /* @__PURE__ */ h("div", { class: "modal-card", style: { maxWidth: 700 } }, /* @__PURE__ */ h("header", { class: "modal-card-head" }, !description ? null : /* @__PURE__ */ h("p", { class: "modal-card-title" }, /* @__PURE__ */ h("b", null, description)), /* @__PURE__ */ h("button", { class: "delete ", "aria-label": "close", onClick: onCancel })), /* @__PURE__ */ h("section", { class: "modal-card-body" }, children), /* @__PURE__ */ h("footer", { class: "modal-card-foot" }, /* @__PURE__ */ h("button", { class: "button", onClick: onCancel }, cancelLabel), /* @__PURE__ */ h(
    "div",
    {
      class: "buttons is-right",
      style: { width: "100%" },
      onKeyDown: (e4) => {
        if (e4.key === "Escape" && onCancel)
          onCancel();
      }
    },
    /* @__PURE__ */ h(
      AsyncButton,
      {
        grabFocus: true,
        class: danger ? "button is-danger " : "button is-info ",
        disabled,
        onClick: onConfirm
      },
      label
    )
  ))), /* @__PURE__ */ h(
    "button",
    {
      class: "modal-close is-large ",
      "aria-label": "close",
      onClick: onCancel
    }
  ));
}

// src/pages/home/AttributeEntryScreen.tsx
function AttributeEntryScreen() {
  const reducer = useAnastasisContext();
  const state = reducer?.currentReducerState;
  const currentIdentityAttributes = state && "identity_attributes" in state ? state.identity_attributes || {} : {};
  const [attrs, setAttrs] = p3(
    currentIdentityAttributes
  );
  const isBackup2 = state?.reducer_type === "backup";
  const [askUserIfSure, setAskUserIfSure] = p3(false);
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (!reducer.currentReducerState || !("required_attributes" in reducer.currentReducerState)) {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  const reqAttr = reducer.currentReducerState.required_attributes || [];
  let hasErrors = false;
  const fieldList = reqAttr.map((spec, i4) => {
    const value = attrs[spec.name];
    const error2 = checkIfValid(value, spec);
    function addAutocomplete(newValue) {
      const ac = spec.autocomplete;
      if (!ac || ac.length <= newValue.length || ac[newValue.length] === "?")
        return newValue;
      if (!value || newValue.length < value.length) {
        return newValue.slice(0, -1);
      }
      return newValue + ac[newValue.length];
    }
    hasErrors = hasErrors || error2 !== void 0;
    return /* @__PURE__ */ h(
      AttributeEntryField,
      {
        key: i4,
        isFirst: i4 == 0,
        setValue: (v4) => setAttrs({ ...attrs, [spec.name]: addAutocomplete(v4) }),
        spec,
        errorMessage: error2,
        onConfirm: () => {
          if (!hasErrors) {
            setAskUserIfSure(true);
          }
        },
        value
      }
    );
  });
  const doConfirm = async () => {
    await reducer.transition("enter_user_attributes", {
      identity_attributes: {
        application_id: "anastasis-standalone",
        ...attrs
      }
    });
  };
  function saveAsPDF() {
    const printWindow = window.open("", "", "height=400,width=800");
    const divContents = document.getElementById("printThis");
    if (!printWindow || !divContents)
      return;
    printWindow.document.write(
      `<html><head><link rel="stylesheet" href="index.css" /><title>Anastasis Recovery Document</title><style>`
    );
    printWindow.document.write("</style></head><body>&nbsp;</body></html>");
    printWindow.document.close();
    printWindow.document.body.appendChild(divContents.cloneNode(true));
    printWindow.addEventListener("load", () => {
      printWindow.print();
      printWindow.close();
    });
  }
  return /* @__PURE__ */ h(
    AnastasisClientFrame,
    {
      title: withProcessLabel(reducer, "Who are you?"),
      hideNext: hasErrors ? "Complete the form." : void 0,
      onNext: async () => isBackup2 ? setAskUserIfSure(true) : doConfirm()
    },
    askUserIfSure ? /* @__PURE__ */ h(
      ConfirmModal,
      {
        active: true,
        onCancel: () => setAskUserIfSure(false),
        description: "The values in the form must be correct",
        label: "I am sure",
        cancelLabel: "Wait, I want to check",
        onConfirm: () => doConfirm().then(() => setAskUserIfSure(false))
      },
      "You personal information is used to define the location where your secret will be safely stored. If you forget what you have entered or if there is a misspell you will be unable to recover your secret.",
      /* @__PURE__ */ h("p", null, /* @__PURE__ */ h("a", { onClick: saveAsPDF }, "Save the personal information as PDF"))
    ) : void 0,
    /* @__PURE__ */ h("div", { class: "columns", style: { maxWidth: "unset" } }, /* @__PURE__ */ h("div", { class: "column", id: "printThis" }, fieldList), /* @__PURE__ */ h("div", { class: "column" }, /* @__PURE__ */ h("p", null, "This personal information will help to locate your secret."), /* @__PURE__ */ h("h1", { class: "title" }, "This stays private"), /* @__PURE__ */ h("p", null, "The information you have entered here:"), /* @__PURE__ */ h("ul", null, /* @__PURE__ */ h("li", null, /* @__PURE__ */ h("span", { class: "icon is-right" }, /* @__PURE__ */ h("i", { class: "mdi mdi-circle-small" })), "Will be hashed, and therefore unreadable"), /* @__PURE__ */ h("li", null, /* @__PURE__ */ h("span", { class: "icon is-right" }, /* @__PURE__ */ h("i", { class: "mdi mdi-circle-small" })), "The non-hashed version is not shared"))))
  );
}
var possibleBirthdayYear = [];
for (let i4 = 0; i4 < 100; i4++) {
  possibleBirthdayYear.push(2020 - i4);
}
function AttributeEntryField(props) {
  return /* @__PURE__ */ h("div", { style: { marginTop: 16 } }, props.spec.type === "date" && /* @__PURE__ */ h(
    DateInput,
    {
      grabFocus: props.isFirst,
      label: props.spec.label,
      years: possibleBirthdayYear,
      onConfirm: props.onConfirm,
      error: props.errorMessage,
      bind: [props.value, props.setValue]
    }
  ), props.spec.type === "number" && /* @__PURE__ */ h(
    PhoneNumberInput,
    {
      grabFocus: props.isFirst,
      label: props.spec.label,
      onConfirm: props.onConfirm,
      error: props.errorMessage,
      bind: [props.value, props.setValue]
    }
  ), props.spec.type === "string" && /* @__PURE__ */ h(
    TextInput,
    {
      grabFocus: props.isFirst,
      label: props.spec.label,
      onConfirm: props.onConfirm,
      error: props.errorMessage,
      bind: [props.value, props.setValue]
    }
  ), props.spec.type === "string" && /* @__PURE__ */ h("div", null, "This field is case-sensitive. You must enter exactly the same value during recovery."), props.spec.name === "full_name" && /* @__PURE__ */ h("div", null, 'If possible, use "LASTNAME, Firstname(s)" without abbreviations.'), /* @__PURE__ */ h("div", { class: "block" }, "This stays private", /* @__PURE__ */ h("span", { class: "icon is-right" }, /* @__PURE__ */ h("i", { class: "mdi mdi-eye-off" }))));
}
var YEAR_REGEX = /^[0-9]+-[0-9]+-[0-9]+$/;
function checkIfValid(value, spec) {
  const pattern = spec["validation-regex"];
  if (pattern) {
    const re = new RegExp(pattern);
    if (!re.test(value))
      return "The value is invalid";
  }
  const logic = spec["validation-logic"];
  if (logic) {
    const func = validators_exports[logic];
    if (func && typeof func === "function" && !func(value))
      return "Please check the value";
  }
  const optional = spec.optional;
  if (!optional && !value) {
    return "This value is required";
  }
  if ("date" === spec.type) {
    if (!YEAR_REGEX.test(value)) {
      return "The date doesn't follow the format";
    }
    try {
      const v4 = parse(value, "yyyy-MM-dd", /* @__PURE__ */ new Date());
      if (Number.isNaN(v4.getTime())) {
        return "Some numeric values seems out of range for a date";
      }
      if ("birthdate" === spec.name && isAfter(v4, /* @__PURE__ */ new Date())) {
        return "A birthdate cannot be in the future";
      }
    } catch (e4) {
      return "Could not parse the date";
    }
  }
  return void 0;
}

// src/pages/home/AuthenticationEditorScreen.tsx
init_preact_module();

// src/components/InvalidState.tsx
init_preact_module();
function InvalidState() {
  return /* @__PURE__ */ h("div", null, "invalid state");
}

// src/components/NoReducer.tsx
init_preact_module();
function NoReducer() {
  return /* @__PURE__ */ h("div", null, "no reducer");
}

// src/utils/index.tsx
var base2 = {
  continents: [
    {
      name: "Europe"
    },
    {
      name: "India"
    },
    {
      name: "Asia"
    },
    {
      name: "North America"
    },
    {
      name: "Testcontinent"
    }
  ],
  countries: [
    {
      code: "xx",
      name: "Testland",
      continent: "Testcontinent",
      continent_i18n: {
        de_DE: "Testkontinent"
      },
      name_i18n: {
        de_DE: "Testlandt",
        de_CH: "Testlandi",
        fr_FR: "Testpais",
        en_UK: "Testland"
      },
      currency: "TESTKUDOS",
      call_code: "+00"
    },
    {
      code: "xy",
      name: "Demoland",
      continent: "Testcontinent",
      continent_i18n: {
        de_DE: "Testkontinent"
      },
      name_i18n: {
        de_DE: "Demolandt",
        de_CH: "Demolandi",
        fr_FR: "Demopais",
        en_UK: "Demoland"
      },
      currency: "KUDOS",
      call_code: "+01"
    }
  ],
  authentication_providers: {
    "http://localhost:8086/": {
      status: "ok",
      http_status: 200,
      annual_fee: "COL:0",
      business_name: "Anastasis Local",
      currency: "COL",
      liability_limit: "COL:10",
      methods: [
        {
          type: "question",
          usage_fee: "COL:0"
        },
        {
          type: "sms",
          usage_fee: "COL:0"
        },
        {
          type: "email",
          usage_fee: "COL:0"
        }
      ],
      provider_salt: "WBMDD76BR1E90YQ5AHBMKPH7GW",
      storage_limit_in_megabytes: 16,
      truth_upload_fee: "COL:0"
    },
    "https://kudos.demo.anastasis.lu/": {
      status: "ok",
      http_status: 200,
      annual_fee: "COL:0",
      business_name: "Anastasis Kudo",
      currency: "COL",
      liability_limit: "COL:10",
      methods: [
        {
          type: "question",
          usage_fee: "COL:0"
        },
        {
          type: "email",
          usage_fee: "COL:0"
        }
      ],
      provider_salt: "WBMDD76BR1E90YQ5AHBMKPH7GW",
      storage_limit_in_megabytes: 16,
      truth_upload_fee: "COL:0"
    },
    "https://anastasis.demo.taler.net/": {
      status: "ok",
      http_status: 200,
      annual_fee: "COL:0",
      business_name: "Anastasis Demo",
      currency: "COL",
      liability_limit: "COL:10",
      methods: [
        {
          type: "question",
          usage_fee: "COL:0"
        },
        {
          type: "sms",
          usage_fee: "COL:0"
        },
        {
          type: "totp",
          usage_fee: "COL:0"
        }
      ],
      provider_salt: "WBMDD76BR1E90YQ5AHBMKPH7GW",
      storage_limit_in_megabytes: 16,
      truth_upload_fee: "COL:0"
    },
    "http://localhost:8087/": {
      status: "error",
      code: 8414,
      hint: "request to provider failed"
    },
    "http://localhost:8088/": {
      status: "error",
      code: 8414,
      hint: "request to provider failed"
    },
    "http://localhost:8089/": {
      status: "error",
      code: 8414,
      hint: "request to provider failed"
    }
  }
};
var reducerStatesExample = {
  initial: void 0,
  recoverySelectCountry: {
    ...base2,
    reducer_type: "recovery",
    recovery_state: RecoveryStates.CountrySelecting
  },
  recoverySelectContinent: {
    ...base2,
    reducer_type: "recovery",
    recovery_state: RecoveryStates.ContinentSelecting
  },
  secretSelection: {
    ...base2,
    reducer_type: "recovery",
    recovery_state: RecoveryStates.SecretSelecting
  },
  recoveryFinished: {
    ...base2,
    reducer_type: "recovery",
    recovery_state: RecoveryStates.RecoveryFinished
  },
  challengeSelecting: {
    ...base2,
    reducer_type: "recovery",
    recovery_state: RecoveryStates.ChallengeSelecting
  },
  challengeSolving: {
    ...base2,
    reducer_type: "recovery",
    recovery_state: RecoveryStates.ChallengeSolving
  },
  challengePaying: {
    ...base2,
    reducer_type: "recovery",
    recovery_state: RecoveryStates.ChallengePaying
  },
  recoveryAttributeEditing: {
    ...base2,
    reducer_type: "recovery",
    recovery_state: RecoveryStates.UserAttributesCollecting
  },
  backupSelectCountry: {
    ...base2,
    reducer_type: "backup",
    backup_state: BackupStates.CountrySelecting
  },
  backupSelectContinent: {
    ...base2,
    reducer_type: "backup",
    backup_state: BackupStates.ContinentSelecting
  },
  secretEdition: {
    ...base2,
    reducer_type: "backup",
    backup_state: BackupStates.SecretEditing
  },
  policyReview: {
    ...base2,
    reducer_type: "backup",
    backup_state: BackupStates.PoliciesReviewing
  },
  policyPay: {
    ...base2,
    reducer_type: "backup",
    backup_state: BackupStates.PoliciesPaying
  },
  backupFinished: {
    ...base2,
    reducer_type: "backup",
    backup_state: BackupStates.BackupFinished
  },
  authEditing: {
    ...base2,
    backup_state: BackupStates.AuthenticationsEditing,
    reducer_type: "backup"
  },
  backupAttributeEditing: {
    ...base2,
    reducer_type: "backup",
    backup_state: BackupStates.UserAttributesCollecting
  },
  truthsPaying: {
    ...base2,
    reducer_type: "backup",
    backup_state: BackupStates.TruthsPaying
  }
};
function compose(name, hook, vs) {
  const Component = (p5) => {
    const state = hook(p5);
    const s4 = state.status;
    const c4 = vs[s4];
    return c4(state);
  };
  return Component;
}

// src/pages/home/authMethod/index.tsx
init_preact_module();

// src/assets/icons/auth_method/postal.svg
var postal_default = "./postal-UR7NHUFJ.svg";

// src/assets/icons/auth_method/question.svg
var question_default = "./question-GOH5WTSN.svg";

// src/assets/icons/auth_method/sms.svg
var sms_default = "./sms-AIXPMDQL.svg";

// src/pages/home/authMethod/AuthMethodEmailSetup.tsx
init_preact_module();

// src/components/fields/EmailInput.tsx
init_preact_module();
function EmailInput(props) {
  const inputRef = _2(null);
  s2(() => {
    if (props.grabFocus) {
      inputRef.current?.focus();
    }
  }, [props.grabFocus]);
  const value = props.bind[0];
  const [dirty, setDirty] = p3(false);
  const showError = dirty && props.error;
  return /* @__PURE__ */ h("div", { class: "field" }, /* @__PURE__ */ h("label", { class: "label" }, props.label, props.tooltip && /* @__PURE__ */ h("span", { class: "icon has-tooltip-right", "data-tooltip": props.tooltip }, /* @__PURE__ */ h("i", { class: "mdi mdi-information" }))), /* @__PURE__ */ h("div", { class: "control has-icons-right" }, /* @__PURE__ */ h(
    "input",
    {
      value,
      required: true,
      placeholder: props.placeholder,
      type: "email",
      class: showError ? "input is-danger" : "input",
      onKeyPress: (e4) => {
        if (e4.key === "Enter" && props.onConfirm) {
          props.onConfirm();
        }
      },
      onInput: (e4) => {
        setDirty(true);
        props.bind[1](e4.target.value);
      },
      ref: inputRef,
      style: { display: "block" }
    }
  )), showError && /* @__PURE__ */ h("p", { class: "help is-danger" }, props.error));
}

// src/pages/home/authMethod/AuthMethodEmailSetup.tsx
var EMAIL_PATTERN = /^(([^<>()[\]\\.,;:\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,}))$/;
function AuthMethodEmailSetup({
  cancel,
  addAuthMethod,
  configured
}) {
  const [email, setEmail] = p3("");
  const addEmailAuth = () => addAuthMethod({
    authentication_method: {
      type: "email",
      instructions: `Email to ${email}`,
      challenge: encodeCrock(stringToBytes(email))
    }
  });
  const emailError = !EMAIL_PATTERN.test(email) ? "Email address is not valid" : void 0;
  const errors2 = !email ? "Add your email" : emailError;
  function goNextIfNoErrors() {
    if (!errors2)
      addEmailAuth();
  }
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Add email authentication" }, /* @__PURE__ */ h("p", null, "For email authentication, you need to provide an email address. When recovering your secret, you will need to enter the code you receive by email. Add the uuid from the challenge"), /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
    EmailInput,
    {
      label: "Email address",
      error: emailError,
      onConfirm: goNextIfNoErrors,
      placeholder: "email@domain.com",
      bind: [email, setEmail]
    }
  )), configured.length > 0 && /* @__PURE__ */ h("section", { class: "section" }, /* @__PURE__ */ h("div", { class: "block" }, "Your emails:"), /* @__PURE__ */ h("div", { class: "block" }, configured.map((c4, i4) => {
    return /* @__PURE__ */ h(
      "div",
      {
        key: i4,
        class: "box",
        style: { display: "flex", justifyContent: "space-between" }
      },
      /* @__PURE__ */ h("p", { style: { marginBottom: "auto", marginTop: "auto" } }, c4.instructions),
      /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("button", { class: "button is-danger", onClick: c4.remove }, "Delete"))
    );
  }))), /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: cancel }, "Cancel"),
    /* @__PURE__ */ h("span", { "data-tooltip": errors2 }, /* @__PURE__ */ h(
      "button",
      {
        class: "button is-info",
        disabled: errors2 !== void 0,
        onClick: addEmailAuth
      },
      "Add"
    ))
  )));
}

// src/pages/home/authMethod/AuthMethodEmailSolve.tsx
init_preact_module();

// src/pages/home/SolveScreen.tsx
init_preact_module();
function SolveOverviewFeedbackDisplay(props) {
  const { feedback } = props;
  if (!feedback) {
    return /* @__PURE__ */ h("div", null);
  }
  switch (feedback.state) {
    case ChallengeFeedbackStatus.TalerPayment:
      return /* @__PURE__ */ h(
        Notifications,
        {
          notifications: [
            {
              type: "INFO",
              message: `Message from provider`,
              description: /* @__PURE__ */ h("span", null, "To pay you can", " ", /* @__PURE__ */ h(
                "a",
                {
                  href: feedback.taler_pay_uri,
                  target: "_blank",
                  rel: "noreferrer"
                },
                "click here"
              ))
            }
          ]
        }
      );
    case ChallengeFeedbackStatus.IbanInstructions:
      return /* @__PURE__ */ h(
        Notifications,
        {
          notifications: [
            {
              type: "INFO",
              message: `Message from provider`,
              description: `Need to send a wire transfer to "${feedback.target_business_name}"`
            }
          ]
        }
      );
    case ChallengeFeedbackStatus.ServerFailure:
      return /* @__PURE__ */ h(
        Notifications,
        {
          notifications: [
            {
              type: "ERROR",
              message: `Server error: response code ${feedback.http_status}`,
              description: !feedback.error_response ? void 0 : `More information: ${JSON.stringify(
                feedback.error_response
              )}`
            }
          ]
        }
      );
    case ChallengeFeedbackStatus.RateLimitExceeded:
      return /* @__PURE__ */ h(
        Notifications,
        {
          notifications: [
            {
              type: "ERROR",
              message: "There were to many failed attempts."
            }
          ]
        }
      );
    case ChallengeFeedbackStatus.Unsupported:
      return /* @__PURE__ */ h(
        Notifications,
        {
          notifications: [
            {
              type: "ERROR",
              message: `This client doesn't support solving this type of challenge`,
              description: `Use another version or contact the provider. Type of challenge "${feedback.unsupported_method}"`
            }
          ]
        }
      );
    case ChallengeFeedbackStatus.TruthUnknown:
      return /* @__PURE__ */ h(
        Notifications,
        {
          notifications: [
            {
              type: "ERROR",
              message: `Provider doesn't recognize the type of challenge`,
              description: "Contact the provider for further information"
            }
          ]
        }
      );
    case ChallengeFeedbackStatus.CodeInFile:
      return /* @__PURE__ */ h(
        Notifications,
        {
          notifications: [
            {
              type: "INFO",
              message: `Required TAN can be found in file "${feedback.filename}"`,
              description: feedback.display_hint ? `HINT: ${feedback.display_hint}` : void 0
            }
          ]
        }
      );
    case ChallengeFeedbackStatus.CodeSent:
      return /* @__PURE__ */ h(
        Notifications,
        {
          notifications: [
            {
              type: "INFO",
              message: `Code sent to address "${feedback.address_hint}"`,
              description: feedback.display_hint ? `HINT: ${feedback.display_hint}` : void 0
            }
          ]
        }
      );
    case ChallengeFeedbackStatus.IncorrectAnswer:
      return /* @__PURE__ */ h(
        Notifications,
        {
          notifications: [
            {
              type: "ERROR",
              message: `The answer is wrong.`
            }
          ]
        }
      );
    case ChallengeFeedbackStatus.Solved:
      return /* @__PURE__ */ h(
        Notifications,
        {
          notifications: [
            {
              type: "SUCCESS",
              message: `This challenge is solved`
            }
          ]
        }
      );
  }
}
function SolveScreen() {
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "no reducer in context"));
  }
  if (reducer.currentReducerState?.reducer_type !== "recovery") {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state"));
  }
  if (!reducer.currentReducerState.recovery_information) {
    return /* @__PURE__ */ h(
      AnastasisClientFrame,
      {
        hideNext: "Recovery document not found",
        title: "Recovery problem"
      },
      /* @__PURE__ */ h("div", null, "no recovery information found")
    );
  }
  if (!reducer.currentReducerState.selected_challenge_uuid) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state"), /* @__PURE__ */ h(
      "div",
      {
        style: {
          marginTop: "2em",
          display: "flex",
          justifyContent: "space-between"
        }
      },
      /* @__PURE__ */ h("button", { class: "button", onClick: () => reducer.back() }, "Back")
    ));
  }
  function SolveNotImplemented() {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Not implemented" }, /* @__PURE__ */ h("p", null, "The challenge selected is not supported for this UI. Please update this version or try using another policy."), reducer && /* @__PURE__ */ h(
      "div",
      {
        style: {
          marginTop: "2em",
          display: "flex",
          justifyContent: "space-between"
        }
      },
      /* @__PURE__ */ h("button", { class: "button", onClick: () => reducer.back() }, "Back")
    ));
  }
  const chArr = reducer.currentReducerState.recovery_information.challenges;
  const selectedUuid = reducer.currentReducerState.selected_challenge_uuid;
  const selectedChallenge = chArr.find((ch) => ch.uuid === selectedUuid);
  const SolveDialog = !selectedChallenge || !authMethods[selectedChallenge.type] ? SolveNotImplemented : authMethods[selectedChallenge.type].solve ?? SolveNotImplemented;
  return /* @__PURE__ */ h(SolveDialog, { id: selectedUuid });
}

// src/pages/home/authMethod/helpers.ts
function shouldHideConfirm(feedback) {
  return feedback?.state === ChallengeFeedbackStatus.RateLimitExceeded || feedback?.state === ChallengeFeedbackStatus.Unsupported || feedback?.state === ChallengeFeedbackStatus.TruthUnknown;
}

// src/pages/home/authMethod/AuthMethodEmailSolve.tsx
function AuthMethodEmailSolve({ id }) {
  const [answer, _setAnswer] = p3("A-");
  function setAnswer(str) {
    const unformatted = str.replace(/^A-/, "").replace(/-/g, "").toLocaleUpperCase();
    let result = `A-${unformatted.substring(0, 5)}`;
    if (unformatted.length > 5) {
      result += `-${unformatted.substring(5, 8)}`;
    }
    if (unformatted.length > 8) {
      result += `-${unformatted.substring(8, 12)}`;
    }
    if (unformatted.length > 12) {
      result += `-${unformatted.substring(12)}`;
    }
    _setAnswer(result);
  }
  const [expanded, setExpanded] = p3(false);
  const { i18n: i18n2 } = useTranslationContext();
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "no reducer in context"));
  }
  if (reducer.currentReducerState?.reducer_type !== "recovery") {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state, no recovery state"));
  }
  if (!reducer.currentReducerState.recovery_information) {
    return /* @__PURE__ */ h(
      AnastasisClientFrame,
      {
        hideNext: "Recovery document not found",
        title: "Recovery problem"
      },
      /* @__PURE__ */ h("div", null, "no recovery information found")
    );
  }
  if (!reducer.currentReducerState.selected_challenge_uuid) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state, no challenge id"), /* @__PURE__ */ h(
      "div",
      {
        style: {
          marginTop: "2em",
          display: "flex",
          justifyContent: "space-between"
        }
      },
      /* @__PURE__ */ h("button", { class: "button", onClick: () => reducer.back() }, "Back")
    ));
  }
  const chArr = reducer.currentReducerState.recovery_information.challenges;
  const challengeFeedback = reducer.currentReducerState.challenge_feedback ?? {};
  const selectedUuid = reducer.currentReducerState.selected_challenge_uuid;
  const challenges = {};
  for (const ch of chArr) {
    challenges[ch.uuid] = ch;
  }
  const selectedChallenge = challenges[selectedUuid];
  const feedback = challengeFeedback[selectedUuid];
  async function onNext() {
    return reducer?.transition("solve_challenge", {
      answer: `A-${answer.replace(/^A-/, "").replace(/-/g, "").trim()}`
    });
  }
  function onCancel() {
    reducer?.back();
  }
  const error2 = answer.length > 21 ? i18n2.str`The answer should not be greater than 21 characters.` : void 0;
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Email challenge" }, /* @__PURE__ */ h(SolveOverviewFeedbackDisplay, { feedback }), /* @__PURE__ */ h("p", null, 'An email has been sent to "', /* @__PURE__ */ h("b", null, selectedChallenge.instructions), '". The message has and identification code and recovery code that starts with "', /* @__PURE__ */ h("b", null, "A-"), '". Wait the message to arrive and the enter the recovery code below.'), !expanded ? /* @__PURE__ */ h("p", null, 'The identification code in the email should start with "', selectedUuid.substring(0, 10), '"', /* @__PURE__ */ h(
    "span",
    {
      class: "icon has-tooltip-top",
      "data-tooltip": "click to expand",
      onClick: () => setExpanded((e4) => !e4)
    },
    /* @__PURE__ */ h("i", { class: "mdi mdi-information" })
  )) : /* @__PURE__ */ h("p", null, 'The identification code in the email is "', selectedUuid, '"', /* @__PURE__ */ h(
    "span",
    {
      class: "icon has-tooltip-top",
      "data-tooltip": "click to show less code",
      onClick: () => setExpanded((e4) => !e4)
    },
    /* @__PURE__ */ h("i", { class: "mdi mdi-information" })
  )), /* @__PURE__ */ h(
    TextInput,
    {
      label: "Answer",
      grabFocus: true,
      onConfirm: onNext,
      bind: [answer, setAnswer],
      error: error2,
      placeholder: "A-12345-678-1234-5678"
    }
  ), /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: onCancel }, "Cancel"),
    !shouldHideConfirm(feedback) && /* @__PURE__ */ h(
      AsyncButton,
      {
        class: "button is-info",
        onClick: onNext,
        disabled: !!error2
      },
      "Confirm"
    )
  ));
}

// src/pages/home/authMethod/AuthMethodIbanSetup.tsx
init_preact_module();
function AuthMethodIbanSetup({
  addAuthMethod,
  cancel,
  configured
}) {
  const [name, setName] = p3("");
  const [account, setAccount] = p3("");
  const addIbanAuth = () => addAuthMethod({
    authentication_method: {
      type: "iban",
      instructions: `Wire transfer from ${account} with holder ${name}`,
      challenge: encodeCrock(
        stringToBytes(
          canonicalJson({
            name,
            account
          })
        )
      )
    }
  });
  const errors2 = !name ? "Add an account name" : !account ? "Add an account IBAN number" : void 0;
  function goNextIfNoErrors() {
    if (!errors2)
      addIbanAuth();
  }
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Add bank transfer authentication" }, /* @__PURE__ */ h("p", null, "For bank transfer authentication, you need to provide a bank account (account holder name and IBAN). When recovering your secret, you will be asked to pay the recovery fee via bank transfer from the account you provided here."), /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
    TextInput,
    {
      label: "Bank account holder name",
      grabFocus: true,
      placeholder: "John Smith",
      onConfirm: goNextIfNoErrors,
      bind: [name, setName]
    }
  ), /* @__PURE__ */ h(
    TextInput,
    {
      label: "IBAN",
      placeholder: "DE91100000000123456789",
      onConfirm: goNextIfNoErrors,
      bind: [account, setAccount]
    }
  )), configured.length > 0 && /* @__PURE__ */ h("section", { class: "section" }, /* @__PURE__ */ h("div", { class: "block" }, "Your bank accounts:"), /* @__PURE__ */ h("div", { class: "block" }, configured.map((c4, i4) => {
    return /* @__PURE__ */ h(
      "div",
      {
        key: i4,
        class: "box",
        style: { display: "flex", justifyContent: "space-between" }
      },
      /* @__PURE__ */ h("p", { style: { marginBottom: "auto", marginTop: "auto" } }, c4.instructions),
      /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("button", { class: "button is-danger", onClick: c4.remove }, "Delete"))
    );
  }))), /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: cancel }, "Cancel"),
    /* @__PURE__ */ h("span", { "data-tooltip": errors2 }, /* @__PURE__ */ h(
      "button",
      {
        class: "button is-info",
        disabled: errors2 !== void 0,
        onClick: addIbanAuth
      },
      "Add"
    ))
  )));
}

// src/pages/home/authMethod/AuthMethodIbanSolve.tsx
init_preact_module();
function AuthMethodIbanSolve({ id }) {
  const [answer, setAnswer] = p3("");
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "no reducer in context"));
  }
  if (reducer.currentReducerState?.reducer_type !== "recovery") {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state"));
  }
  if (!reducer.currentReducerState.recovery_information) {
    return /* @__PURE__ */ h(
      AnastasisClientFrame,
      {
        hideNext: "Recovery document not found",
        title: "Recovery problem"
      },
      /* @__PURE__ */ h("div", null, "no recovery information found")
    );
  }
  if (!reducer.currentReducerState.selected_challenge_uuid) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state"), /* @__PURE__ */ h(
      "div",
      {
        style: {
          marginTop: "2em",
          display: "flex",
          justifyContent: "space-between"
        }
      },
      /* @__PURE__ */ h("button", { class: "button", onClick: () => reducer.back() }, "Back")
    ));
  }
  const chArr = reducer.currentReducerState.recovery_information.challenges;
  const challengeFeedback = reducer.currentReducerState.challenge_feedback ?? {};
  const selectedUuid = reducer.currentReducerState.selected_challenge_uuid;
  const challenges = {};
  for (const ch of chArr) {
    challenges[ch.uuid] = ch;
  }
  const selectedChallenge = challenges[selectedUuid];
  const feedback = challengeFeedback[selectedUuid];
  async function onNext() {
    return reducer?.transition("solve_challenge", { answer });
  }
  function onCancel() {
    reducer?.back();
  }
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "IBAN Challenge" }, /* @__PURE__ */ h(SolveOverviewFeedbackDisplay, { feedback }), /* @__PURE__ */ h("p", null, "Send a wire transfer to the address,"), /* @__PURE__ */ h("button", { class: "button" }, "Check"), /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: onCancel }, "Cancel"),
    !shouldHideConfirm(feedback) && /* @__PURE__ */ h(AsyncButton, { class: "button is-info", onClick: onNext }, "Confirm")
  ));
}

// src/pages/home/authMethod/AuthMethodPostSetup.tsx
init_preact_module();
function AuthMethodPostSetup({
  addAuthMethod,
  cancel,
  configured
}) {
  const [fullName, setFullName] = p3("");
  const [street, setStreet] = p3("");
  const [city, setCity] = p3("");
  const [postcode, setPostcode] = p3("");
  const [country, setCountry] = p3("");
  const addPostAuth = () => {
    const challengeJson = {
      full_name: fullName,
      street,
      city,
      postcode,
      country
    };
    addAuthMethod({
      authentication_method: {
        type: "post",
        instructions: `Letter to address in postal code ${postcode}`,
        challenge: encodeCrock(stringToBytes(canonicalJson(challengeJson)))
      }
    });
  };
  const errors2 = !fullName ? "The full name is missing" : !street ? "The street is missing" : !city ? "The city is missing" : !postcode ? "The postcode is missing" : !country ? "The country is missing" : void 0;
  function goNextIfNoErrors() {
    if (!errors2)
      addPostAuth();
  }
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Add postal authentication" }, /* @__PURE__ */ h("p", null, "For postal letter authentication, you need to provide a postal address. When recovering your secret, you will be asked to enter a code that you will receive in a letter to that address."), /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
    TextInput,
    {
      grabFocus: true,
      label: "Full Name",
      bind: [fullName, setFullName],
      onConfirm: goNextIfNoErrors
    }
  )), /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
    TextInput,
    {
      onConfirm: goNextIfNoErrors,
      label: "Street",
      bind: [street, setStreet]
    }
  )), /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
    TextInput,
    {
      onConfirm: goNextIfNoErrors,
      label: "City",
      bind: [city, setCity]
    }
  )), /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
    TextInput,
    {
      onConfirm: goNextIfNoErrors,
      label: "Postal Code",
      bind: [postcode, setPostcode]
    }
  )), /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
    TextInput,
    {
      onConfirm: goNextIfNoErrors,
      label: "Country",
      bind: [country, setCountry]
    }
  )), configured.length > 0 && /* @__PURE__ */ h("section", { class: "section" }, /* @__PURE__ */ h("div", { class: "block" }, "Your postal code:"), /* @__PURE__ */ h("div", { class: "block" }, configured.map((c4, i4) => {
    return /* @__PURE__ */ h(
      "div",
      {
        key: i4,
        class: "box",
        style: { display: "flex", justifyContent: "space-between" }
      },
      /* @__PURE__ */ h("p", { style: { marginBottom: "auto", marginTop: "auto" } }, c4.instructions),
      /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("button", { class: "button is-danger", onClick: c4.remove }, "Delete"))
    );
  }))), /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: cancel }, "Cancel"),
    /* @__PURE__ */ h("span", { "data-tooltip": errors2 }, /* @__PURE__ */ h(
      "button",
      {
        class: "button is-info",
        disabled: errors2 !== void 0,
        onClick: addPostAuth
      },
      "Add"
    ))
  ));
}

// src/pages/home/authMethod/AuthMethodPostSolve.tsx
init_preact_module();
function AuthMethodPostSolve({ id }) {
  const [answer, _setAnswer] = p3("A-");
  function setAnswer(str) {
    const unformatted = str.replace(/^A-/, "").replace(/-/g, "").toLocaleUpperCase();
    let result = `A-${unformatted.substring(0, 5)}`;
    if (unformatted.length > 5) {
      result += `-${unformatted.substring(5, 8)}`;
    }
    if (unformatted.length > 8) {
      result += `-${unformatted.substring(8, 12)}`;
    }
    if (unformatted.length > 12) {
      result += `-${unformatted.substring(12)}`;
    }
    _setAnswer(result);
  }
  const { i18n: i18n2 } = useTranslationContext();
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "no reducer in context"));
  }
  if (reducer.currentReducerState?.reducer_type !== "recovery") {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state"));
  }
  if (!reducer.currentReducerState.recovery_information) {
    return /* @__PURE__ */ h(
      AnastasisClientFrame,
      {
        hideNext: "Recovery document not found",
        title: "Recovery problem"
      },
      /* @__PURE__ */ h("div", null, "no recovery information found")
    );
  }
  if (!reducer.currentReducerState.selected_challenge_uuid) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state"), /* @__PURE__ */ h(
      "div",
      {
        style: {
          marginTop: "2em",
          display: "flex",
          justifyContent: "space-between"
        }
      },
      /* @__PURE__ */ h("button", { class: "button", onClick: () => reducer.back() }, "Back")
    ));
  }
  const chArr = reducer.currentReducerState.recovery_information.challenges;
  const challengeFeedback = reducer.currentReducerState.challenge_feedback ?? {};
  const selectedUuid = reducer.currentReducerState.selected_challenge_uuid;
  const challenges = {};
  for (const ch of chArr) {
    challenges[ch.uuid] = ch;
  }
  const selectedChallenge = challenges[selectedUuid];
  const feedback = challengeFeedback[selectedUuid];
  async function onNext() {
    return reducer?.transition("solve_challenge", {
      answer: `A-${answer.replace(/^A-/, "").replace(/-/g, "").trim()}`
    });
  }
  function onCancel() {
    reducer?.back();
  }
  const error2 = answer.length > 21 ? i18n2.str`The answer should not be greater than 21 characters.` : void 0;
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Postal Challenge" }, /* @__PURE__ */ h(SolveOverviewFeedbackDisplay, { feedback }), /* @__PURE__ */ h("p", null, "Wait for the answer"), /* @__PURE__ */ h(
    TextInput,
    {
      onConfirm: onNext,
      label: "Answer",
      grabFocus: true,
      placeholder: "A-12345-678-1234-5678",
      error: error2,
      bind: [answer, setAnswer]
    }
  ), /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: onCancel }, "Cancel"),
    !shouldHideConfirm(feedback) && /* @__PURE__ */ h(
      AsyncButton,
      {
        class: "button is-info",
        onClick: onNext,
        disabled: !!error2
      },
      "Confirm"
    )
  ));
}

// src/pages/home/authMethod/AuthMethodQuestionSetup.tsx
init_preact_module();
function AuthMethodQuestionSetup({
  cancel,
  addAuthMethod,
  configured
}) {
  const [questionText, setQuestionText] = p3("");
  const [answerText, setAnswerText] = p3("");
  const addQuestionAuth = () => addAuthMethod({
    authentication_method: {
      type: "question",
      instructions: questionText,
      challenge: encodeCrock(stringToBytes(answerText))
    }
  });
  const errors2 = !questionText ? "Add your security question" : !answerText ? "Add the answer to your question" : void 0;
  function goNextIfNoErrors() {
    if (!errors2)
      addQuestionAuth();
  }
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Add Security Question" }, /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("p", null, "For security question authentication, you need to provide a question and its answer. When recovering your secret, you will be shown the question and you will need to type the answer exactly as you typed it here."), /* @__PURE__ */ h("p", { class: "notification is-warning" }, "Note that the answer is case-sensitive and must be entered in exactly the same way (punctuation, spaces) during recovery."), /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
    TextInput,
    {
      label: "Security question",
      grabFocus: true,
      onConfirm: goNextIfNoErrors,
      placeholder: "Your question",
      bind: [questionText, setQuestionText]
    }
  )), /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
    TextInput,
    {
      label: "Answer",
      onConfirm: goNextIfNoErrors,
      placeholder: "Your answer",
      bind: [answerText, setAnswerText]
    }
  )), /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: cancel }, "Cancel"),
    /* @__PURE__ */ h("span", { "data-tooltip": errors2 }, /* @__PURE__ */ h(
      "button",
      {
        class: "button is-info",
        disabled: errors2 !== void 0,
        onClick: addQuestionAuth
      },
      "Add"
    ))
  ), configured.length > 0 && /* @__PURE__ */ h("section", { class: "section" }, /* @__PURE__ */ h("div", { class: "block" }, "Your security questions:"), /* @__PURE__ */ h("div", { class: "block" }, configured.map((c4, i4) => {
    return /* @__PURE__ */ h(
      "div",
      {
        key: i4,
        class: "box",
        style: { display: "flex", justifyContent: "space-between" }
      },
      /* @__PURE__ */ h("p", { style: { marginBottom: "auto", marginTop: "auto" } }, c4.instructions),
      /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("button", { class: "button is-danger", onClick: c4.remove }, "Delete"))
    );
  })))));
}

// src/pages/home/authMethod/AuthMethodQuestionSolve.tsx
init_preact_module();
function AuthMethodQuestionSolve({ id }) {
  const [answer, setAnswer] = p3("");
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "no reducer in context"));
  }
  if (reducer.currentReducerState?.reducer_type !== "recovery") {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state"));
  }
  if (!reducer.currentReducerState.recovery_information) {
    return /* @__PURE__ */ h(
      AnastasisClientFrame,
      {
        hideNext: "Recovery document not found",
        title: "Recovery problem"
      },
      /* @__PURE__ */ h("div", null, "no recovery information found")
    );
  }
  if (!reducer.currentReducerState.selected_challenge_uuid) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state"), /* @__PURE__ */ h(
      "div",
      {
        style: {
          marginTop: "2em",
          display: "flex",
          justifyContent: "space-between"
        }
      },
      /* @__PURE__ */ h("button", { class: "button", onClick: () => reducer.back() }, "Back")
    ));
  }
  const chArr = reducer.currentReducerState.recovery_information.challenges;
  const challengeFeedback = reducer.currentReducerState.challenge_feedback ?? {};
  const selectedUuid = reducer.currentReducerState.selected_challenge_uuid;
  const challenges = {};
  for (const ch of chArr) {
    challenges[ch.uuid] = ch;
  }
  const selectedChallenge = challenges[selectedUuid];
  const feedback = challengeFeedback[selectedUuid];
  async function onNext() {
    return reducer?.transition("solve_challenge", { answer });
  }
  function onCancel() {
    reducer?.back();
  }
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Question challenge" }, /* @__PURE__ */ h(SolveOverviewFeedbackDisplay, { feedback }), /* @__PURE__ */ h("p", null, "In this challenge you need to provide the answer for the next question:"), /* @__PURE__ */ h("pre", null, selectedChallenge.instructions), /* @__PURE__ */ h("p", null, "Type the answer below"), /* @__PURE__ */ h(
    TextInput,
    {
      label: "Answer",
      onConfirm: onNext,
      grabFocus: true,
      bind: [answer, setAnswer]
    }
  ), /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: onCancel }, "Cancel"),
    !shouldHideConfirm(feedback) && /* @__PURE__ */ h(AsyncButton, { class: "button is-info", onClick: onNext }, "Confirm")
  ));
}

// src/pages/home/authMethod/AuthMethodSmsSetup.tsx
init_preact_module();
var REGEX_JUST_NUMBERS = /^\+[0-9 ]*$/;
function isJustNumbers(str) {
  return REGEX_JUST_NUMBERS.test(str);
}
function AuthMethodSmsSetup({
  addAuthMethod,
  cancel,
  configured
}) {
  const [mobileNumber, setMobileNumber] = p3("+");
  const addSmsAuth = () => {
    addAuthMethod({
      authentication_method: {
        type: "sms",
        instructions: `SMS to ${mobileNumber}`,
        challenge: encodeCrock(stringToBytes(mobileNumber))
      }
    });
  };
  const inputRef = _2(null);
  s2(() => {
    inputRef.current?.focus();
  }, []);
  const errors2 = !mobileNumber ? "Add a mobile number" : !mobileNumber.startsWith("+") ? "Mobile number should start with '+'" : !isJustNumbers(mobileNumber) ? "Mobile number can't have other than numbers" : void 0;
  function goNextIfNoErrors() {
    if (!errors2)
      addSmsAuth();
  }
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Add SMS authentication" }, /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("p", null, "For SMS authentication, you need to provide a mobile number. When recovering your secret, you will be asked to enter the code you receive via SMS."), /* @__PURE__ */ h("div", { class: "container" }, /* @__PURE__ */ h(
    PhoneNumberInput,
    {
      label: "Mobile number",
      placeholder: "Your mobile number",
      onConfirm: goNextIfNoErrors,
      error: errors2,
      grabFocus: true,
      bind: [mobileNumber, setMobileNumber]
    }
  ), /* @__PURE__ */ h("div", null, "Enter mobile number including +CC international dialing prefix.")), configured.length > 0 && /* @__PURE__ */ h("section", { class: "section" }, /* @__PURE__ */ h("div", { class: "block" }, "Your mobile numbers:"), /* @__PURE__ */ h("div", { class: "block" }, configured.map((c4, i4) => {
    return /* @__PURE__ */ h(
      "div",
      {
        key: i4,
        class: "box",
        style: { display: "flex", justifyContent: "space-between" }
      },
      /* @__PURE__ */ h("p", { style: { marginTop: "auto", marginBottom: "auto" } }, c4.instructions),
      /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("button", { class: "button is-danger", onClick: c4.remove }, "Delete"))
    );
  }))), /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: cancel }, "Cancel"),
    /* @__PURE__ */ h("span", { "data-tooltip": errors2 }, /* @__PURE__ */ h(
      "button",
      {
        class: "button is-info",
        disabled: errors2 !== void 0,
        onClick: addSmsAuth
      },
      "Add"
    ))
  )));
}

// src/pages/home/authMethod/AuthMethodSmsSolve.tsx
init_preact_module();
function AuthMethodSmsSolve({ id }) {
  const [answer, _setAnswer] = p3("A-");
  function setAnswer(str) {
    const unformatted = str.replace(/^A-/, "").replace(/-/g, "").toLocaleUpperCase();
    let result = `A-${unformatted.substring(0, 5)}`;
    if (unformatted.length > 5) {
      result += `-${unformatted.substring(5, 8)}`;
    }
    if (unformatted.length > 8) {
      result += `-${unformatted.substring(8, 12)}`;
    }
    if (unformatted.length > 12) {
      result += `-${unformatted.substring(12)}`;
    }
    _setAnswer(result);
  }
  const { i18n: i18n2 } = useTranslationContext();
  const [expanded, setExpanded] = p3(false);
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "no reducer in context"));
  }
  if (reducer.currentReducerState?.reducer_type !== "recovery") {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state"));
  }
  if (!reducer.currentReducerState.recovery_information) {
    return /* @__PURE__ */ h(
      AnastasisClientFrame,
      {
        hideNext: "Recovery document not found",
        title: "Recovery problem"
      },
      /* @__PURE__ */ h("div", null, "no recovery information found")
    );
  }
  if (!reducer.currentReducerState.selected_challenge_uuid) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state"), /* @__PURE__ */ h(
      "div",
      {
        style: {
          marginTop: "2em",
          display: "flex",
          justifyContent: "space-between"
        }
      },
      /* @__PURE__ */ h("button", { class: "button", onClick: () => reducer.back() }, "Back")
    ));
  }
  const chArr = reducer.currentReducerState.recovery_information.challenges;
  const challengeFeedback = reducer.currentReducerState.challenge_feedback ?? {};
  const selectedUuid = reducer.currentReducerState.selected_challenge_uuid;
  const challenges = {};
  for (const ch of chArr) {
    challenges[ch.uuid] = ch;
  }
  const selectedChallenge = challenges[selectedUuid];
  const feedback = challengeFeedback[selectedUuid];
  async function onNext() {
    return reducer?.transition("solve_challenge", {
      answer: `A-${answer.replace(/^A-/, "").replace(/-/g, "").trim()}`
    });
  }
  function onCancel() {
    reducer?.back();
  }
  const error2 = answer.length > 21 ? i18n2.str`The answer should not be greater than 21 characters.` : void 0;
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "SMS Challenge" }, /* @__PURE__ */ h(SolveOverviewFeedbackDisplay, { feedback }), /* @__PURE__ */ h("p", null, 'An sms has been sent to "', /* @__PURE__ */ h("b", null, selectedChallenge.instructions), '". The message has and identification code and recovery code that starts with "', /* @__PURE__ */ h("b", null, "A-"), '". Wait the message to arrive and the enter the recovery code below.'), !expanded ? /* @__PURE__ */ h("p", null, 'The identification code in the SMS should start with "', selectedUuid.substring(0, 10), '"', /* @__PURE__ */ h(
    "span",
    {
      class: "icon has-tooltip-top",
      "data-tooltip": "click to expand",
      onClick: () => setExpanded((e4) => !e4)
    },
    /* @__PURE__ */ h("i", { class: "mdi mdi-information" })
  )) : /* @__PURE__ */ h("p", null, 'The identification code in the SMS is "', selectedUuid, '"', /* @__PURE__ */ h(
    "span",
    {
      class: "icon has-tooltip-top",
      "data-tooltip": "click to show less code",
      onClick: () => setExpanded((e4) => !e4)
    },
    /* @__PURE__ */ h("i", { class: "mdi mdi-information" })
  )), /* @__PURE__ */ h(
    TextInput,
    {
      label: "Answer",
      grabFocus: true,
      onConfirm: onNext,
      bind: [answer, setAnswer],
      error: error2,
      placeholder: "A-12345-678-1234-5678"
    }
  ), /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: onCancel }, "Cancel"),
    !shouldHideConfirm(feedback) && /* @__PURE__ */ h(
      AsyncButton,
      {
        class: "button is-info",
        onClick: onNext,
        disabled: !!error2
      },
      "Confirm"
    )
  ));
}

// src/pages/home/authMethod/AuthMethodTotpSetup.tsx
init_preact_module();

// src/components/QR.tsx
init_preact_module();
var import_qrcode_generator = __toESM(require_qrcode(), 1);
function QR({ text }) {
  const divRef = _2(null);
  h2(() => {
    const qr = (0, import_qrcode_generator.default)(0, "L");
    qr.addData(text);
    qr.make();
    if (divRef.current)
      divRef.current.innerHTML = qr.createSvgTag({
        scalable: true
      });
  });
  return /* @__PURE__ */ h(
    "div",
    {
      style: {
        width: "100%",
        display: "flex",
        flexDirection: "column",
        alignItems: "center"
      }
    },
    /* @__PURE__ */ h(
      "div",
      {
        style: { width: "50%", minWidth: 200, maxWidth: 300 },
        ref: divRef
      }
    )
  );
}

// ../../node_modules/.pnpm/jssha@3.3.0/node_modules/jssha/dist/sha.mjs
var t3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function n2(t4, n3, e4, r4) {
  let i4, s4, o4;
  const h4 = n3 || [0], u4 = (e4 = e4 || 0) >>> 3, w4 = -1 === r4 ? 3 : 0;
  for (i4 = 0; i4 < t4.length; i4 += 1)
    o4 = i4 + u4, s4 = o4 >>> 2, h4.length <= s4 && h4.push(0), h4[s4] |= t4[i4] << 8 * (w4 + r4 * (o4 % 4));
  return { value: h4, binLen: 8 * t4.length + e4 };
}
function e3(e4, r4, i4) {
  switch (r4) {
    case "UTF8":
    case "UTF16BE":
    case "UTF16LE":
      break;
    default:
      throw new Error("encoding must be UTF8, UTF16BE, or UTF16LE");
  }
  switch (e4) {
    case "HEX":
      return function(t4, n3, e5) {
        return function(t5, n4, e6, r5) {
          let i5, s4, o4, h4;
          if (0 != t5.length % 2)
            throw new Error("String of HEX type must be in byte increments");
          const u4 = n4 || [0], w4 = (e6 = e6 || 0) >>> 3, c4 = -1 === r5 ? 3 : 0;
          for (i5 = 0; i5 < t5.length; i5 += 2) {
            if (s4 = parseInt(t5.substr(i5, 2), 16), isNaN(s4))
              throw new Error("String of HEX type contains invalid characters");
            for (h4 = (i5 >>> 1) + w4, o4 = h4 >>> 2; u4.length <= o4; )
              u4.push(0);
            u4[o4] |= s4 << 8 * (c4 + r5 * (h4 % 4));
          }
          return { value: u4, binLen: 4 * t5.length + e6 };
        }(t4, n3, e5, i4);
      };
    case "TEXT":
      return function(t4, n3, e5) {
        return function(t5, n4, e6, r5, i5) {
          let s4, o4, h4, u4, w4, c4, f4, a4, l4 = 0;
          const A4 = e6 || [0], E2 = (r5 = r5 || 0) >>> 3;
          if ("UTF8" === n4)
            for (f4 = -1 === i5 ? 3 : 0, h4 = 0; h4 < t5.length; h4 += 1)
              for (s4 = t5.charCodeAt(h4), o4 = [], 128 > s4 ? o4.push(s4) : 2048 > s4 ? (o4.push(192 | s4 >>> 6), o4.push(128 | 63 & s4)) : 55296 > s4 || 57344 <= s4 ? o4.push(224 | s4 >>> 12, 128 | s4 >>> 6 & 63, 128 | 63 & s4) : (h4 += 1, s4 = 65536 + ((1023 & s4) << 10 | 1023 & t5.charCodeAt(h4)), o4.push(240 | s4 >>> 18, 128 | s4 >>> 12 & 63, 128 | s4 >>> 6 & 63, 128 | 63 & s4)), u4 = 0; u4 < o4.length; u4 += 1) {
                for (c4 = l4 + E2, w4 = c4 >>> 2; A4.length <= w4; )
                  A4.push(0);
                A4[w4] |= o4[u4] << 8 * (f4 + i5 * (c4 % 4)), l4 += 1;
              }
          else
            for (f4 = -1 === i5 ? 2 : 0, a4 = "UTF16LE" === n4 && 1 !== i5 || "UTF16LE" !== n4 && 1 === i5, h4 = 0; h4 < t5.length; h4 += 1) {
              for (s4 = t5.charCodeAt(h4), true === a4 && (u4 = 255 & s4, s4 = u4 << 8 | s4 >>> 8), c4 = l4 + E2, w4 = c4 >>> 2; A4.length <= w4; )
                A4.push(0);
              A4[w4] |= s4 << 8 * (f4 + i5 * (c4 % 4)), l4 += 2;
            }
          return { value: A4, binLen: 8 * l4 + r5 };
        }(t4, r4, n3, e5, i4);
      };
    case "B64":
      return function(n3, e5, r5) {
        return function(n4, e6, r6, i5) {
          let s4, o4, h4, u4, w4, c4, f4, a4 = 0;
          const l4 = e6 || [0], A4 = (r6 = r6 || 0) >>> 3, E2 = -1 === i5 ? 3 : 0, H3 = n4.indexOf("=");
          if (-1 === n4.search(/^[a-zA-Z0-9=+/]+$/))
            throw new Error("Invalid character in base-64 string");
          if (n4 = n4.replace(/=/g, ""), -1 !== H3 && H3 < n4.length)
            throw new Error("Invalid '=' found in base-64 string");
          for (o4 = 0; o4 < n4.length; o4 += 4) {
            for (w4 = n4.substr(o4, 4), u4 = 0, h4 = 0; h4 < w4.length; h4 += 1)
              s4 = t3.indexOf(w4.charAt(h4)), u4 |= s4 << 18 - 6 * h4;
            for (h4 = 0; h4 < w4.length - 1; h4 += 1) {
              for (f4 = a4 + A4, c4 = f4 >>> 2; l4.length <= c4; )
                l4.push(0);
              l4[c4] |= (u4 >>> 16 - 8 * h4 & 255) << 8 * (E2 + i5 * (f4 % 4)), a4 += 1;
            }
          }
          return { value: l4, binLen: 8 * a4 + r6 };
        }(n3, e5, r5, i4);
      };
    case "BYTES":
      return function(t4, n3, e5) {
        return function(t5, n4, e6, r5) {
          let i5, s4, o4, h4;
          const u4 = n4 || [0], w4 = (e6 = e6 || 0) >>> 3, c4 = -1 === r5 ? 3 : 0;
          for (s4 = 0; s4 < t5.length; s4 += 1)
            i5 = t5.charCodeAt(s4), h4 = s4 + w4, o4 = h4 >>> 2, u4.length <= o4 && u4.push(0), u4[o4] |= i5 << 8 * (c4 + r5 * (h4 % 4));
          return { value: u4, binLen: 8 * t5.length + e6 };
        }(t4, n3, e5, i4);
      };
    case "ARRAYBUFFER":
      try {
        new ArrayBuffer(0);
      } catch (t4) {
        throw new Error("ARRAYBUFFER not supported by this environment");
      }
      return function(t4, e5, r5) {
        return function(t5, e6, r6, i5) {
          return n2(new Uint8Array(t5), e6, r6, i5);
        }(t4, e5, r5, i4);
      };
    case "UINT8ARRAY":
      try {
        new Uint8Array(0);
      } catch (t4) {
        throw new Error("UINT8ARRAY not supported by this environment");
      }
      return function(t4, e5, r5) {
        return n2(t4, e5, r5, i4);
      };
    default:
      throw new Error("format must be HEX, TEXT, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY");
  }
}
function r3(n3, e4, r4, i4) {
  switch (n3) {
    case "HEX":
      return function(t4) {
        return function(t5, n4, e5, r5) {
          const i5 = "0123456789abcdef";
          let s4, o4, h4 = "";
          const u4 = n4 / 8, w4 = -1 === e5 ? 3 : 0;
          for (s4 = 0; s4 < u4; s4 += 1)
            o4 = t5[s4 >>> 2] >>> 8 * (w4 + e5 * (s4 % 4)), h4 += i5.charAt(o4 >>> 4 & 15) + i5.charAt(15 & o4);
          return r5.outputUpper ? h4.toUpperCase() : h4;
        }(t4, e4, r4, i4);
      };
    case "B64":
      return function(n4) {
        return function(n5, e5, r5, i5) {
          let s4, o4, h4, u4, w4, c4 = "";
          const f4 = e5 / 8, a4 = -1 === r5 ? 3 : 0;
          for (s4 = 0; s4 < f4; s4 += 3)
            for (u4 = s4 + 1 < f4 ? n5[s4 + 1 >>> 2] : 0, w4 = s4 + 2 < f4 ? n5[s4 + 2 >>> 2] : 0, h4 = (n5[s4 >>> 2] >>> 8 * (a4 + r5 * (s4 % 4)) & 255) << 16 | (u4 >>> 8 * (a4 + r5 * ((s4 + 1) % 4)) & 255) << 8 | w4 >>> 8 * (a4 + r5 * ((s4 + 2) % 4)) & 255, o4 = 0; o4 < 4; o4 += 1)
              c4 += 8 * s4 + 6 * o4 <= e5 ? t3.charAt(h4 >>> 6 * (3 - o4) & 63) : i5.b64Pad;
          return c4;
        }(n4, e4, r4, i4);
      };
    case "BYTES":
      return function(t4) {
        return function(t5, n4, e5) {
          let r5, i5, s4 = "";
          const o4 = n4 / 8, h4 = -1 === e5 ? 3 : 0;
          for (r5 = 0; r5 < o4; r5 += 1)
            i5 = t5[r5 >>> 2] >>> 8 * (h4 + e5 * (r5 % 4)) & 255, s4 += String.fromCharCode(i5);
          return s4;
        }(t4, e4, r4);
      };
    case "ARRAYBUFFER":
      try {
        new ArrayBuffer(0);
      } catch (t4) {
        throw new Error("ARRAYBUFFER not supported by this environment");
      }
      return function(t4) {
        return function(t5, n4, e5) {
          let r5;
          const i5 = n4 / 8, s4 = new ArrayBuffer(i5), o4 = new Uint8Array(s4), h4 = -1 === e5 ? 3 : 0;
          for (r5 = 0; r5 < i5; r5 += 1)
            o4[r5] = t5[r5 >>> 2] >>> 8 * (h4 + e5 * (r5 % 4)) & 255;
          return s4;
        }(t4, e4, r4);
      };
    case "UINT8ARRAY":
      try {
        new Uint8Array(0);
      } catch (t4) {
        throw new Error("UINT8ARRAY not supported by this environment");
      }
      return function(t4) {
        return function(t5, n4, e5) {
          let r5;
          const i5 = n4 / 8, s4 = -1 === e5 ? 3 : 0, o4 = new Uint8Array(i5);
          for (r5 = 0; r5 < i5; r5 += 1)
            o4[r5] = t5[r5 >>> 2] >>> 8 * (s4 + e5 * (r5 % 4)) & 255;
          return o4;
        }(t4, e4, r4);
      };
    default:
      throw new Error("format must be HEX, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY");
  }
}
var i3 = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298];
var s3 = [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428];
var o3 = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225];
var h3 = "Chosen SHA variant is not supported";
function u3(t4, n3) {
  let e4, r4;
  const i4 = t4.binLen >>> 3, s4 = n3.binLen >>> 3, o4 = i4 << 3, h4 = 4 - i4 << 3;
  if (i4 % 4 != 0) {
    for (e4 = 0; e4 < s4; e4 += 4)
      r4 = i4 + e4 >>> 2, t4.value[r4] |= n3.value[e4 >>> 2] << o4, t4.value.push(0), t4.value[r4 + 1] |= n3.value[e4 >>> 2] >>> h4;
    return (t4.value.length << 2) - 4 >= s4 + i4 && t4.value.pop(), { value: t4.value, binLen: t4.binLen + n3.binLen };
  }
  return { value: t4.value.concat(n3.value), binLen: t4.binLen + n3.binLen };
}
function w3(t4) {
  const n3 = { outputUpper: false, b64Pad: "=", outputLen: -1 }, e4 = t4 || {}, r4 = "Output length must be a multiple of 8";
  if (n3.outputUpper = e4.outputUpper || false, e4.b64Pad && (n3.b64Pad = e4.b64Pad), e4.outputLen) {
    if (e4.outputLen % 8 != 0)
      throw new Error(r4);
    n3.outputLen = e4.outputLen;
  } else if (e4.shakeLen) {
    if (e4.shakeLen % 8 != 0)
      throw new Error(r4);
    n3.outputLen = e4.shakeLen;
  }
  if ("boolean" != typeof n3.outputUpper)
    throw new Error("Invalid outputUpper formatting option");
  if ("string" != typeof n3.b64Pad)
    throw new Error("Invalid b64Pad formatting option");
  return n3;
}
function c3(t4, n3, r4, i4) {
  const s4 = t4 + " must include a value and format";
  if (!n3) {
    if (!i4)
      throw new Error(s4);
    return i4;
  }
  if (void 0 === n3.value || !n3.format)
    throw new Error(s4);
  return e3(n3.format, n3.encoding || "UTF8", r4)(n3.value);
}
var f3 = class {
  constructor(t4, n3, e4) {
    const r4 = e4 || {};
    if (this.t = n3, this.i = r4.encoding || "UTF8", this.numRounds = r4.numRounds || 1, isNaN(this.numRounds) || this.numRounds !== parseInt(this.numRounds, 10) || 1 > this.numRounds)
      throw new Error("numRounds must a integer >= 1");
    this.o = t4, this.h = [], this.u = 0, this.l = false, this.A = 0, this.H = false, this.S = [], this.p = [];
  }
  update(t4) {
    let n3, e4 = 0;
    const r4 = this.m >>> 5, i4 = this.C(t4, this.h, this.u), s4 = i4.binLen, o4 = i4.value, h4 = s4 >>> 5;
    for (n3 = 0; n3 < h4; n3 += r4)
      e4 + this.m <= s4 && (this.R = this.U(o4.slice(n3, n3 + r4), this.R), e4 += this.m);
    return this.A += e4, this.h = o4.slice(e4 >>> 5), this.u = s4 % this.m, this.l = true, this;
  }
  getHash(t4, n3) {
    let e4, i4, s4 = this.v;
    const o4 = w3(n3);
    if (this.K) {
      if (-1 === o4.outputLen)
        throw new Error("Output length must be specified in options");
      s4 = o4.outputLen;
    }
    const h4 = r3(t4, s4, this.T, o4);
    if (this.H && this.F)
      return h4(this.F(o4));
    for (i4 = this.g(this.h.slice(), this.u, this.A, this.B(this.R), s4), e4 = 1; e4 < this.numRounds; e4 += 1)
      this.K && s4 % 32 != 0 && (i4[i4.length - 1] &= 16777215 >>> 24 - s4 % 32), i4 = this.g(i4, s4, 0, this.L(this.o), s4);
    return h4(i4);
  }
  setHMACKey(t4, n3, r4) {
    if (!this.M)
      throw new Error("Variant does not support HMAC");
    if (this.l)
      throw new Error("Cannot set MAC key after calling update");
    const i4 = e3(n3, (r4 || {}).encoding || "UTF8", this.T);
    this.k(i4(t4));
  }
  k(t4) {
    const n3 = this.m >>> 3, e4 = n3 / 4 - 1;
    let r4;
    if (1 !== this.numRounds)
      throw new Error("Cannot set numRounds with MAC");
    if (this.H)
      throw new Error("MAC key already set");
    for (n3 < t4.binLen / 8 && (t4.value = this.g(t4.value, t4.binLen, 0, this.L(this.o), this.v)); t4.value.length <= e4; )
      t4.value.push(0);
    for (r4 = 0; r4 <= e4; r4 += 1)
      this.S[r4] = 909522486 ^ t4.value[r4], this.p[r4] = 1549556828 ^ t4.value[r4];
    this.R = this.U(this.S, this.R), this.A = this.m, this.H = true;
  }
  getHMAC(t4, n3) {
    const e4 = w3(n3);
    return r3(t4, this.v, this.T, e4)(this.Y());
  }
  Y() {
    let t4;
    if (!this.H)
      throw new Error("Cannot call getHMAC without first setting MAC key");
    const n3 = this.g(this.h.slice(), this.u, this.A, this.B(this.R), this.v);
    return t4 = this.U(this.p, this.L(this.o)), t4 = this.g(n3, this.v, this.m, t4, this.v), t4;
  }
};
function a3(t4, n3) {
  return t4 << n3 | t4 >>> 32 - n3;
}
function l3(t4, n3) {
  return t4 >>> n3 | t4 << 32 - n3;
}
function A3(t4, n3) {
  return t4 >>> n3;
}
function E(t4, n3, e4) {
  return t4 ^ n3 ^ e4;
}
function H2(t4, n3, e4) {
  return t4 & n3 ^ ~t4 & e4;
}
function S3(t4, n3, e4) {
  return t4 & n3 ^ t4 & e4 ^ n3 & e4;
}
function b3(t4) {
  return l3(t4, 2) ^ l3(t4, 13) ^ l3(t4, 22);
}
function p4(t4, n3) {
  const e4 = (65535 & t4) + (65535 & n3);
  return (65535 & (t4 >>> 16) + (n3 >>> 16) + (e4 >>> 16)) << 16 | 65535 & e4;
}
function d3(t4, n3, e4, r4) {
  const i4 = (65535 & t4) + (65535 & n3) + (65535 & e4) + (65535 & r4);
  return (65535 & (t4 >>> 16) + (n3 >>> 16) + (e4 >>> 16) + (r4 >>> 16) + (i4 >>> 16)) << 16 | 65535 & i4;
}
function m3(t4, n3, e4, r4, i4) {
  const s4 = (65535 & t4) + (65535 & n3) + (65535 & e4) + (65535 & r4) + (65535 & i4);
  return (65535 & (t4 >>> 16) + (n3 >>> 16) + (e4 >>> 16) + (r4 >>> 16) + (i4 >>> 16) + (s4 >>> 16)) << 16 | 65535 & s4;
}
function C2(t4) {
  return l3(t4, 7) ^ l3(t4, 18) ^ A3(t4, 3);
}
function y3(t4) {
  return l3(t4, 6) ^ l3(t4, 11) ^ l3(t4, 25);
}
function R(t4) {
  return [1732584193, 4023233417, 2562383102, 271733878, 3285377520];
}
function U(t4, n3) {
  let e4, r4, i4, s4, o4, h4, u4;
  const w4 = [];
  for (e4 = n3[0], r4 = n3[1], i4 = n3[2], s4 = n3[3], o4 = n3[4], u4 = 0; u4 < 80; u4 += 1)
    w4[u4] = u4 < 16 ? t4[u4] : a3(w4[u4 - 3] ^ w4[u4 - 8] ^ w4[u4 - 14] ^ w4[u4 - 16], 1), h4 = u4 < 20 ? m3(a3(e4, 5), H2(r4, i4, s4), o4, 1518500249, w4[u4]) : u4 < 40 ? m3(a3(e4, 5), E(r4, i4, s4), o4, 1859775393, w4[u4]) : u4 < 60 ? m3(a3(e4, 5), S3(r4, i4, s4), o4, 2400959708, w4[u4]) : m3(a3(e4, 5), E(r4, i4, s4), o4, 3395469782, w4[u4]), o4 = s4, s4 = i4, i4 = a3(r4, 30), r4 = e4, e4 = h4;
  return n3[0] = p4(e4, n3[0]), n3[1] = p4(r4, n3[1]), n3[2] = p4(i4, n3[2]), n3[3] = p4(s4, n3[3]), n3[4] = p4(o4, n3[4]), n3;
}
function v3(t4, n3, e4, r4) {
  let i4;
  const s4 = 15 + (n3 + 65 >>> 9 << 4), o4 = n3 + e4;
  for (; t4.length <= s4; )
    t4.push(0);
  for (t4[n3 >>> 5] |= 128 << 24 - n3 % 32, t4[s4] = 4294967295 & o4, t4[s4 - 1] = o4 / 4294967296 | 0, i4 = 0; i4 < t4.length; i4 += 16)
    r4 = U(t4.slice(i4, i4 + 16), r4);
  return r4;
}
var K3 = class extends f3 {
  constructor(t4, n3, r4) {
    if ("SHA-1" !== t4)
      throw new Error(h3);
    super(t4, n3, r4);
    const i4 = r4 || {};
    this.M = true, this.F = this.Y, this.T = -1, this.C = e3(this.t, this.i, this.T), this.U = U, this.B = function(t5) {
      return t5.slice();
    }, this.L = R, this.g = v3, this.R = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.m = 512, this.v = 160, this.K = false, i4.hmacKey && this.k(c3("hmacKey", i4.hmacKey, this.T));
  }
};
function T3(t4) {
  let n3;
  return n3 = "SHA-224" == t4 ? s3.slice() : o3.slice(), n3;
}
function F2(t4, n3) {
  let e4, r4, s4, o4, h4, u4, w4, c4, f4, a4, E2;
  const R2 = [];
  for (e4 = n3[0], r4 = n3[1], s4 = n3[2], o4 = n3[3], h4 = n3[4], u4 = n3[5], w4 = n3[6], c4 = n3[7], E2 = 0; E2 < 64; E2 += 1)
    R2[E2] = E2 < 16 ? t4[E2] : d3(l3(U2 = R2[E2 - 2], 17) ^ l3(U2, 19) ^ A3(U2, 10), R2[E2 - 7], C2(R2[E2 - 15]), R2[E2 - 16]), f4 = m3(c4, y3(h4), H2(h4, u4, w4), i3[E2], R2[E2]), a4 = p4(b3(e4), S3(e4, r4, s4)), c4 = w4, w4 = u4, u4 = h4, h4 = p4(o4, f4), o4 = s4, s4 = r4, r4 = e4, e4 = p4(f4, a4);
  var U2;
  return n3[0] = p4(e4, n3[0]), n3[1] = p4(r4, n3[1]), n3[2] = p4(s4, n3[2]), n3[3] = p4(o4, n3[3]), n3[4] = p4(h4, n3[4]), n3[5] = p4(u4, n3[5]), n3[6] = p4(w4, n3[6]), n3[7] = p4(c4, n3[7]), n3;
}
var g3 = class extends f3 {
  constructor(t4, n3, r4) {
    if ("SHA-224" !== t4 && "SHA-256" !== t4)
      throw new Error(h3);
    super(t4, n3, r4);
    const i4 = r4 || {};
    this.F = this.Y, this.M = true, this.T = -1, this.C = e3(this.t, this.i, this.T), this.U = F2, this.B = function(t5) {
      return t5.slice();
    }, this.L = T3, this.g = function(n4, e4, r5, i5) {
      return function(t5, n5, e5, r6, i6) {
        let s4, o4;
        const h4 = 15 + (n5 + 65 >>> 9 << 4), u4 = n5 + e5;
        for (; t5.length <= h4; )
          t5.push(0);
        for (t5[n5 >>> 5] |= 128 << 24 - n5 % 32, t5[h4] = 4294967295 & u4, t5[h4 - 1] = u4 / 4294967296 | 0, s4 = 0; s4 < t5.length; s4 += 16)
          r6 = F2(t5.slice(s4, s4 + 16), r6);
        return o4 = "SHA-224" === i6 ? [r6[0], r6[1], r6[2], r6[3], r6[4], r6[5], r6[6]] : r6, o4;
      }(n4, e4, r5, i5, t4);
    }, this.R = T3(t4), this.m = 512, this.v = "SHA-224" === t4 ? 224 : 256, this.K = false, i4.hmacKey && this.k(c3("hmacKey", i4.hmacKey, this.T));
  }
};
var B3 = class {
  constructor(t4, n3) {
    this.N = t4, this.I = n3;
  }
};
function L3(t4, n3) {
  let e4;
  return n3 > 32 ? (e4 = 64 - n3, new B3(t4.I << n3 | t4.N >>> e4, t4.N << n3 | t4.I >>> e4)) : 0 !== n3 ? (e4 = 32 - n3, new B3(t4.N << n3 | t4.I >>> e4, t4.I << n3 | t4.N >>> e4)) : t4;
}
function M3(t4, n3) {
  let e4;
  return n3 < 32 ? (e4 = 32 - n3, new B3(t4.N >>> n3 | t4.I << e4, t4.I >>> n3 | t4.N << e4)) : (e4 = 64 - n3, new B3(t4.I >>> n3 | t4.N << e4, t4.N >>> n3 | t4.I << e4));
}
function k3(t4, n3) {
  return new B3(t4.N >>> n3, t4.I >>> n3 | t4.N << 32 - n3);
}
function Y2(t4, n3, e4) {
  return new B3(t4.N & n3.N ^ t4.N & e4.N ^ n3.N & e4.N, t4.I & n3.I ^ t4.I & e4.I ^ n3.I & e4.I);
}
function N2(t4) {
  const n3 = M3(t4, 28), e4 = M3(t4, 34), r4 = M3(t4, 39);
  return new B3(n3.N ^ e4.N ^ r4.N, n3.I ^ e4.I ^ r4.I);
}
function I3(t4, n3) {
  let e4, r4;
  e4 = (65535 & t4.I) + (65535 & n3.I), r4 = (t4.I >>> 16) + (n3.I >>> 16) + (e4 >>> 16);
  const i4 = (65535 & r4) << 16 | 65535 & e4;
  e4 = (65535 & t4.N) + (65535 & n3.N) + (r4 >>> 16), r4 = (t4.N >>> 16) + (n3.N >>> 16) + (e4 >>> 16);
  return new B3((65535 & r4) << 16 | 65535 & e4, i4);
}
function X2(t4, n3, e4, r4) {
  let i4, s4;
  i4 = (65535 & t4.I) + (65535 & n3.I) + (65535 & e4.I) + (65535 & r4.I), s4 = (t4.I >>> 16) + (n3.I >>> 16) + (e4.I >>> 16) + (r4.I >>> 16) + (i4 >>> 16);
  const o4 = (65535 & s4) << 16 | 65535 & i4;
  i4 = (65535 & t4.N) + (65535 & n3.N) + (65535 & e4.N) + (65535 & r4.N) + (s4 >>> 16), s4 = (t4.N >>> 16) + (n3.N >>> 16) + (e4.N >>> 16) + (r4.N >>> 16) + (i4 >>> 16);
  return new B3((65535 & s4) << 16 | 65535 & i4, o4);
}
function z3(t4, n3, e4, r4, i4) {
  let s4, o4;
  s4 = (65535 & t4.I) + (65535 & n3.I) + (65535 & e4.I) + (65535 & r4.I) + (65535 & i4.I), o4 = (t4.I >>> 16) + (n3.I >>> 16) + (e4.I >>> 16) + (r4.I >>> 16) + (i4.I >>> 16) + (s4 >>> 16);
  const h4 = (65535 & o4) << 16 | 65535 & s4;
  s4 = (65535 & t4.N) + (65535 & n3.N) + (65535 & e4.N) + (65535 & r4.N) + (65535 & i4.N) + (o4 >>> 16), o4 = (t4.N >>> 16) + (n3.N >>> 16) + (e4.N >>> 16) + (r4.N >>> 16) + (i4.N >>> 16) + (s4 >>> 16);
  return new B3((65535 & o4) << 16 | 65535 & s4, h4);
}
function x2(t4, n3) {
  return new B3(t4.N ^ n3.N, t4.I ^ n3.I);
}
function _3(t4) {
  const n3 = M3(t4, 19), e4 = M3(t4, 61), r4 = k3(t4, 6);
  return new B3(n3.N ^ e4.N ^ r4.N, n3.I ^ e4.I ^ r4.I);
}
function O2(t4) {
  const n3 = M3(t4, 1), e4 = M3(t4, 8), r4 = k3(t4, 7);
  return new B3(n3.N ^ e4.N ^ r4.N, n3.I ^ e4.I ^ r4.I);
}
function P3(t4) {
  const n3 = M3(t4, 14), e4 = M3(t4, 18), r4 = M3(t4, 41);
  return new B3(n3.N ^ e4.N ^ r4.N, n3.I ^ e4.I ^ r4.I);
}
var V = [new B3(i3[0], 3609767458), new B3(i3[1], 602891725), new B3(i3[2], 3964484399), new B3(i3[3], 2173295548), new B3(i3[4], 4081628472), new B3(i3[5], 3053834265), new B3(i3[6], 2937671579), new B3(i3[7], 3664609560), new B3(i3[8], 2734883394), new B3(i3[9], 1164996542), new B3(i3[10], 1323610764), new B3(i3[11], 3590304994), new B3(i3[12], 4068182383), new B3(i3[13], 991336113), new B3(i3[14], 633803317), new B3(i3[15], 3479774868), new B3(i3[16], 2666613458), new B3(i3[17], 944711139), new B3(i3[18], 2341262773), new B3(i3[19], 2007800933), new B3(i3[20], 1495990901), new B3(i3[21], 1856431235), new B3(i3[22], 3175218132), new B3(i3[23], 2198950837), new B3(i3[24], 3999719339), new B3(i3[25], 766784016), new B3(i3[26], 2566594879), new B3(i3[27], 3203337956), new B3(i3[28], 1034457026), new B3(i3[29], 2466948901), new B3(i3[30], 3758326383), new B3(i3[31], 168717936), new B3(i3[32], 1188179964), new B3(i3[33], 1546045734), new B3(i3[34], 1522805485), new B3(i3[35], 2643833823), new B3(i3[36], 2343527390), new B3(i3[37], 1014477480), new B3(i3[38], 1206759142), new B3(i3[39], 344077627), new B3(i3[40], 1290863460), new B3(i3[41], 3158454273), new B3(i3[42], 3505952657), new B3(i3[43], 106217008), new B3(i3[44], 3606008344), new B3(i3[45], 1432725776), new B3(i3[46], 1467031594), new B3(i3[47], 851169720), new B3(i3[48], 3100823752), new B3(i3[49], 1363258195), new B3(i3[50], 3750685593), new B3(i3[51], 3785050280), new B3(i3[52], 3318307427), new B3(i3[53], 3812723403), new B3(i3[54], 2003034995), new B3(i3[55], 3602036899), new B3(i3[56], 1575990012), new B3(i3[57], 1125592928), new B3(i3[58], 2716904306), new B3(i3[59], 442776044), new B3(i3[60], 593698344), new B3(i3[61], 3733110249), new B3(i3[62], 2999351573), new B3(i3[63], 3815920427), new B3(3391569614, 3928383900), new B3(3515267271, 566280711), new B3(3940187606, 3454069534), new B3(4118630271, 4000239992), new B3(116418474, 1914138554), new B3(174292421, 2731055270), new B3(289380356, 3203993006), new B3(460393269, 320620315), new B3(685471733, 587496836), new B3(852142971, 1086792851), new B3(1017036298, 365543100), new B3(1126000580, 2618297676), new B3(1288033470, 3409855158), new B3(1501505948, 4234509866), new B3(1607167915, 987167468), new B3(1816402316, 1246189591)];
function Z2(t4) {
  return "SHA-384" === t4 ? [new B3(3418070365, s3[0]), new B3(1654270250, s3[1]), new B3(2438529370, s3[2]), new B3(355462360, s3[3]), new B3(1731405415, s3[4]), new B3(41048885895, s3[5]), new B3(3675008525, s3[6]), new B3(1203062813, s3[7])] : [new B3(o3[0], 4089235720), new B3(o3[1], 2227873595), new B3(o3[2], 4271175723), new B3(o3[3], 1595750129), new B3(o3[4], 2917565137), new B3(o3[5], 725511199), new B3(o3[6], 4215389547), new B3(o3[7], 327033209)];
}
function j3(t4, n3) {
  let e4, r4, i4, s4, o4, h4, u4, w4, c4, f4, a4, l4;
  const A4 = [];
  for (e4 = n3[0], r4 = n3[1], i4 = n3[2], s4 = n3[3], o4 = n3[4], h4 = n3[5], u4 = n3[6], w4 = n3[7], a4 = 0; a4 < 80; a4 += 1)
    a4 < 16 ? (l4 = 2 * a4, A4[a4] = new B3(t4[l4], t4[l4 + 1])) : A4[a4] = X2(_3(A4[a4 - 2]), A4[a4 - 7], O2(A4[a4 - 15]), A4[a4 - 16]), c4 = z3(w4, P3(o4), (H3 = h4, S4 = u4, new B3((E2 = o4).N & H3.N ^ ~E2.N & S4.N, E2.I & H3.I ^ ~E2.I & S4.I)), V[a4], A4[a4]), f4 = I3(N2(e4), Y2(e4, r4, i4)), w4 = u4, u4 = h4, h4 = o4, o4 = I3(s4, c4), s4 = i4, i4 = r4, r4 = e4, e4 = I3(c4, f4);
  var E2, H3, S4;
  return n3[0] = I3(e4, n3[0]), n3[1] = I3(r4, n3[1]), n3[2] = I3(i4, n3[2]), n3[3] = I3(s4, n3[3]), n3[4] = I3(o4, n3[4]), n3[5] = I3(h4, n3[5]), n3[6] = I3(u4, n3[6]), n3[7] = I3(w4, n3[7]), n3;
}
var q3 = class extends f3 {
  constructor(t4, n3, r4) {
    if ("SHA-384" !== t4 && "SHA-512" !== t4)
      throw new Error(h3);
    super(t4, n3, r4);
    const i4 = r4 || {};
    this.F = this.Y, this.M = true, this.T = -1, this.C = e3(this.t, this.i, this.T), this.U = j3, this.B = function(t5) {
      return t5.slice();
    }, this.L = Z2, this.g = function(n4, e4, r5, i5) {
      return function(t5, n5, e5, r6, i6) {
        let s4, o4;
        const h4 = 31 + (n5 + 129 >>> 10 << 5), u4 = n5 + e5;
        for (; t5.length <= h4; )
          t5.push(0);
        for (t5[n5 >>> 5] |= 128 << 24 - n5 % 32, t5[h4] = 4294967295 & u4, t5[h4 - 1] = u4 / 4294967296 | 0, s4 = 0; s4 < t5.length; s4 += 32)
          r6 = j3(t5.slice(s4, s4 + 32), r6);
        return o4 = "SHA-384" === i6 ? [r6[0].N, r6[0].I, r6[1].N, r6[1].I, r6[2].N, r6[2].I, r6[3].N, r6[3].I, r6[4].N, r6[4].I, r6[5].N, r6[5].I] : [r6[0].N, r6[0].I, r6[1].N, r6[1].I, r6[2].N, r6[2].I, r6[3].N, r6[3].I, r6[4].N, r6[4].I, r6[5].N, r6[5].I, r6[6].N, r6[6].I, r6[7].N, r6[7].I], o4;
      }(n4, e4, r5, i5, t4);
    }, this.R = Z2(t4), this.m = 1024, this.v = "SHA-384" === t4 ? 384 : 512, this.K = false, i4.hmacKey && this.k(c3("hmacKey", i4.hmacKey, this.T));
  }
};
var D3 = [new B3(0, 1), new B3(0, 32898), new B3(2147483648, 32906), new B3(2147483648, 2147516416), new B3(0, 32907), new B3(0, 2147483649), new B3(2147483648, 2147516545), new B3(2147483648, 32777), new B3(0, 138), new B3(0, 136), new B3(0, 2147516425), new B3(0, 2147483658), new B3(0, 2147516555), new B3(2147483648, 139), new B3(2147483648, 32905), new B3(2147483648, 32771), new B3(2147483648, 32770), new B3(2147483648, 128), new B3(0, 32778), new B3(2147483648, 2147483658), new B3(2147483648, 2147516545), new B3(2147483648, 32896), new B3(0, 2147483649), new B3(2147483648, 2147516424)];
var G = [[0, 36, 3, 41, 18], [1, 44, 10, 45, 2], [62, 6, 43, 15, 61], [28, 55, 25, 21, 56], [27, 20, 39, 8, 14]];
function J(t4) {
  let n3;
  const e4 = [];
  for (n3 = 0; n3 < 5; n3 += 1)
    e4[n3] = [new B3(0, 0), new B3(0, 0), new B3(0, 0), new B3(0, 0), new B3(0, 0)];
  return e4;
}
function Q(t4) {
  let n3;
  const e4 = [];
  for (n3 = 0; n3 < 5; n3 += 1)
    e4[n3] = t4[n3].slice();
  return e4;
}
function W(t4, n3) {
  let e4, r4, i4, s4;
  const o4 = [], h4 = [];
  if (null !== t4)
    for (r4 = 0; r4 < t4.length; r4 += 2)
      n3[(r4 >>> 1) % 5][(r4 >>> 1) / 5 | 0] = x2(n3[(r4 >>> 1) % 5][(r4 >>> 1) / 5 | 0], new B3(t4[r4 + 1], t4[r4]));
  for (e4 = 0; e4 < 24; e4 += 1) {
    for (s4 = J(), r4 = 0; r4 < 5; r4 += 1)
      o4[r4] = (u4 = n3[r4][0], w4 = n3[r4][1], c4 = n3[r4][2], f4 = n3[r4][3], a4 = n3[r4][4], new B3(u4.N ^ w4.N ^ c4.N ^ f4.N ^ a4.N, u4.I ^ w4.I ^ c4.I ^ f4.I ^ a4.I));
    for (r4 = 0; r4 < 5; r4 += 1)
      h4[r4] = x2(o4[(r4 + 4) % 5], L3(o4[(r4 + 1) % 5], 1));
    for (r4 = 0; r4 < 5; r4 += 1)
      for (i4 = 0; i4 < 5; i4 += 1)
        n3[r4][i4] = x2(n3[r4][i4], h4[r4]);
    for (r4 = 0; r4 < 5; r4 += 1)
      for (i4 = 0; i4 < 5; i4 += 1)
        s4[i4][(2 * r4 + 3 * i4) % 5] = L3(n3[r4][i4], G[r4][i4]);
    for (r4 = 0; r4 < 5; r4 += 1)
      for (i4 = 0; i4 < 5; i4 += 1)
        n3[r4][i4] = x2(s4[r4][i4], new B3(~s4[(r4 + 1) % 5][i4].N & s4[(r4 + 2) % 5][i4].N, ~s4[(r4 + 1) % 5][i4].I & s4[(r4 + 2) % 5][i4].I));
    n3[0][0] = x2(n3[0][0], D3[e4]);
  }
  var u4, w4, c4, f4, a4;
  return n3;
}
function $2(t4) {
  let n3, e4, r4 = 0;
  const i4 = [0, 0], s4 = [4294967295 & t4, t4 / 4294967296 & 2097151];
  for (n3 = 6; n3 >= 0; n3--)
    e4 = s4[n3 >> 2] >>> 8 * n3 & 255, 0 === e4 && 0 === r4 || (i4[r4 + 1 >> 2] |= e4 << 8 * (r4 + 1), r4 += 1);
  return r4 = 0 !== r4 ? r4 : 1, i4[0] |= r4, { value: r4 + 1 > 4 ? i4 : [i4[0]], binLen: 8 + 8 * r4 };
}
function tt(t4) {
  return u3($2(t4.binLen), t4);
}
function nt(t4, n3) {
  let e4, r4 = $2(n3);
  r4 = u3(r4, t4);
  const i4 = n3 >>> 2, s4 = (i4 - r4.value.length % i4) % i4;
  for (e4 = 0; e4 < s4; e4++)
    r4.value.push(0);
  return r4.value;
}
var et2 = class extends f3 {
  constructor(t4, n3, r4) {
    let i4 = 6, s4 = 0;
    super(t4, n3, r4);
    const o4 = r4 || {};
    if (1 !== this.numRounds) {
      if (o4.kmacKey || o4.hmacKey)
        throw new Error("Cannot set numRounds with MAC");
      if ("CSHAKE128" === this.o || "CSHAKE256" === this.o)
        throw new Error("Cannot set numRounds for CSHAKE variants");
    }
    switch (this.T = 1, this.C = e3(this.t, this.i, this.T), this.U = W, this.B = Q, this.L = J, this.R = J(), this.K = false, t4) {
      case "SHA3-224":
        this.m = s4 = 1152, this.v = 224, this.M = true, this.F = this.Y;
        break;
      case "SHA3-256":
        this.m = s4 = 1088, this.v = 256, this.M = true, this.F = this.Y;
        break;
      case "SHA3-384":
        this.m = s4 = 832, this.v = 384, this.M = true, this.F = this.Y;
        break;
      case "SHA3-512":
        this.m = s4 = 576, this.v = 512, this.M = true, this.F = this.Y;
        break;
      case "SHAKE128":
        i4 = 31, this.m = s4 = 1344, this.v = -1, this.K = true, this.M = false, this.F = null;
        break;
      case "SHAKE256":
        i4 = 31, this.m = s4 = 1088, this.v = -1, this.K = true, this.M = false, this.F = null;
        break;
      case "KMAC128":
        i4 = 4, this.m = s4 = 1344, this.X(r4), this.v = -1, this.K = true, this.M = false, this.F = this._;
        break;
      case "KMAC256":
        i4 = 4, this.m = s4 = 1088, this.X(r4), this.v = -1, this.K = true, this.M = false, this.F = this._;
        break;
      case "CSHAKE128":
        this.m = s4 = 1344, i4 = this.O(r4), this.v = -1, this.K = true, this.M = false, this.F = null;
        break;
      case "CSHAKE256":
        this.m = s4 = 1088, i4 = this.O(r4), this.v = -1, this.K = true, this.M = false, this.F = null;
        break;
      default:
        throw new Error(h3);
    }
    this.g = function(t5, n4, e4, r5, o5) {
      return function(t6, n5, e5, r6, i5, s5, o6) {
        let h4, u4, w4 = 0;
        const c4 = [], f4 = i5 >>> 5, a4 = n5 >>> 5;
        for (h4 = 0; h4 < a4 && n5 >= i5; h4 += f4)
          r6 = W(t6.slice(h4, h4 + f4), r6), n5 -= i5;
        for (t6 = t6.slice(h4), n5 %= i5; t6.length < f4; )
          t6.push(0);
        for (h4 = n5 >>> 3, t6[h4 >> 2] ^= s5 << h4 % 4 * 8, t6[f4 - 1] ^= 2147483648, r6 = W(t6, r6); 32 * c4.length < o6 && (u4 = r6[w4 % 5][w4 / 5 | 0], c4.push(u4.I), !(32 * c4.length >= o6)); )
          c4.push(u4.N), w4 += 1, 0 == 64 * w4 % i5 && (W(null, r6), w4 = 0);
        return c4;
      }(t5, n4, 0, r5, s4, i4, o5);
    }, o4.hmacKey && this.k(c3("hmacKey", o4.hmacKey, this.T));
  }
  O(t4, n3) {
    const e4 = function(t5) {
      const n4 = t5 || {};
      return { funcName: c3("funcName", n4.funcName, 1, { value: [], binLen: 0 }), customization: c3("Customization", n4.customization, 1, { value: [], binLen: 0 }) };
    }(t4 || {});
    n3 && (e4.funcName = n3);
    const r4 = u3(tt(e4.funcName), tt(e4.customization));
    if (0 !== e4.customization.binLen || 0 !== e4.funcName.binLen) {
      const t5 = nt(r4, this.m >>> 3);
      for (let n4 = 0; n4 < t5.length; n4 += this.m >>> 5)
        this.R = this.U(t5.slice(n4, n4 + (this.m >>> 5)), this.R), this.A += this.m;
      return 4;
    }
    return 31;
  }
  X(t4) {
    const n3 = function(t5) {
      const n4 = t5 || {};
      return { kmacKey: c3("kmacKey", n4.kmacKey, 1), funcName: { value: [1128353099], binLen: 32 }, customization: c3("Customization", n4.customization, 1, { value: [], binLen: 0 }) };
    }(t4 || {});
    this.O(t4, n3.funcName);
    const e4 = nt(tt(n3.kmacKey), this.m >>> 3);
    for (let t5 = 0; t5 < e4.length; t5 += this.m >>> 5)
      this.R = this.U(e4.slice(t5, t5 + (this.m >>> 5)), this.R), this.A += this.m;
    this.H = true;
  }
  _(t4) {
    const n3 = u3({ value: this.h.slice(), binLen: this.u }, function(t5) {
      let n4, e4, r4 = 0;
      const i4 = [0, 0], s4 = [4294967295 & t5, t5 / 4294967296 & 2097151];
      for (n4 = 6; n4 >= 0; n4--)
        e4 = s4[n4 >> 2] >>> 8 * n4 & 255, 0 === e4 && 0 === r4 || (i4[r4 >> 2] |= e4 << 8 * r4, r4 += 1);
      return r4 = 0 !== r4 ? r4 : 1, i4[r4 >> 2] |= r4 << 8 * r4, { value: r4 + 1 > 4 ? i4 : [i4[0]], binLen: 8 + 8 * r4 };
    }(t4.outputLen));
    return this.g(n3.value, n3.binLen, this.A, this.B(this.R), t4.outputLen);
  }
};
var rt = class {
  constructor(t4, n3, e4) {
    if ("SHA-1" == t4)
      this.P = new K3(t4, n3, e4);
    else if ("SHA-224" == t4 || "SHA-256" == t4)
      this.P = new g3(t4, n3, e4);
    else if ("SHA-384" == t4 || "SHA-512" == t4)
      this.P = new q3(t4, n3, e4);
    else {
      if ("SHA3-224" != t4 && "SHA3-256" != t4 && "SHA3-384" != t4 && "SHA3-512" != t4 && "SHAKE128" != t4 && "SHAKE256" != t4 && "CSHAKE128" != t4 && "CSHAKE256" != t4 && "KMAC128" != t4 && "KMAC256" != t4)
        throw new Error(h3);
      this.P = new et2(t4, n3, e4);
    }
  }
  update(t4) {
    return this.P.update(t4), this;
  }
  getHash(t4, n3) {
    return this.P.getHash(t4, n3);
  }
  setHMACKey(t4, n3, e4) {
    this.P.setHMACKey(t4, n3, e4);
  }
  getHMAC(t4, n3) {
    return this.P.getHMAC(t4, n3);
  }
};

// src/pages/home/authMethod/totp.ts
var SEARCH_RANGE = 16;
var timeStep = 30;
function computeTOTPandCheck(secretKey, digits, code) {
  const now2 = (/* @__PURE__ */ new Date()).getTime();
  const epoch = Math.floor(Math.round(now2 / 1e3) / timeStep);
  for (let ms = -SEARCH_RANGE; ms < SEARCH_RANGE; ms++) {
    const movingFactor = (epoch + ms).toString(16).padStart(16, "0");
    const hmacSha = new rt("SHA-1", "HEX", {
      hmacKey: { value: secretKey, format: "UINT8ARRAY" }
    });
    hmacSha.update(movingFactor);
    const hmac_text = hmacSha.getHMAC("UINT8ARRAY");
    const offset = hmac_text[hmac_text.length - 1] & 15;
    const otp = ((hmac_text[offset + 0] << 24) + (hmac_text[offset + 1] << 16) + (hmac_text[offset + 2] << 8) + hmac_text[offset + 3] & 2147483647) % Math.pow(10, digits);
    if (otp == code)
      return true;
  }
  return false;
}
var encTable__ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split("");
function base32enc(buffer) {
  let rpos = 0;
  let bits2 = 0;
  let vbit = 0;
  let result = "";
  while (rpos < buffer.length || vbit > 0) {
    if (rpos < buffer.length && vbit < 5) {
      bits2 = bits2 << 8 | buffer[rpos++];
      vbit += 8;
    }
    if (vbit < 5) {
      bits2 <<= 5 - vbit;
      vbit = 5;
    }
    result += encTable__[bits2 >> vbit - 5 & 31];
    vbit -= 5;
  }
  return result;
}

// src/pages/home/authMethod/AuthMethodTotpSetup.tsx
var ANASTASIS_TOTP_DIGITS = 8;
function AuthMethodTotpSetup({
  addAuthMethod,
  cancel,
  configured
}) {
  const [name, setName] = p3("anastasis");
  const [test, setTest] = p3("");
  const secretKey = F(() => {
    const array = new Uint8Array(32);
    if (typeof window === "undefined")
      return array;
    return window.crypto.getRandomValues(array);
  }, []);
  const secret32 = base32enc(secretKey);
  const totpURL = `otpauth://totp/${name}?digits=${ANASTASIS_TOTP_DIGITS}&secret=${secret32}`;
  const addTotpAuth = () => addAuthMethod({
    authentication_method: {
      type: "totp",
      instructions: `Enter ${ANASTASIS_TOTP_DIGITS} digits code for "${name}"`,
      challenge: encodeCrock(secretKey)
    }
  });
  const testCodeMatches = computeTOTPandCheck(secretKey, 8, parseInt(test, 10));
  const errors2 = !name ? "The TOTP name is missing" : !testCodeMatches ? "The test code doesn't match" : void 0;
  function goNextIfNoErrors() {
    if (!errors2)
      addTotpAuth();
  }
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Add TOTP authentication" }, /* @__PURE__ */ h("p", null, "For Time-based One-Time Password (TOTP) authentication, you need to set a name for the TOTP secret. Then, you must scan the generated QR code with your TOTP App to import the TOTP secret into your TOTP App."), /* @__PURE__ */ h("div", { class: "block" }, /* @__PURE__ */ h(TextInput, { label: "TOTP Name", grabFocus: true, bind: [name, setName] })), /* @__PURE__ */ h("div", { style: { height: 300 } }, /* @__PURE__ */ h(QR, { text: totpURL })), /* @__PURE__ */ h("p", null, "Confirm that your TOTP App works by entering the current 8-digit TOTP code here:"), /* @__PURE__ */ h(
    TextInput,
    {
      label: "Test code",
      onConfirm: goNextIfNoErrors,
      bind: [test, setTest]
    }
  ), /* @__PURE__ */ h("div", null, "We note that Google's implementation of TOTP is incomplete and will not work. We recommend using FreeOTP+."), configured.length > 0 && /* @__PURE__ */ h("section", { class: "section" }, /* @__PURE__ */ h("div", { class: "block" }, "Your TOTP numbers:"), /* @__PURE__ */ h("div", { class: "block" }, configured.map((c4, i4) => {
    return /* @__PURE__ */ h(
      "div",
      {
        key: i4,
        class: "box",
        style: { display: "flex", justifyContent: "space-between" }
      },
      /* @__PURE__ */ h("p", { style: { marginTop: "auto", marginBottom: "auto" } }, c4.instructions),
      /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("button", { class: "button is-danger", onClick: c4.remove }, "Delete"))
    );
  }))), /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: cancel }, "Cancel"),
    /* @__PURE__ */ h("span", { "data-tooltip": errors2 }, /* @__PURE__ */ h(
      "button",
      {
        class: "button is-info",
        disabled: errors2 !== void 0,
        onClick: addTotpAuth
      },
      "Add"
    ))
  )));
}

// src/pages/home/authMethod/AuthMethodTotpSolve.tsx
init_preact_module();
function AuthMethodTotpSolve(props) {
  const [answerCode, setAnswerCode] = p3("");
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "no reducer in context"));
  }
  if (reducer.currentReducerState?.reducer_type !== "recovery") {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state"));
  }
  if (!reducer.currentReducerState.recovery_information) {
    return /* @__PURE__ */ h(
      AnastasisClientFrame,
      {
        hideNext: "Recovery document not found",
        title: "Recovery problem"
      },
      /* @__PURE__ */ h("div", null, "no recovery information found")
    );
  }
  if (!reducer.currentReducerState.selected_challenge_uuid) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery problem" }, /* @__PURE__ */ h("div", null, "invalid state"), /* @__PURE__ */ h(
      "div",
      {
        style: {
          marginTop: "2em",
          display: "flex",
          justifyContent: "space-between"
        }
      },
      /* @__PURE__ */ h("button", { class: "button", onClick: () => reducer.back() }, "Back")
    ));
  }
  const chArr = reducer.currentReducerState.recovery_information.challenges;
  const challengeFeedback = reducer.currentReducerState.challenge_feedback ?? {};
  const selectedUuid = reducer.currentReducerState.selected_challenge_uuid;
  const challenges = {};
  for (const ch of chArr) {
    challenges[ch.uuid] = ch;
  }
  const feedback = challengeFeedback[selectedUuid];
  async function onNext() {
    return reducer?.transition("solve_challenge", {
      answer: answerCode
    });
  }
  function onCancel() {
    reducer?.back();
  }
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "TOTP Challenge" }, /* @__PURE__ */ h(SolveOverviewFeedbackDisplay, { feedback }), /* @__PURE__ */ h("p", null, "enter the totp solution"), /* @__PURE__ */ h(
    TextInput,
    {
      label: "Answer",
      onConfirm: onNext,
      grabFocus: true,
      bind: [answerCode, setAnswerCode]
    }
  ), /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: onCancel }, "Cancel"),
    !shouldHideConfirm(feedback) && /* @__PURE__ */ h(AsyncButton, { class: "button is-info", onClick: onNext }, "Confirm")
  ));
}

// src/pages/home/authMethod/index.tsx
var ALL_METHODS = [
  "sms",
  "email",
  "post",
  "question",
  "totp",
  "iban"
];
function isKnownAuthMethods(value) {
  return ALL_METHODS.includes(value);
}
var authMethods = {
  question: {
    icon: /* @__PURE__ */ h("img", { src: question_default }),
    label: "Question",
    setup: AuthMethodQuestionSetup,
    solve: AuthMethodQuestionSolve
  },
  sms: {
    icon: /* @__PURE__ */ h("img", { src: sms_default }),
    label: "SMS",
    setup: AuthMethodSmsSetup,
    solve: AuthMethodSmsSolve
  },
  email: {
    icon: /* @__PURE__ */ h("i", { class: "mdi mdi-email" }),
    label: "Email",
    setup: AuthMethodEmailSetup,
    solve: AuthMethodEmailSolve
  },
  iban: {
    icon: /* @__PURE__ */ h("i", { class: "mdi mdi-bank" }),
    label: "IBAN",
    setup: AuthMethodIbanSetup,
    solve: AuthMethodIbanSolve
  },
  post: {
    icon: /* @__PURE__ */ h("img", { src: postal_default }),
    label: "Physical mail",
    setup: AuthMethodPostSetup,
    solve: AuthMethodPostSolve
  },
  totp: {
    icon: /* @__PURE__ */ h("i", { class: "mdi mdi-devices" }),
    label: "TOTP",
    setup: AuthMethodTotpSetup,
    solve: AuthMethodTotpSolve
  }
};

// src/pages/home/AddingProviderScreen/state.ts
function useComponentState({
  providerType,
  onCancel,
  notifications = []
}) {
  const reducer = useAnastasisContext();
  const [providerURL, setProviderURL] = p3("");
  const [error2, setError] = p3();
  const [testing, setTesting] = p3(false);
  const providerLabel = providerType ? authMethods[providerType].label : void 0;
  const allAuthProviders = !reducer || !reducer.currentReducerState || reducer.currentReducerState.reducer_type === "error" || !reducer.currentReducerState.authentication_providers ? {} : reducer.currentReducerState.authentication_providers;
  const authProvidersByStatus = Object.keys(allAuthProviders).reduce(
    (prev, url2) => {
      const p5 = allAuthProviders[url2];
      if (providerLabel && p5.status === "ok" && p5.methods.findIndex((m4) => m4.type === providerType) !== -1) {
        return prev;
      }
      prev[p5.status].push({ ...p5, url: url2 });
      return prev;
    },
    {
      "not-contacted": [],
      disabled: [],
      error: [],
      ok: []
    }
  );
  const authProviders = authProvidersByStatus["ok"].map((p5) => p5.url);
  const timeout = _2(void 0);
  h2(() => {
    if (timeout.current)
      clearTimeout(timeout.current);
    timeout.current = setTimeout(async () => {
      let url2 = providerURL;
      if (!url2 || authProviders.includes(url2))
        return;
      if (url2 && !url2.match(/^(https?:)\/\/.+\/(?:config)?$/iu))
        return setError(
          "Malformed URL: Must be an HTTP(S) URL ending with a /"
        );
      if (url2.endsWith("/config"))
        url2 = url2.substring(0, url2.length - 6);
      try {
        setTesting(true);
        await testProvider(url2, providerType);
        setError("");
      } catch (e4) {
        if (e4 instanceof Error)
          setError(e4.message);
        else
          throw new Error(
            `Unexpected Error Type: ${typeof e4} - Cannot handle. Error: ${e4}`
          );
      }
      setTesting(false);
    }, 200);
  }, [providerURL, reducer]);
  if (!reducer) {
    return {
      status: "no-reducer"
    };
  }
  if (!reducer.currentReducerState || !("authentication_providers" in reducer.currentReducerState)) {
    return {
      status: "invalid-state"
    };
  }
  const addProvider = async (provider_url) => {
    await reducer.transition("add_provider", { provider_url });
    onCancel();
  };
  const deleteProvider = async (provider_url) => {
    reducer.transition("delete_provider", { provider_url });
  };
  let errors2 = !providerURL ? "Add provider URL" : void 0;
  let url;
  const _url = url;
  if (!!error2 && !errors2) {
    errors2 = error2;
  }
  if (!errors2 && authProviders.includes(url)) {
    errors2 = "That provider is already known";
  }
  const commonState = {
    addProvider: !_url ? void 0 : async () => addProvider(_url),
    deleteProvider: async (url2) => deleteProvider(url2),
    allAuthProviders,
    authProvidersByStatus,
    onCancel,
    providerURL,
    testing,
    setProviderURL: async (s4) => setProviderURL(s4),
    errors: errors2,
    error: error2,
    notifications
  };
  if (!providerLabel) {
    return {
      status: "without-type",
      ...commonState
    };
  } else {
    return {
      status: "with-type",
      providerLabel,
      ...commonState
    };
  }
}

// src/pages/home/AddingProviderScreen/views.tsx
init_preact_module();
function WithProviderType(props) {
  const { i18n: i18n2 } = useTranslationContext();
  return /* @__PURE__ */ h(
    AnastasisClientFrame,
    {
      hideNav: true,
      title: "Backup: Manage providers1",
      hideNext: props.errors
    },
    /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(Notifications, { notifications: props.notifications }), /* @__PURE__ */ h("p", null, i18n2.str`Add a provider url for a ${props.providerLabel} service`), /* @__PURE__ */ h("div", { class: "container" }, /* @__PURE__ */ h(
      TextInput,
      {
        label: "Provider URL",
        placeholder: "https://provider.com",
        grabFocus: true,
        error: props.errors,
        bind: [props.providerURL, props.setProviderURL]
      }
    )), /* @__PURE__ */ h("p", { class: "block" }, "Example: https://kudos.demo.anastasis.lu"), props.testing && /* @__PURE__ */ h("p", { class: "has-text-info" }, "Testing"), /* @__PURE__ */ h(
      "div",
      {
        class: "block",
        style: {
          marginTop: "2em",
          display: "flex",
          justifyContent: "space-between"
        }
      },
      /* @__PURE__ */ h("button", { class: "button", onClick: props.onCancel }, "Cancel"),
      /* @__PURE__ */ h("span", { "data-tooltip": props.errors }, /* @__PURE__ */ h(
        "button",
        {
          class: "button is-info",
          disabled: props.error !== "" || props.testing,
          onClick: props.addProvider
        },
        "Add"
      ))
    ), props.authProvidersByStatus["ok"].length > 0 ? /* @__PURE__ */ h("p", { class: "subtitle" }, "Current providers for ", props.providerLabel, " service") : /* @__PURE__ */ h("p", { class: "subtitle" }, "No known providers for ", props.providerLabel, " service"), props.authProvidersByStatus["ok"].map((k4, i4) => {
      const p5 = k4;
      return /* @__PURE__ */ h(
        TableRow,
        {
          key: i4,
          url: k4.url,
          info: p5,
          onDelete: props.deleteProvider
        }
      );
    }), /* @__PURE__ */ h("p", { class: "subtitle" }, "Providers with errors"), props.authProvidersByStatus["error"].map((k4, i4) => {
      const p5 = k4;
      return /* @__PURE__ */ h(
        TableRowError,
        {
          key: i4,
          url: k4.url,
          info: p5,
          onDelete: props.deleteProvider
        }
      );
    }))
  );
}
function WithoutProviderType(props) {
  return /* @__PURE__ */ h(
    AnastasisClientFrame,
    {
      hideNav: true,
      title: "Backup: Manage providers",
      hideNext: props.errors
    },
    /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(Notifications, { notifications: props.notifications }), /* @__PURE__ */ h("p", null, "Add a provider url"), /* @__PURE__ */ h("div", { class: "container" }, /* @__PURE__ */ h(
      TextInput,
      {
        label: "Provider URL",
        placeholder: "https://provider.com/",
        grabFocus: true,
        error: props.errors,
        bind: [props.providerURL, props.setProviderURL]
      }
    )), /* @__PURE__ */ h("p", { class: "block" }, "Example: https://kudos.demo.anastasis.lu/"), props.testing && /* @__PURE__ */ h("p", { class: "has-text-info" }, "Testing"), /* @__PURE__ */ h(
      "div",
      {
        class: "block",
        style: {
          marginTop: "2em",
          display: "flex",
          justifyContent: "space-between"
        }
      },
      /* @__PURE__ */ h("button", { class: "button", onClick: props.onCancel }, "Cancel"),
      /* @__PURE__ */ h("span", { "data-tooltip": props.errors }, /* @__PURE__ */ h(
        "button",
        {
          class: "button is-info",
          disabled: props.error !== "" || props.testing,
          onClick: props.addProvider
        },
        "Add"
      ))
    ), props.authProvidersByStatus["ok"].length > 0 ? /* @__PURE__ */ h("p", { class: "subtitle" }, "Current providers") : /* @__PURE__ */ h("p", { class: "subtitle" }, "No known providers, add one."), props.authProvidersByStatus["ok"].map((k4, i4) => {
      const p5 = k4;
      return /* @__PURE__ */ h(
        TableRow,
        {
          key: i4,
          url: k4.url,
          info: p5,
          onDelete: props.deleteProvider
        }
      );
    }), /* @__PURE__ */ h("p", { class: "subtitle" }, "Providers with errors"), props.authProvidersByStatus["error"].map((k4, i4) => {
      const p5 = k4;
      return /* @__PURE__ */ h(
        TableRowError,
        {
          key: i4,
          url: k4.url,
          info: p5,
          onDelete: props.deleteProvider
        }
      );
    }))
  );
}
function TableRow({
  url,
  info,
  onDelete
}) {
  const [status, setStatus] = p3("checking");
  h2(function() {
    testProvider(url.endsWith("/") ? url.substring(0, url.length - 1) : url).then(function() {
      setStatus("responding");
    }).catch(function() {
      setStatus("failed to contact");
    });
  });
  return /* @__PURE__ */ h(
    "div",
    {
      class: "box",
      style: { display: "flex", justifyContent: "space-between" }
    },
    /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("div", { class: "subtitle" }, url), /* @__PURE__ */ h("dl", null, /* @__PURE__ */ h("dt", null, /* @__PURE__ */ h("b", null, "Business Name")), /* @__PURE__ */ h("dd", null, info.business_name), /* @__PURE__ */ h("dt", null, /* @__PURE__ */ h("b", null, "Supported methods")), /* @__PURE__ */ h("dd", null, info.methods.map((m4) => m4.type).join(",")), /* @__PURE__ */ h("dt", null, /* @__PURE__ */ h("b", null, "Maximum storage")), /* @__PURE__ */ h("dd", null, info.storage_limit_in_megabytes, " Mb"), /* @__PURE__ */ h("dt", null, /* @__PURE__ */ h("b", null, "Status")), /* @__PURE__ */ h("dd", null, status))),
    /* @__PURE__ */ h(
      "div",
      {
        class: "block",
        style: {
          marginTop: "auto",
          marginBottom: "auto",
          display: "flex",
          justifyContent: "space-between",
          flexDirection: "column"
        }
      },
      /* @__PURE__ */ h("button", { class: "button is-danger", onClick: () => onDelete(url) }, "Remove")
    )
  );
}
function TableRowError({
  url,
  info,
  onDelete
}) {
  const [status, setStatus] = p3("checking");
  h2(function() {
    testProvider(url.endsWith("/") ? url.substring(0, url.length - 1) : url).then(function() {
      setStatus("responding");
    }).catch(function() {
      setStatus("failed to contact");
    });
  });
  return /* @__PURE__ */ h(
    "div",
    {
      class: "box",
      style: { display: "flex", justifyContent: "space-between" }
    },
    /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("div", { class: "subtitle" }, url), /* @__PURE__ */ h("dl", null, /* @__PURE__ */ h("dt", null, /* @__PURE__ */ h("b", null, "Error")), /* @__PURE__ */ h("dd", null, info.hint), /* @__PURE__ */ h("dt", null, /* @__PURE__ */ h("b", null, "Code")), /* @__PURE__ */ h("dd", null, info.code), /* @__PURE__ */ h("dt", null, /* @__PURE__ */ h("b", null, "Status")), /* @__PURE__ */ h("dd", null, status))),
    /* @__PURE__ */ h(
      "div",
      {
        class: "block",
        style: {
          marginTop: "auto",
          marginBottom: "auto",
          display: "flex",
          justifyContent: "space-between",
          flexDirection: "column"
        }
      },
      /* @__PURE__ */ h("button", { class: "button is-danger", onClick: () => onDelete(url) }, "Remove")
    )
  );
}

// src/pages/home/AddingProviderScreen/index.ts
var map2 = {
  "no-reducer": NoReducer,
  "invalid-state": InvalidState,
  "with-type": WithProviderType,
  "without-type": WithoutProviderType
};
var AddingProviderScreen_default = compose("AddingProviderScreen", useComponentState, map2);
var providerResponseCache = /* @__PURE__ */ new Map();
async function testProvider(url, expectedMethodType) {
  const testFatalPrefix = `Encountered a fatal error whilst testing the provider ${url}`;
  let configUrl = "";
  try {
    configUrl = new URL("config", url).href;
  } catch (error2) {
    throw new Error(`${testFatalPrefix}: Invalid Provider URL: ${url}
Error: ${error2}`);
  }
  const providerHasUrl = providerResponseCache.has(url);
  const json = providerHasUrl ? providerResponseCache.get(url) : await fetch(configUrl).catch((error2) => {
    throw new Error(`${testFatalPrefix}: Could not connect: ${error2}
Please check the URL.`);
  }).then(async (response) => {
    if (!response.ok)
      throw new Error(
        `${testFatalPrefix}: The server ${response.url} responded with a non-2xx response.`
      );
    try {
      return await response.json();
    } catch (error2) {
      throw new Error(
        `${testFatalPrefix}: The server responded with malformed JSON.
Error: ${error2}`
      );
    }
  });
  if (typeof json !== "object")
    throw new Error(
      `${testFatalPrefix}: Did not get an object after decoding.`
    );
  if (!("name" in json) || json.name !== "anastasis") {
    throw new Error(
      `${testFatalPrefix}: The provider does not appear to be an Anastasis provider. Please check the provider's URL.`
    );
  }
  if (!("methods" in json) || !Array.isArray(json.methods)) {
    throw new Error(
      "This provider doesn't have authentication method. Please check the provider's URL and ensure it is properly configured."
    );
  }
  if (!providerHasUrl)
    providerResponseCache.set(url, json);
  if (!expectedMethodType) {
    return;
  }
  let found = false;
  for (let i4 = 0; i4 < json.methods.length && !found; i4++) {
    found = json.methods[i4].type === expectedMethodType;
  }
  if (!found) {
    throw new Error(
      `${testFatalPrefix}: This provider does not support authentication method ${expectedMethodType}`
    );
  }
  return;
}

// src/pages/home/AuthenticationEditorScreen.tsx
var getKeys = Object.keys;
function AuthenticationEditorScreen() {
  const [noProvidersAck, setNoProvidersAck] = p3(false);
  const [selectedMethod, setSelectedMethod] = p3(void 0);
  const [tooFewAuths, setTooFewAuths] = p3(false);
  const [manageProvider, setManageProvider] = p3(
    void 0
  );
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (reducer.currentReducerState?.reducer_type !== "backup") {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  const configuredAuthMethods = reducer.currentReducerState.authentication_methods ?? [];
  function removeByIndex(index) {
    if (reducer)
      reducer.transition("delete_authentication", {
        authentication_method: index
      });
  }
  const camByType = {};
  for (let index = 0; index < configuredAuthMethods.length; index++) {
    const cam = {
      ...configuredAuthMethods[index],
      remove: () => removeByIndex(index)
    };
    const prevValue = camByType[cam.type] || [];
    prevValue.push(cam);
    camByType[cam.type] = prevValue;
  }
  const providers = reducer.currentReducerState.authentication_providers;
  const authAvailableSet = /* @__PURE__ */ new Set();
  for (const provKey of Object.keys(providers)) {
    const p5 = providers[provKey];
    if (p5.status === "ok") {
      for (const meth of p5.methods) {
        authAvailableSet.add(meth.type);
      }
    }
  }
  if (manageProvider !== void 0) {
    return /* @__PURE__ */ h(
      AddingProviderScreen_default,
      {
        onCancel: async () => setManageProvider(void 0),
        providerType: isKnownAuthMethods(manageProvider) ? manageProvider : void 0
      }
    );
  }
  if (selectedMethod) {
    const cancel = () => setSelectedMethod(void 0);
    const addMethod = (args) => {
      reducer.transition("add_authentication", args);
      setSelectedMethod(void 0);
    };
    const AuthSetup = authMethods[selectedMethod].setup ?? AuthMethodNotImplemented;
    return /* @__PURE__ */ h(p, null, /* @__PURE__ */ h(
      AuthSetup,
      {
        cancel,
        configured: camByType[selectedMethod] || [],
        addAuthMethod: addMethod,
        method: selectedMethod
      }
    ), !authAvailableSet.has(selectedMethod) && /* @__PURE__ */ h(
      ConfirmModal,
      {
        active: true,
        onCancel: cancel,
        description: "No providers found",
        label: "Add a provider manually",
        onConfirm: async () => {
          setManageProvider(selectedMethod);
        }
      },
      /* @__PURE__ */ h("p", null, "We have found no Anastasis providers that support this authentication method. You can add a provider manually. To add a provider you must know the provider URL (e.g. https://provider.com)"),
      /* @__PURE__ */ h("p", null, /* @__PURE__ */ h("a", null, "Learn more about Anastasis providers"))
    ));
  }
  function MethodButton(props) {
    if (authMethods[props.method].skip)
      return /* @__PURE__ */ h("div", null);
    return /* @__PURE__ */ h("div", { class: "block" }, /* @__PURE__ */ h(
      "button",
      {
        style: { justifyContent: "space-between" },
        class: "button is-fullwidth",
        onClick: () => {
          setSelectedMethod(props.method);
        }
      },
      /* @__PURE__ */ h("div", { style: { display: "flex" } }, /* @__PURE__ */ h("span", { class: "icon " }, authMethods[props.method].icon), authAvailableSet.has(props.method) ? /* @__PURE__ */ h("span", null, "Add a ", authMethods[props.method].label, " challenge") : /* @__PURE__ */ h("span", null, "Add a ", authMethods[props.method].label, " provider")),
      !authAvailableSet.has(props.method) && /* @__PURE__ */ h("span", { class: "icon has-text-danger" }, /* @__PURE__ */ h("i", { class: "mdi mdi-exclamation-thick" })),
      camByType[props.method] && /* @__PURE__ */ h("span", { class: "tag is-info" }, camByType[props.method].length)
    ));
  }
  const errors2 = configuredAuthMethods.length < 2 ? "There is not enough authentication methods." : void 0;
  const handleNext = async () => {
    const st = reducer.currentReducerState;
    if ((st.authentication_methods ?? []).length <= 2) {
      setTooFewAuths(true);
    } else {
      await reducer.transition("next", {});
    }
  };
  return /* @__PURE__ */ h(
    AnastasisClientFrame,
    {
      title: "Backup: Configure Authentication Methods",
      hideNext: errors2,
      onNext: handleNext
    },
    /* @__PURE__ */ h("div", { class: "columns" }, /* @__PURE__ */ h("div", { class: "column" }, /* @__PURE__ */ h("div", null, getKeys(authMethods).map((method) => /* @__PURE__ */ h(MethodButton, { key: method, method }))), tooFewAuths ? /* @__PURE__ */ h(
      ConfirmModal,
      {
        active: tooFewAuths,
        onCancel: () => setTooFewAuths(false),
        description: "Too few auth methods configured",
        label: "Proceed anyway",
        onConfirm: () => reducer.transition("next", {})
      },
      "You have selected fewer than 3 authentication methods. We recommend that you add at least 3."
    ) : null, authAvailableSet.size === 0 && /* @__PURE__ */ h(
      ConfirmModal,
      {
        active: !noProvidersAck,
        onCancel: () => setNoProvidersAck(true),
        description: "No providers found",
        label: "Add a provider manually",
        onConfirm: async () => {
          setManageProvider("");
        }
      },
      /* @__PURE__ */ h("p", null, "We have found no Anastasis providers for your chosen country / currency. You can add a providers manually. To add a provider you must know the provider URL (e.g. https://provider.com)"),
      /* @__PURE__ */ h("p", null, /* @__PURE__ */ h("a", null, "Learn more about Anastasis providers"))
    )), /* @__PURE__ */ h("div", { class: "column" }, /* @__PURE__ */ h("p", { class: "block" }, "When recovering your secret data, you will be asked to verify your identity via the methods you configure here. The list of authentication method is defined by the backup provider list."), /* @__PURE__ */ h("p", { class: "block" }, /* @__PURE__ */ h(
      "button",
      {
        class: "button is-info",
        onClick: () => setManageProvider("")
      },
      "Manage backup providers"
    )), authAvailableSet.size > 0 && /* @__PURE__ */ h("p", { class: "block" }, "We couldn't find provider for some of the authentication methods.")))
  );
}
function AuthMethodNotImplemented(props) {
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: `Add ${props.method} authentication` }, /* @__PURE__ */ h("p", null, "This auth method is not implemented yet, please choose another one."), /* @__PURE__ */ h("button", { onClick: () => props.cancel() }, "Cancel"));
}

// src/pages/home/BackupFinishedScreen.tsx
init_preact_module();
function BackupFinishedScreen() {
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (reducer.currentReducerState?.reducer_type !== "backup") {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  const details = reducer.currentReducerState.success_details;
  const providers = reducer.currentReducerState.authentication_providers ?? {};
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Backup success!" }, /* @__PURE__ */ h("p", null, "Your backup is complete."), details && /* @__PURE__ */ h("div", { class: "block" }, /* @__PURE__ */ h("p", null, "The backup is stored by the following providers:"), Object.keys(details).map((url, i4) => {
    const sd = details[url];
    const p5 = providers[url];
    return /* @__PURE__ */ h("div", { key: i4, class: "box" }, /* @__PURE__ */ h("a", { href: url, target: "_blank", rel: "noreferrer" }, p5.business_name), /* @__PURE__ */ h("p", null, "version ", sd.policy_version, sd.policy_expiration.t_s !== "never" ? ` expires at: ${format(
      new Date(sd.policy_expiration.t_s * 1e3),
      "dd-MM-yyyy"
    )}` : " without expiration date"));
  }), /* @__PURE__ */ h(
    "div",
    {
      style: {
        display: "flex",
        justifyContent: "center"
      }
    },
    /* @__PURE__ */ h("p", null, /* @__PURE__ */ h("div", { class: "buttons ml-4" }, /* @__PURE__ */ h(
      "button",
      {
        class: "button is-primary is-right",
        onClick: () => reducer.reset()
      },
      "Start again"
    )))
  )));
}

// src/pages/home/ChallengeOverviewScreen.tsx
init_preact_module();
function OverviewFeedbackDisplay(props) {
  const { feedback } = props;
  if (!feedback) {
    return /* @__PURE__ */ h(p, null);
  }
  switch (feedback.state) {
    case ChallengeFeedbackStatus.Solved:
      return /* @__PURE__ */ h("div", null);
    case ChallengeFeedbackStatus.IbanInstructions:
      return /* @__PURE__ */ h("div", { class: "block has-text-info" }, "Payment required.");
    case ChallengeFeedbackStatus.ServerFailure:
      return /* @__PURE__ */ h("div", { class: "block has-text-danger" }, "Server error.");
    case ChallengeFeedbackStatus.RateLimitExceeded:
      return /* @__PURE__ */ h("div", { class: "block has-text-danger" }, "There were to many failed attempts.");
    case ChallengeFeedbackStatus.Unsupported:
      return /* @__PURE__ */ h("div", { class: "block has-text-danger" }, "This client doesn't support solving this type of challenge. Use another version or contact the provider.");
    case ChallengeFeedbackStatus.TruthUnknown:
      return /* @__PURE__ */ h("div", { class: "block has-text-danger" }, "Provider doesn't recognize the type of challenge. Use another version or contact the provider.");
    case ChallengeFeedbackStatus.IncorrectAnswer:
      return /* @__PURE__ */ h("div", { class: "block has-text-danger" }, "The answer was not correct.");
    case ChallengeFeedbackStatus.CodeInFile:
      return /* @__PURE__ */ h("div", { class: "block has-text-info" }, "code in file");
    case ChallengeFeedbackStatus.CodeSent:
      return /* @__PURE__ */ h("div", { class: "block has-text-info" }, "Code sent");
    case ChallengeFeedbackStatus.TalerPayment:
      return /* @__PURE__ */ h("div", { class: "block has-text-info" }, "Payment required");
  }
}
function ChallengeOverviewScreen() {
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (reducer.currentReducerState?.reducer_type !== "recovery") {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  const policies = reducer.currentReducerState.recovery_information?.policies ?? [];
  const knownChallengesArray = reducer.currentReducerState.recovery_information?.challenges ?? [];
  const challengeFeedback = reducer.currentReducerState?.challenge_feedback ?? {};
  const knownChallengesMap = {};
  for (const ch of knownChallengesArray) {
    knownChallengesMap[ch.uuid] = {
      type: ch.type,
      instructions: ch.instructions,
      feedback: challengeFeedback[ch.uuid]
    };
  }
  const policiesWithInfo = policies.map((row) => {
    let isPolicySolved = true;
    const challenges = row.map(({ uuid }) => {
      const info = knownChallengesMap[uuid];
      const isChallengeSolved = info?.feedback?.state === "solved";
      isPolicySolved = isPolicySolved && isChallengeSolved;
      return { info, uuid, isChallengeSolved };
    }).filter((ch) => ch.info !== void 0);
    return {
      isPolicySolved,
      challenges,
      corrupted: row.length > challenges.length
    };
  }).filter((p5) => !p5.corrupted);
  const atLeastThereIsOnePolicySolved = policiesWithInfo.find((p5) => p5.isPolicySolved) !== void 0;
  const errors2 = !atLeastThereIsOnePolicySolved ? "Solve one policy before proceeding" : void 0;
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNext: errors2, title: "Recovery: Solve challenges" }, !policiesWithInfo.length ? /* @__PURE__ */ h("p", { class: "block" }, "No policies found, try with another version of the secret") : policiesWithInfo.length === 1 ? /* @__PURE__ */ h("p", { class: "block" }, "One policy found for this secret. You need to solve all the challenges in order to recover your secret.") : /* @__PURE__ */ h("p", { class: "block" }, "We have found ", policiesWithInfo.length, " polices. You need to solve all the challenges from one policy in order to recover your secret."), policiesWithInfo.map((policy, policy_index) => {
    const tableBody = policy.challenges.map(({ info, uuid }) => {
      const method = authMethods[info.type];
      if (!method) {
        return /* @__PURE__ */ h(
          "div",
          {
            key: uuid,
            class: "block",
            style: { display: "flex", justifyContent: "space-between" }
          },
          /* @__PURE__ */ h("div", { style: { display: "flex", alignItems: "center" } }, /* @__PURE__ */ h("span", null, "unknown challenge"))
        );
      }
      function ChallengeButton({
        id,
        feedback
      }) {
        async function selectChallenge2() {
          if (reducer) {
            return reducer.transition("select_challenge", { uuid: id });
          }
        }
        if (!feedback) {
          return /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
            AsyncButton,
            {
              class: "button",
              disabled: atLeastThereIsOnePolicySolved && !policy.isPolicySolved,
              onClick: selectChallenge2
            },
            "Solve"
          ));
        }
        switch (feedback.state) {
          case ChallengeFeedbackStatus.ServerFailure:
          case ChallengeFeedbackStatus.Unsupported:
          case ChallengeFeedbackStatus.TruthUnknown:
          case ChallengeFeedbackStatus.RateLimitExceeded:
            return /* @__PURE__ */ h("div", null);
          case ChallengeFeedbackStatus.IbanInstructions:
          case ChallengeFeedbackStatus.TalerPayment:
            return /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
              AsyncButton,
              {
                class: "button",
                disabled: atLeastThereIsOnePolicySolved && !policy.isPolicySolved,
                onClick: selectChallenge2
              },
              "Pay"
            ));
          case ChallengeFeedbackStatus.Solved:
            return /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("div", { class: "tag is-success is-large" }, "Solved"));
          default:
            return /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
              AsyncButton,
              {
                class: "button",
                disabled: atLeastThereIsOnePolicySolved && !policy.isPolicySolved,
                onClick: selectChallenge2
              },
              "Solve"
            ));
        }
      }
      return /* @__PURE__ */ h(
        "div",
        {
          key: uuid,
          class: "block",
          style: { display: "flex", justifyContent: "space-between" }
        },
        /* @__PURE__ */ h(
          "div",
          {
            style: {
              display: "flex",
              flexDirection: "column"
            }
          },
          /* @__PURE__ */ h("div", { style: { display: "flex", alignItems: "center" } }, /* @__PURE__ */ h("span", { class: "icon" }, method?.icon), /* @__PURE__ */ h("span", null, info.instructions)),
          /* @__PURE__ */ h(OverviewFeedbackDisplay, { feedback: info.feedback })
        ),
        /* @__PURE__ */ h(ChallengeButton, { id: uuid, feedback: info.feedback })
      );
    });
    const policyName = policy.challenges.map((x3) => x3.info.type).join(" + ");
    const opa = !atLeastThereIsOnePolicySolved ? void 0 : policy.isPolicySolved ? void 0 : "0.6";
    return /* @__PURE__ */ h(
      "div",
      {
        key: policy_index,
        class: "box",
        style: {
          opacity: opa
        }
      },
      /* @__PURE__ */ h("h3", { class: "subtitle" }, "Policy #", policy_index + 1, ": ", policyName),
      policy.challenges.length === 0 && /* @__PURE__ */ h("p", null, "This policy doesn't have any challenges."),
      policy.challenges.length === 1 && /* @__PURE__ */ h("p", null, "This policy has one challenge."),
      policy.challenges.length > 1 && /* @__PURE__ */ h("p", null, "This policy has ", policy.challenges.length, " challenges."),
      tableBody
    );
  }));
}

// src/pages/home/ChallengePayingScreen.tsx
init_preact_module();
function ChallengePayingScreen() {
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (reducer.currentReducerState?.reducer_type !== "recovery") {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  const payments = [""];
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Recovery: Challenge Paying" }, /* @__PURE__ */ h("p", null, "Some of the providers require a payment to store the encrypted authentication information."), /* @__PURE__ */ h("ul", null, payments.map((x3, i4) => {
    return /* @__PURE__ */ h("li", { key: i4 }, x3);
  })), /* @__PURE__ */ h("button", { onClick: () => reducer.transition("pay", {}) }, "Check payment status now"));
}

// src/pages/home/ContinentSelectionScreen.tsx
init_preact_module();
function ContinentSelectionScreen() {
  const reducer = useAnastasisContext();
  const countryFromReducer = (reducer?.currentReducerState).selected_country || "";
  const [countryCode, setCountryCode] = p3(countryFromReducer);
  if (!reducer || !reducer.currentReducerState || !("continents" in reducer.currentReducerState)) {
    return /* @__PURE__ */ h("div", null);
  }
  const selectContinent = (continent) => {
    reducer.transition("select_continent", { continent });
  };
  const selectCountry2 = (country) => {
    setCountryCode(country);
  };
  const continentList = reducer.currentReducerState.continents || [];
  const countryList = reducer.currentReducerState.countries || [];
  const theContinent = reducer.currentReducerState.selected_continent || "";
  const theCountry = countryList.find((c4) => c4.code === countryCode);
  const selectCountryAction = async () => {
    if (!theCountry)
      return;
    reducer.transition("select_country", {
      country_code: countryCode
    });
  };
  const errors2 = !theCountry ? "Select a country" : void 0;
  const handleBack = async () => {
    reducer.reset();
  };
  return /* @__PURE__ */ h(
    AnastasisClientFrame,
    {
      hideNext: errors2,
      title: withProcessLabel(reducer, "Where do you live?"),
      onNext: selectCountryAction,
      onBack: handleBack
    },
    /* @__PURE__ */ h("div", { class: "columns" }, /* @__PURE__ */ h("div", { class: "column is-one-third" }, /* @__PURE__ */ h("div", { class: "field" }, /* @__PURE__ */ h("label", { class: "label" }, "Continent"), /* @__PURE__ */ h("div", { class: "control is-expanded has-icons-left" }, /* @__PURE__ */ h("div", { class: "select is-fullwidth" }, /* @__PURE__ */ h(
      "select",
      {
        onChange: (e4) => selectContinent(e4.currentTarget.value),
        value: theContinent
      },
      /* @__PURE__ */ h("option", { key: "none", disabled: true, selected: true, value: "" }, " ", "Choose a continent", " "),
      continentList.map((prov) => /* @__PURE__ */ h("option", { key: prov.name, value: prov.name }, prov.name))
    ), /* @__PURE__ */ h("div", { class: "icon is-small is-left" }, /* @__PURE__ */ h("i", { class: "mdi mdi-earth" }))))), /* @__PURE__ */ h("div", { class: "field" }, /* @__PURE__ */ h("label", { class: "label" }, "Country"), /* @__PURE__ */ h("div", { class: "control is-expanded has-icons-left" }, /* @__PURE__ */ h("div", { class: "select is-fullwidth" }, /* @__PURE__ */ h(
      "select",
      {
        onChange: (e4) => selectCountry2(e4.target.value),
        disabled: !theContinent,
        value: theCountry?.code || ""
      },
      /* @__PURE__ */ h("option", { key: "none", disabled: true, selected: true, value: "" }, " ", "Choose a country", " "),
      countryList.map((prov) => /* @__PURE__ */ h("option", { key: prov.name, value: prov.code }, prov.name))
    ), /* @__PURE__ */ h("div", { class: "icon is-small is-left" }, /* @__PURE__ */ h("i", { class: "mdi mdi-earth" })))))), /* @__PURE__ */ h("div", { class: "column is-two-third" }, /* @__PURE__ */ h("p", null, "Your selection will help us ask right information to uniquely identify you when you want to recover your secret again."), /* @__PURE__ */ h("p", null, "Choose the country that issued most of your long-term legal documents or personal identifiers.")))
  );
}

// src/pages/home/PoliciesPayingScreen.tsx
init_preact_module();
function PoliciesPayingScreen() {
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (reducer.currentReducerState?.reducer_type !== "backup") {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  const payments = reducer.currentReducerState.policy_payment_requests ?? [];
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Backup: Recovery Document Payments" }, /* @__PURE__ */ h("p", null, "Some of the providers require a payment to store the encrypted recovery document."), /* @__PURE__ */ h("ul", null, payments.map((x3, i4) => {
    return /* @__PURE__ */ h("li", { key: i4 }, x3.provider, ": ", x3.payto);
  })), /* @__PURE__ */ h("button", { onClick: () => reducer.transition("pay", {}) }, "Check payment status now"));
}

// src/pages/home/RecoveryFinishedScreen.tsx
init_preact_module();
function RecoveryFinishedScreen() {
  const reducer = useAnastasisContext();
  const [copied, setCopied] = p3(false);
  h2(() => {
    setTimeout(() => {
      setCopied(false);
    }, 1e3);
  }, [copied]);
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (reducer.currentReducerState?.reducer_type !== "recovery") {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  const secretName = reducer.currentReducerState.recovery_document?.secret_name;
  const encodedSecret = reducer.currentReducerState.core_secret;
  if (!encodedSecret) {
    return /* @__PURE__ */ h(AnastasisClientFrame, { title: "Recovery Problem", hideNav: true }, /* @__PURE__ */ h("p", null, "Secret not found"), /* @__PURE__ */ h(
      "div",
      {
        style: {
          marginTop: "2em",
          display: "flex",
          justifyContent: "space-between"
        }
      },
      /* @__PURE__ */ h("button", { class: "button", onClick: () => reducer.back() }, "Back")
    ));
  }
  const secret = bytesToString(decodeCrock(encodedSecret.value));
  const plainText = encodedSecret.value.length < 1e3 && encodedSecret.mime === "text/plain";
  let [uri, setUri] = p3(`data:${encodedSecret.mime},${secret}`);
  fetch(`data:${encodedSecret.mime},${secret}`).then((v4) => v4.blob()).then((blob) => URL.createObjectURL(blob)).then((newUri) => {
    setUri(newUri);
  });
  return /* @__PURE__ */ h(AnastasisClientFrame, { title: "Recovery Success", hideNav: true }, /* @__PURE__ */ h("h2", { class: "subtitle" }, "Your secret was recovered"), secretName && /* @__PURE__ */ h("p", { class: "block" }, /* @__PURE__ */ h("b", null, "Secret name:"), " ", secretName), /* @__PURE__ */ h("div", { class: "block buttons", disabled: copied }, plainText ? /* @__PURE__ */ h(
    "button",
    {
      class: "button",
      onClick: () => {
        navigator.clipboard.writeText(secret);
        setCopied(true);
      }
    },
    !copied ? "Copy" : "Copied"
  ) : void 0, /* @__PURE__ */ h(
    "a",
    {
      class: "button is-info",
      download: encodedSecret.filename ? encodedSecret.filename : "secret.file",
      href: uri
    },
    /* @__PURE__ */ h("div", { class: "icon is-small " }, /* @__PURE__ */ h("i", { class: "mdi mdi-download" })),
    /* @__PURE__ */ h("span", null, "Download content")
  )), plainText ? /* @__PURE__ */ h("div", { class: "block" }, /* @__PURE__ */ h(QR, { text: secret })) : void 0, /* @__PURE__ */ h(
    "div",
    {
      style: {
        display: "flex",
        justifyContent: "center"
      }
    },
    /* @__PURE__ */ h("p", null, /* @__PURE__ */ h("div", { class: "buttons ml-4" }, /* @__PURE__ */ h(
      "button",
      {
        class: "button is-primary is-right",
        onClick: () => reducer.reset()
      },
      "Start again"
    )))
  ));
}

// src/pages/home/ReviewPoliciesScreen.tsx
init_preact_module();

// src/pages/home/EditPoliciesScreen.tsx
init_preact_module();
function EditPoliciesScreen({
  index: policy_index,
  cancel,
  confirm
}) {
  const [changedProvider, setChangedProvider] = p3([]);
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (reducer.currentReducerState?.reducer_type !== "backup") {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  const selectableProviders = {};
  const allProviders = Object.entries(
    reducer.currentReducerState.authentication_providers || {}
  );
  for (let index = 0; index < allProviders.length; index++) {
    const [url, status] = allProviders[index];
    if ("methods" in status) {
      status.methods.map((m4) => {
        const type = m4.type;
        const values = selectableProviders[type] || [];
        const isFree = !m4.usage_fee || m4.usage_fee.endsWith(":0");
        values.push({ url, cost: m4.usage_fee, isFree });
        selectableProviders[type] = values;
      });
    }
  }
  const allAuthMethods = reducer.currentReducerState.authentication_methods ?? [];
  const policies = reducer.currentReducerState.policies ?? [];
  const policy = policies[policy_index];
  for (let method_index = 0; method_index < allAuthMethods.length; method_index++) {
    policy?.methods.find((m4) => m4.authentication_method === method_index)?.provider;
  }
  function sendChanges() {
    const newMethods = [];
    allAuthMethods.forEach((method, index) => {
      const oldValue = policy?.methods.find(
        (m4) => m4.authentication_method === index
      );
      if (changedProvider[index] === void 0 && oldValue !== void 0) {
        newMethods.push(oldValue);
      }
      if (changedProvider[index] !== void 0 && changedProvider[index] !== "") {
        newMethods.push({
          authentication_method: index,
          provider: changedProvider[index]
        });
      }
    });
    confirm(newMethods);
  }
  return /* @__PURE__ */ h(
    AnastasisClientFrame,
    {
      hideNav: true,
      title: !policy ? "Backup: New Policy" : "Backup: Edit Policy"
    },
    /* @__PURE__ */ h("section", { class: "section" }, !policy ? /* @__PURE__ */ h("p", null, "Creating a new policy #", policy_index) : /* @__PURE__ */ h("p", null, "Editing policy #", policy_index), allAuthMethods.map((method, index) => {
      const providerURL = changedProvider[index] === void 0 ? policy?.methods.find((m4) => m4.authentication_method === index)?.provider : changedProvider[index];
      const type = method.type;
      function changeProviderTo(url) {
        const copy = [...changedProvider];
        copy[index] = url;
        setChangedProvider(copy);
      }
      return /* @__PURE__ */ h(
        "div",
        {
          key: index,
          class: "block",
          style: { display: "flex", alignItems: "center" }
        },
        /* @__PURE__ */ h("span", { class: "icon" }, authMethods[type]?.icon),
        /* @__PURE__ */ h("span", null, method.instructions),
        /* @__PURE__ */ h("span", null, /* @__PURE__ */ h("span", { class: "select " }, /* @__PURE__ */ h(
          "select",
          {
            onChange: (e4) => changeProviderTo(e4.currentTarget.value),
            value: providerURL ?? ""
          },
          /* @__PURE__ */ h("option", { key: "none", value: "" }, " ", "<< off >>", " "),
          selectableProviders[type]?.map((prov) => /* @__PURE__ */ h("option", { key: prov.url, value: prov.url }, prov.url))
        )))
      );
    }), /* @__PURE__ */ h(
      "div",
      {
        style: {
          marginTop: "2em",
          display: "flex",
          justifyContent: "space-between"
        }
      },
      /* @__PURE__ */ h("button", { class: "button", onClick: cancel }, "Cancel"),
      /* @__PURE__ */ h("span", { class: "buttons" }, /* @__PURE__ */ h("button", { class: "button", onClick: () => setChangedProvider([]) }, "Reset"), /* @__PURE__ */ h("button", { class: "button is-info", onClick: sendChanges }, "Confirm"))
    ))
  );
}

// src/pages/home/ReviewPoliciesScreen.tsx
function ReviewPoliciesScreen() {
  const [editingPolicy, setEditingPolicy] = p3();
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (reducer.currentReducerState?.reducer_type !== "backup") {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  const configuredAuthMethods = reducer.currentReducerState.authentication_methods ?? [];
  const policies = reducer.currentReducerState.policies ?? [];
  const providers = reducer.currentReducerState.authentication_providers ?? {};
  if (editingPolicy !== void 0) {
    return /* @__PURE__ */ h(
      EditPoliciesScreen,
      {
        index: editingPolicy,
        cancel: () => setEditingPolicy(void 0),
        confirm: async (newMethods) => {
          await reducer.transition("update_policy", {
            policy_index: editingPolicy,
            policy: newMethods
          });
          setEditingPolicy(void 0);
        }
      }
    );
  }
  const errors2 = policies.length < 1 ? "Need more policies" : void 0;
  return /* @__PURE__ */ h(
    AnastasisClientFrame,
    {
      hideNext: errors2,
      title: "Backup: Review Recovery Policies"
    },
    policies.length > 0 && /* @__PURE__ */ h("p", { class: "block" }, "Based on your configured authentication method you have created, some policies have been configured. In order to recover your secret you have to solve all the challenges of at least one policy."),
    policies.length < 1 && /* @__PURE__ */ h("p", { class: "block" }, "No policies had been created. Go back and add more authentication methods."),
    /* @__PURE__ */ h("div", { class: "block" }, /* @__PURE__ */ h(
      "button",
      {
        class: "button is-success",
        style: { marginLeft: 10 },
        onClick: () => setEditingPolicy(policies.length)
      },
      "Add new policy"
    )),
    policies.map((p5, policy_index) => {
      const methods = p5.methods.map(
        (x3) => configuredAuthMethods[x3.authentication_method] && {
          ...configuredAuthMethods[x3.authentication_method],
          provider: x3.provider
        }
      ).filter((x3) => !!x3);
      const policyName = methods.map((x3) => x3.type).join(" + ");
      if (p5.methods.length > methods.length) {
        return null;
      }
      return /* @__PURE__ */ h(
        "div",
        {
          key: policy_index,
          class: "box",
          style: { display: "flex", justifyContent: "space-between" }
        },
        /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("h3", { class: "subtitle" }, "Policy #", policy_index + 1, ": ", policyName), !methods.length && /* @__PURE__ */ h("p", null, "No auth method found"), methods.map((m4, i4) => {
          const p6 = providers[m4.provider];
          return /* @__PURE__ */ h(
            "p",
            {
              key: i4,
              class: "block",
              style: { display: "flex", alignItems: "center" }
            },
            /* @__PURE__ */ h("span", { class: "icon" }, authMethods[m4.type]?.icon),
            /* @__PURE__ */ h("span", null, m4.instructions, " recovery provided by", " ", /* @__PURE__ */ h("a", { href: m4.provider, target: "_blank", rel: "noreferrer" }, p6.business_name))
          );
        })),
        /* @__PURE__ */ h(
          "div",
          {
            style: {
              marginTop: "auto",
              marginBottom: "auto",
              display: "flex",
              justifyContent: "space-between",
              flexDirection: "column"
            }
          },
          /* @__PURE__ */ h(
            "button",
            {
              class: "button is-info block",
              onClick: () => setEditingPolicy(policy_index)
            },
            "Edit"
          ),
          /* @__PURE__ */ h(
            "button",
            {
              class: "button is-danger block",
              onClick: () => reducer.transition("delete_policy", { policy_index })
            },
            "Delete"
          )
        )
      );
    })
  );
}

// src/pages/home/SecretEditorScreen.tsx
init_preact_module();

// src/components/fields/FileInput.tsx
init_preact_module();
var MAX_IMAGE_UPLOAD_SIZE = 1024 * 1024;
function FileInput(props) {
  const inputRef = _2(null);
  s2(() => {
    if (props.grabFocus) {
      inputRef.current?.focus();
    }
  }, [props.grabFocus]);
  const fileInputRef = _2(null);
  const [sizeError, setSizeError] = p3(false);
  return /* @__PURE__ */ h("div", { class: "field" }, /* @__PURE__ */ h("label", { class: "label" }, /* @__PURE__ */ h("a", { class: "button", onClick: (e4) => fileInputRef.current?.click() }, /* @__PURE__ */ h("div", { class: "icon is-small " }, /* @__PURE__ */ h("i", { class: "mdi mdi-folder" })), /* @__PURE__ */ h("span", null, props.label)), props.tooltip && /* @__PURE__ */ h("span", { class: "icon has-tooltip-right", "data-tooltip": props.tooltip }, /* @__PURE__ */ h("i", { class: "mdi mdi-information" }))), /* @__PURE__ */ h("div", { class: "control" }, /* @__PURE__ */ h(
    "input",
    {
      ref: fileInputRef,
      style: { display: "none" },
      type: "file",
      onChange: (e4) => {
        const f4 = e4.currentTarget.files;
        if (!f4 || f4.length != 1) {
          return props.onChange(void 0);
        }
        if (f4[0].size > MAX_IMAGE_UPLOAD_SIZE) {
          setSizeError(true);
          return props.onChange(void 0);
        }
        setSizeError(false);
        return f4[0].arrayBuffer().then((b4) => {
          const b64 = btoa(
            new Uint8Array(b4).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ""
            )
          );
          return props.onChange({
            content: `data:${f4[0].type};base64,${b64}`,
            name: f4[0].name,
            type: f4[0].type
          });
        });
      }
    }
  ), props.error && /* @__PURE__ */ h("p", { class: "help is-danger" }, props.error), sizeError && /* @__PURE__ */ h("p", { class: "help is-danger" }, "File should be smaller than 1 MB")));
}

// src/pages/home/SecretEditorScreen.tsx
function SecretEditorScreen() {
  const reducer = useAnastasisContext();
  const [secretValue, setSecretValue] = p3("");
  const [secretFile, _setSecretFile] = p3(
    void 0
  );
  function setSecretFile(v4) {
    setSecretValue("");
    _setSecretFile(v4);
  }
  const currentSecretName = reducer?.currentReducerState && "secret_name" in reducer.currentReducerState && reducer.currentReducerState.secret_name;
  const [secretName, setSecretName] = p3(currentSecretName || "");
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (reducer.currentReducerState?.reducer_type !== "backup") {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  const secretNext = async () => {
    const secret = secretFile ? {
      value: encodeCrock(stringToBytes(secretFile.content)),
      filename: secretFile.name,
      mime: secretFile.type
    } : {
      value: encodeCrock(stringToBytes(secretValue)),
      mime: "text/plain"
    };
    return reducer.runTransaction(async (tx) => {
      await tx.transition("enter_secret_name", {
        name: secretName
      });
      await tx.transition("enter_secret", {
        secret,
        expiration: {
          t_s: (/* @__PURE__ */ new Date()).getTime() + 60 * 60 * 24 * 365 * 5
        }
      });
      await tx.transition("next", {});
    });
  };
  const errors2 = !secretName ? "Add a secret name" : !secretValue && !secretFile ? "Add a secret value or a choose a file to upload" : void 0;
  function goNextIfNoErrors() {
    if (!errors2)
      secretNext();
  }
  return /* @__PURE__ */ h(
    AnastasisClientFrame,
    {
      hideNext: errors2,
      title: "Backup: Provide secret to backup",
      onNext: () => secretNext()
    },
    /* @__PURE__ */ h("div", { class: "block" }, /* @__PURE__ */ h(
      TextInput,
      {
        label: "Secret name:",
        tooltip: "This allows you to uniquely identify a secret if you have made multiple back ups. The value entered here will NOT be protected by the authentication checks!",
        grabFocus: true,
        onConfirm: goNextIfNoErrors,
        bind: [secretName, setSecretName]
      }
    ), /* @__PURE__ */ h("div", null, "Names should be unique, so that you can easily identify your secret later.")),
    /* @__PURE__ */ h("div", { class: "block" }, /* @__PURE__ */ h(
      TextInput,
      {
        inputType: "multiline",
        disabled: !!secretFile,
        onConfirm: goNextIfNoErrors,
        label: "Enter the secret as text:",
        bind: [secretValue, setSecretValue]
      }
    )),
    /* @__PURE__ */ h("div", { class: "block" }, "Or upload a secret file", /* @__PURE__ */ h(FileInput, { label: "Choose file", onChange: setSecretFile }), secretFile && /* @__PURE__ */ h("div", null, "Uploading secret file ", /* @__PURE__ */ h("b", null, secretFile.name), " ", /* @__PURE__ */ h("a", { onClick: () => setSecretFile(void 0) }, "cancel")))
  );
}

// src/pages/home/SecretSelectionScreen.tsx
init_preact_module();
function SecretSelectionScreenFound({
  policies,
  onManageProvider,
  onNext
}) {
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (!reducer.currentReducerState || reducer.currentReducerState.reducer_type !== "recovery") {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  return /* @__PURE__ */ h(
    AnastasisClientFrame,
    {
      title: "Recovery: Select secret",
      hideNext: "Please select version to recover"
    },
    /* @__PURE__ */ h("div", { class: "columns" }, /* @__PURE__ */ h("div", { class: "column" }, /* @__PURE__ */ h("p", { class: "block" }, "Found versions:"), policies.map((version, i4) => /* @__PURE__ */ h("div", { key: i4, class: "box" }, /* @__PURE__ */ h(
      "div",
      {
        class: "block",
        style: { display: "flex", justifyContent: "space-between" }
      },
      /* @__PURE__ */ h(
        "div",
        {
          style: {
            display: "flex",
            flexDirection: "column"
          }
        },
        /* @__PURE__ */ h("div", { style: { display: "flex", alignItems: "center" } }, /* @__PURE__ */ h("b", null, "Name:"), "\xA0", /* @__PURE__ */ h("span", null, version.secret_name)),
        /* @__PURE__ */ h("div", { style: { display: "flex", alignItems: "center" } }, /* @__PURE__ */ h("b", null, "Id:"), "\xA0", /* @__PURE__ */ h(
          "span",
          {
            class: "icon has-tooltip-top",
            "data-tooltip": version.policy_hash
          },
          /* @__PURE__ */ h("i", { class: "mdi mdi-information" })
        ), /* @__PURE__ */ h("span", null, version.policy_hash.substring(0, 22), "..."))
      ),
      /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
        AsyncButton,
        {
          class: "button",
          onClick: async () => onNext(version)
        },
        "Recover"
      ))
    )))), /* @__PURE__ */ h("div", { class: "column" }, /* @__PURE__ */ h("p", null, "Secret found, you can select another version or continue to the challenges solving"), /* @__PURE__ */ h("p", { class: "block" }, /* @__PURE__ */ h("a", { onClick: onManageProvider }, "Manage recovery providers"))))
  );
}
function SecretSelectionScreen() {
  const reducer = useAnastasisContext();
  const [manageProvider, setManageProvider] = p3(false);
  h2(() => {
    async function f4() {
      if (reducer) {
        await reducer.discoverStart();
      }
    }
    f4().catch((e4) => console.log(e4));
  }, []);
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (!reducer.currentReducerState || reducer.currentReducerState.reducer_type !== "recovery") {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  if (manageProvider) {
    return /* @__PURE__ */ h(AddingProviderScreen_default, { onCancel: async () => setManageProvider(false) });
  }
  if (reducer.discoveryState.state === "none" || reducer.discoveryState.state === "active") {
    return /* @__PURE__ */ h(SecretSelectionScreenWaiting, null);
  }
  const policies = reducer.discoveryState.aggregatedPolicies ?? [];
  if (policies.length === 0) {
    return /* @__PURE__ */ h(
      AddingProviderScreen_default,
      {
        onCancel: async () => setManageProvider(false),
        notifications: [
          {
            message: "Secret not found",
            type: "ERROR",
            description: "With the information you provided we could not found secret in any of the providers. You can try adding more providers if you think the data is correct."
          }
        ]
      }
    );
  }
  return /* @__PURE__ */ h(
    SecretSelectionScreenFound,
    {
      policies,
      onNext: (version) => reducer.transition("select_version", version),
      onManageProvider: async () => setManageProvider(false)
    }
  );
}
function SecretSelectionScreenWaiting() {
  return /* @__PURE__ */ h(AnastasisClientFrame, { title: "Recovery: Select secret" }, /* @__PURE__ */ h("div", null, "loading secret versions"));
}

// src/pages/home/StartScreen.tsx
init_preact_module();

// src/components/FlieButton.tsx
init_preact_module();
var MAX_IMAGE_UPLOAD_SIZE2 = 1024 * 1024;
function FileButton(props) {
  const fileInputRef = _2(null);
  const [sizeError, setSizeError] = p3(false);
  return /* @__PURE__ */ h("div", null, /* @__PURE__ */ h("button", { class: "button", onClick: (e4) => fileInputRef.current?.click() }, /* @__PURE__ */ h("span", null, props.label)), /* @__PURE__ */ h(
    "input",
    {
      ref: fileInputRef,
      style: { display: "none" },
      type: "file",
      onChange: (e4) => {
        const f4 = e4.currentTarget.files;
        if (!f4 || f4.length != 1) {
          return props.onChange(void 0);
        }
        if (f4[0].size > MAX_IMAGE_UPLOAD_SIZE2) {
          setSizeError(true);
          return props.onChange(void 0);
        }
        setSizeError(false);
        return f4[0].arrayBuffer().then((b4) => {
          const content = new Uint8Array(b4).reduce(
            (data, byte) => data + String.fromCharCode(byte),
            ""
          );
          return props.onChange({
            content,
            name: f4[0].name,
            type: f4[0].type
          });
        });
      }
    }
  ), sizeError && /* @__PURE__ */ h("p", { class: "help is-danger" }, "File should be smaller than 1 MB"));
}

// src/pages/home/StartScreen.tsx
function StartScreen() {
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Home" }, /* @__PURE__ */ h("div", { class: "columns" }, /* @__PURE__ */ h("div", { class: "column" }), /* @__PURE__ */ h("div", { class: "column is-four-fifths" }, /* @__PURE__ */ h("div", { class: "buttons" }, /* @__PURE__ */ h(
    "button",
    {
      class: "button is-success",
      autoFocus: true,
      onClick: () => reducer.startBackup()
    },
    /* @__PURE__ */ h("div", { class: "icon" }, /* @__PURE__ */ h("i", { class: "mdi mdi-arrow-up" })),
    /* @__PURE__ */ h("span", null, "Backup a secret")
  ), /* @__PURE__ */ h(
    "button",
    {
      class: "button is-info",
      onClick: () => reducer.startRecover()
    },
    /* @__PURE__ */ h("div", { class: "icon" }, /* @__PURE__ */ h("i", { class: "mdi mdi-arrow-down" })),
    /* @__PURE__ */ h("span", null, "Recover a secret")
  ), /* @__PURE__ */ h(
    FileButton,
    {
      label: "Restore a session",
      onChange: (content) => {
        if (content?.type === "application/json") {
          reducer.importState(content.content);
        }
      }
    }
  ))), /* @__PURE__ */ h("div", { class: "column" })));
}

// src/pages/home/TruthsPayingScreen.tsx
init_preact_module();
function TruthsPayingScreen() {
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h("div", null, "no reducer in context");
  }
  if (reducer.currentReducerState?.reducer_type !== "backup") {
    return /* @__PURE__ */ h("div", null, "invalid state");
  }
  const payments = reducer.currentReducerState.payments ?? [];
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNext: "FIXME", title: "Backup: Truths Paying" }, /* @__PURE__ */ h("p", null, "Some of the providers require a payment to store the encrypted authentication information."), /* @__PURE__ */ h("ul", null, payments.map((x3, i4) => {
    return /* @__PURE__ */ h("li", { key: i4 }, x3);
  })), /* @__PURE__ */ h("button", { onClick: () => reducer.transition("pay", {}) }, "Check payment status now"));
}

// src/pages/home/index.tsx
function isBackup(reducer) {
  return reducer.currentReducerState?.reducer_type === "backup";
}
function withProcessLabel(reducer, text) {
  if (isBackup(reducer)) {
    return `Backup: ${text}`;
  }
  return `Recovery: ${text}`;
}
function ErrorBoundary(props) {
  const [error2, resetError] = P2(
    (error3) => console.log("ErrorBoundary got error", error3)
  );
  if (error2) {
    return /* @__PURE__ */ h("div", null, /* @__PURE__ */ h(
      "button",
      {
        onClick: () => {
          props.reducer.reset();
          resetError();
        }
      },
      "Reset"
    ), /* @__PURE__ */ h("p", null, "Error: ", /* @__PURE__ */ h("pre", null, error2.stack)));
  }
  return /* @__PURE__ */ h("div", null, props.children);
}
var currentHistoryId = 0;
function AnastasisClientFrame(props) {
  const reducer = useAnastasisContext();
  const doBack = async () => {
    if (props.onBack) {
      await props.onBack();
    } else {
      if (!reducer)
        return;
      await reducer.back();
    }
  };
  const doNext = async (fromPopstate) => {
    if (!fromPopstate) {
      try {
        const nextId = (history.state && typeof history.state.id === "number" ? history.state.id : 0) + 1;
        currentHistoryId = nextId;
        history.pushState({ id: nextId }, "unused", `#${nextId}`);
      } catch (e4) {
        console.log("ERROR doNext ", e4);
      }
    }
    if (props.onNext) {
      await props.onNext();
    } else {
      if (!reducer)
        return;
      await reducer.transition("next", {});
    }
  };
  const handleKeyPress = (e4) => {
  };
  const browserOnBackButton = T2(async (ev) => {
    if (!ev.state || ev.state.id === 0 || ev.state.id < currentHistoryId) {
      await doBack();
    } else {
      await doNext(true);
    }
    return false;
  }, []);
  h2(() => {
    window.addEventListener("popstate", browserOnBackButton);
    return () => {
      window.removeEventListener("popstate", browserOnBackButton);
    };
  }, []);
  return /* @__PURE__ */ h(p, null, /* @__PURE__ */ h("div", { class: "home", onKeyPress: (e4) => handleKeyPress(e4) }, /* @__PURE__ */ h("h1", { class: "title" }, props.title), /* @__PURE__ */ h(ErrorBanner, null), /* @__PURE__ */ h("section", { class: "section is-main-section" }, props.children, !props.hideNav ? /* @__PURE__ */ h(
    "div",
    {
      style: {
        marginTop: "2em",
        display: "flex",
        justifyContent: "space-between"
      }
    },
    /* @__PURE__ */ h("button", { class: "button", onClick: () => doBack() }, "Back"),
    /* @__PURE__ */ h(
      AsyncButton,
      {
        class: "button is-info",
        "data-tooltip": props.hideNext,
        onClick: () => doNext(),
        disabled: props.hideNext !== void 0
      },
      "Next"
    )
  ) : null)));
}
var AnastasisClient = () => {
  const reducer = useAnastasisReducer();
  return /* @__PURE__ */ h(AnastasisProvider, { value: reducer }, /* @__PURE__ */ h(ErrorBoundary, { reducer }, /* @__PURE__ */ h(Menu, { title: "Anastasis" }), /* @__PURE__ */ h(AnastasisClientImpl, null)));
};
function AnastasisClientImpl() {
  const reducer = useAnastasisContext();
  if (!reducer) {
    return /* @__PURE__ */ h("p", null, "Fatal: Reducer must be in context.");
  }
  const state = reducer.currentReducerState;
  if (!state) {
    return /* @__PURE__ */ h(StartScreen, null);
  }
  if (state.reducer_type === "backup" && state.backup_state === BackupStates.ContinentSelecting || state.reducer_type === "recovery" && state.recovery_state === RecoveryStates.ContinentSelecting || state.reducer_type === "backup" && state.backup_state === BackupStates.CountrySelecting || state.reducer_type === "recovery" && state.recovery_state === RecoveryStates.CountrySelecting) {
    return /* @__PURE__ */ h(ContinentSelectionScreen, null);
  }
  if (state.reducer_type === "backup" && state.backup_state === BackupStates.UserAttributesCollecting || state.reducer_type === "recovery" && state.recovery_state === RecoveryStates.UserAttributesCollecting) {
    return /* @__PURE__ */ h(AttributeEntryScreen, null);
  }
  if (state.reducer_type === "backup" && state.backup_state === BackupStates.AuthenticationsEditing) {
    return /* @__PURE__ */ h(AuthenticationEditorScreen, null);
  }
  if (state.reducer_type === "backup" && state.backup_state === BackupStates.PoliciesReviewing) {
    return /* @__PURE__ */ h(ReviewPoliciesScreen, null);
  }
  if (state.reducer_type === "backup" && state.backup_state === BackupStates.SecretEditing) {
    return /* @__PURE__ */ h(SecretEditorScreen, null);
  }
  if (state.reducer_type === "backup" && state.backup_state === BackupStates.BackupFinished) {
    return /* @__PURE__ */ h(BackupFinishedScreen, null);
  }
  if (state.reducer_type === "backup" && state.backup_state === BackupStates.TruthsPaying) {
    return /* @__PURE__ */ h(TruthsPayingScreen, null);
  }
  if (state.reducer_type === "backup" && state.backup_state === BackupStates.PoliciesPaying) {
    return /* @__PURE__ */ h(PoliciesPayingScreen, null);
  }
  if (state.reducer_type === "recovery" && state.recovery_state === RecoveryStates.SecretSelecting) {
    return /* @__PURE__ */ h(SecretSelectionScreen, null);
  }
  if (state.reducer_type === "recovery" && state.recovery_state === RecoveryStates.ChallengeSelecting) {
    return /* @__PURE__ */ h(ChallengeOverviewScreen, null);
  }
  if (state.reducer_type === "recovery" && state.recovery_state === RecoveryStates.ChallengeSolving) {
    return /* @__PURE__ */ h(SolveScreen, null);
  }
  if (state.reducer_type === "recovery" && state.recovery_state === RecoveryStates.RecoveryFinished) {
    return /* @__PURE__ */ h(RecoveryFinishedScreen, null);
  }
  if (state.reducer_type === "recovery" && state.recovery_state === RecoveryStates.ChallengePaying) {
    return /* @__PURE__ */ h(ChallengePayingScreen, null);
  }
  console.log("unknown state", reducer.currentReducerState);
  return /* @__PURE__ */ h(AnastasisClientFrame, { hideNav: true, title: "Bug" }, /* @__PURE__ */ h("p", null, "Bug: Unknown state."), /* @__PURE__ */ h("div", { class: "buttons is-right" }, /* @__PURE__ */ h("button", { class: "button", onClick: () => reducer.reset() }, "Reset")));
}
function ErrorBanner() {
  const reducer = useAnastasisContext();
  if (!reducer || !reducer.currentError)
    return null;
  return /* @__PURE__ */ h(
    Notifications,
    {
      removeNotification: reducer.dismissError,
      notifications: [
        {
          type: "ERROR",
          message: `Error code: ${reducer.currentError.code}`,
          description: reducer.currentError.hint
        }
      ]
    }
  );
}
var home_default = AnastasisClient;

// src/components/app.tsx
var App = () => {
  return /* @__PURE__ */ h(TranslationProvider, null, /* @__PURE__ */ h("div", { id: "app", class: "has-navbar-fixed-top" }, /* @__PURE__ */ h(home_default, null)));
};
var app_default = App;

// src/index.ts
function main() {
  try {
    const container = document.getElementById("container");
    if (!container) {
      throw new Error("container not found, can't mount page contents");
    }
    P(h(app_default, {}), container);
  } catch (e4) {
    console.error("got error", e4);
    if (e4 instanceof Error) {
      document.body.innerText = `Fatal error: "${e4.message}".  Please report this bug at https://bugs.gnunet.org/.`;
    }
  }
}
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", main);
} else {
  main();
}
/*! Bundled license information:

jed/jed.js:
  (**
   * @preserve jed.js https://github.com/SlexAxton/Jed
   *)

hash-wasm/dist/index.esm.js:
  (*!
   * hash-wasm (https://www.npmjs.com/package/hash-wasm)
   * (c) Dani Biro
   * @license MIT
   *)
*/
//# sourceMappingURL=index.js.map
