function makeMap(str, expectsLowerCase) {
  const map = /* @__PURE__ */ Object.create(null);
  const list = str.split(",");
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true;
  }
  return expectsLowerCase ? (val) => !!map[val.toLowerCase()] : (val) => !!map[val];
}
const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
const isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs);
function includeBooleanAttr(value) {
  return !!value || value === "";
}
function normalizeStyle(value) {
  if (isArray(value)) {
    const res = {};
    for (let i = 0; i < value.length; i++) {
      const item = value[i];
      const normalized = isString(item) ? parseStringStyle(item) : normalizeStyle(item);
      if (normalized) {
        for (const key in normalized) {
          res[key] = normalized[key];
        }
      }
    }
    return res;
  } else if (isString(value)) {
    return value;
  } else if (isObject(value)) {
    return value;
  }
}
const listDelimiterRE = /;(?![^(]*\))/g;
const propertyDelimiterRE = /:(.+)/;
function parseStringStyle(cssText) {
  const ret = {};
  cssText.split(listDelimiterRE).forEach((item) => {
    if (item) {
      const tmp = item.split(propertyDelimiterRE);
      tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
    }
  });
  return ret;
}
function normalizeClass(value) {
  let res = "";
  if (isString(value)) {
    res = value;
  } else if (isArray(value)) {
    for (let i = 0; i < value.length; i++) {
      const normalized = normalizeClass(value[i]);
      if (normalized) {
        res += normalized + " ";
      }
    }
  } else if (isObject(value)) {
    for (const name in value) {
      if (value[name]) {
        res += name + " ";
      }
    }
  }
  return res.trim();
}
const toDisplayString = (val) => {
  return isString(val) ? val : val == null ? "" : isArray(val) || isObject(val) && (val.toString === objectToString || !isFunction(val.toString)) ? JSON.stringify(val, replacer, 2) : String(val);
};
const replacer = (_key, val) => {
  if (val && val.__v_isRef) {
    return replacer(_key, val.value);
  } else if (isMap(val)) {
    return {
      [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val2]) => {
        entries[`${key} =>`] = val2;
        return entries;
      }, {})
    };
  } else if (isSet(val)) {
    return {
      [`Set(${val.size})`]: [...val.values()]
    };
  } else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
    return String(val);
  }
  return val;
};
const EMPTY_OBJ = {};
const EMPTY_ARR = [];
const NOOP = () => {
};
const NO = () => false;
const onRE = /^on[^a-z]/;
const isOn = (key) => onRE.test(key);
const isModelListener = (key) => key.startsWith("onUpdate:");
const extend = Object.assign;
const remove = (arr, el) => {
  const i = arr.indexOf(el);
  if (i > -1) {
    arr.splice(i, 1);
  }
};
const hasOwnProperty = Object.prototype.hasOwnProperty;
const hasOwn = (val, key) => hasOwnProperty.call(val, key);
const isArray = Array.isArray;
const isMap = (val) => toTypeString(val) === "[object Map]";
const isSet = (val) => toTypeString(val) === "[object Set]";
const isFunction = (val) => typeof val === "function";
const isString = (val) => typeof val === "string";
const isSymbol = (val) => typeof val === "symbol";
const isObject = (val) => val !== null && typeof val === "object";
const isPromise = (val) => {
  return isObject(val) && isFunction(val.then) && isFunction(val.catch);
};
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const toRawType = (value) => {
  return toTypeString(value).slice(8, -1);
};
const isPlainObject = (val) => toTypeString(val) === "[object Object]";
const isIntegerKey = (key) => isString(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key;
const isReservedProp = /* @__PURE__ */ makeMap(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted");
const cacheStringFunction = (fn) => {
  const cache = /* @__PURE__ */ Object.create(null);
  return (str) => {
    const hit = cache[str];
    return hit || (cache[str] = fn(str));
  };
};
const camelizeRE = /-(\w)/g;
const camelize = cacheStringFunction((str) => {
  return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : "");
});
const hyphenateRE = /\B([A-Z])/g;
const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase());
const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
const invokeArrayFns = (fns, arg) => {
  for (let i = 0; i < fns.length; i++) {
    fns[i](arg);
  }
};
const def = (obj, key, value) => {
  Object.defineProperty(obj, key, {
    configurable: true,
    enumerable: false,
    value
  });
};
const toNumber = (val) => {
  const n = parseFloat(val);
  return isNaN(n) ? val : n;
};
let _globalThis;
const getGlobalThis = () => {
  return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {});
};
let activeEffectScope;
class EffectScope {
  constructor(detached = false) {
    this.active = true;
    this.effects = [];
    this.cleanups = [];
    if (!detached && activeEffectScope) {
      this.parent = activeEffectScope;
      this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
    }
  }
  run(fn) {
    if (this.active) {
      const currentEffectScope = activeEffectScope;
      try {
        activeEffectScope = this;
        return fn();
      } finally {
        activeEffectScope = currentEffectScope;
      }
    }
  }
  on() {
    activeEffectScope = this;
  }
  off() {
    activeEffectScope = this.parent;
  }
  stop(fromParent) {
    if (this.active) {
      let i, l;
      for (i = 0, l = this.effects.length; i < l; i++) {
        this.effects[i].stop();
      }
      for (i = 0, l = this.cleanups.length; i < l; i++) {
        this.cleanups[i]();
      }
      if (this.scopes) {
        for (i = 0, l = this.scopes.length; i < l; i++) {
          this.scopes[i].stop(true);
        }
      }
      if (this.parent && !fromParent) {
        const last = this.parent.scopes.pop();
        if (last && last !== this) {
          this.parent.scopes[this.index] = last;
          last.index = this.index;
        }
      }
      this.active = false;
    }
  }
}
function recordEffectScope(effect, scope = activeEffectScope) {
  if (scope && scope.active) {
    scope.effects.push(effect);
  }
}
const createDep = (effects) => {
  const dep = new Set(effects);
  dep.w = 0;
  dep.n = 0;
  return dep;
};
const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
const newTracked = (dep) => (dep.n & trackOpBit) > 0;
const initDepMarkers = ({ deps }) => {
  if (deps.length) {
    for (let i = 0; i < deps.length; i++) {
      deps[i].w |= trackOpBit;
    }
  }
};
const finalizeDepMarkers = (effect) => {
  const { deps } = effect;
  if (deps.length) {
    let ptr = 0;
    for (let i = 0; i < deps.length; i++) {
      const dep = deps[i];
      if (wasTracked(dep) && !newTracked(dep)) {
        dep.delete(effect);
      } else {
        deps[ptr++] = dep;
      }
      dep.w &= ~trackOpBit;
      dep.n &= ~trackOpBit;
    }
    deps.length = ptr;
  }
};
const targetMap = /* @__PURE__ */ new WeakMap();
let effectTrackDepth = 0;
let trackOpBit = 1;
const maxMarkerBits = 30;
let activeEffect;
const ITERATE_KEY = Symbol("");
const MAP_KEY_ITERATE_KEY = Symbol("");
class ReactiveEffect {
  constructor(fn, scheduler = null, scope) {
    this.fn = fn;
    this.scheduler = scheduler;
    this.active = true;
    this.deps = [];
    this.parent = void 0;
    recordEffectScope(this, scope);
  }
  run() {
    if (!this.active) {
      return this.fn();
    }
    let parent = activeEffect;
    let lastShouldTrack = shouldTrack;
    while (parent) {
      if (parent === this) {
        return;
      }
      parent = parent.parent;
    }
    try {
      this.parent = activeEffect;
      activeEffect = this;
      shouldTrack = true;
      trackOpBit = 1 << ++effectTrackDepth;
      if (effectTrackDepth <= maxMarkerBits) {
        initDepMarkers(this);
      } else {
        cleanupEffect(this);
      }
      return this.fn();
    } finally {
      if (effectTrackDepth <= maxMarkerBits) {
        finalizeDepMarkers(this);
      }
      trackOpBit = 1 << --effectTrackDepth;
      activeEffect = this.parent;
      shouldTrack = lastShouldTrack;
      this.parent = void 0;
      if (this.deferStop) {
        this.stop();
      }
    }
  }
  stop() {
    if (activeEffect === this) {
      this.deferStop = true;
    } else if (this.active) {
      cleanupEffect(this);
      if (this.onStop) {
        this.onStop();
      }
      this.active = false;
    }
  }
}
function cleanupEffect(effect) {
  const { deps } = effect;
  if (deps.length) {
    for (let i = 0; i < deps.length; i++) {
      deps[i].delete(effect);
    }
    deps.length = 0;
  }
}
let shouldTrack = true;
const trackStack = [];
function pauseTracking() {
  trackStack.push(shouldTrack);
  shouldTrack = false;
}
function resetTracking() {
  const last = trackStack.pop();
  shouldTrack = last === void 0 ? true : last;
}
function track(target, type, key) {
  if (shouldTrack && activeEffect) {
    let depsMap = targetMap.get(target);
    if (!depsMap) {
      targetMap.set(target, depsMap = /* @__PURE__ */ new Map());
    }
    let dep = depsMap.get(key);
    if (!dep) {
      depsMap.set(key, dep = createDep());
    }
    trackEffects(dep);
  }
}
function trackEffects(dep, debuggerEventExtraInfo) {
  let shouldTrack2 = false;
  if (effectTrackDepth <= maxMarkerBits) {
    if (!newTracked(dep)) {
      dep.n |= trackOpBit;
      shouldTrack2 = !wasTracked(dep);
    }
  } else {
    shouldTrack2 = !dep.has(activeEffect);
  }
  if (shouldTrack2) {
    dep.add(activeEffect);
    activeEffect.deps.push(dep);
  }
}
function trigger(target, type, key, newValue, oldValue, oldTarget) {
  const depsMap = targetMap.get(target);
  if (!depsMap) {
    return;
  }
  let deps = [];
  if (type === "clear") {
    deps = [...depsMap.values()];
  } else if (key === "length" && isArray(target)) {
    depsMap.forEach((dep, key2) => {
      if (key2 === "length" || key2 >= newValue) {
        deps.push(dep);
      }
    });
  } else {
    if (key !== void 0) {
      deps.push(depsMap.get(key));
    }
    switch (type) {
      case "add":
        if (!isArray(target)) {
          deps.push(depsMap.get(ITERATE_KEY));
          if (isMap(target)) {
            deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
          }
        } else if (isIntegerKey(key)) {
          deps.push(depsMap.get("length"));
        }
        break;
      case "delete":
        if (!isArray(target)) {
          deps.push(depsMap.get(ITERATE_KEY));
          if (isMap(target)) {
            deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
          }
        }
        break;
      case "set":
        if (isMap(target)) {
          deps.push(depsMap.get(ITERATE_KEY));
        }
        break;
    }
  }
  if (deps.length === 1) {
    if (deps[0]) {
      {
        triggerEffects(deps[0]);
      }
    }
  } else {
    const effects = [];
    for (const dep of deps) {
      if (dep) {
        effects.push(...dep);
      }
    }
    {
      triggerEffects(createDep(effects));
    }
  }
}
function triggerEffects(dep, debuggerEventExtraInfo) {
  const effects = isArray(dep) ? dep : [...dep];
  for (const effect of effects) {
    if (effect.computed) {
      triggerEffect(effect);
    }
  }
  for (const effect of effects) {
    if (!effect.computed) {
      triggerEffect(effect);
    }
  }
}
function triggerEffect(effect, debuggerEventExtraInfo) {
  if (effect !== activeEffect || effect.allowRecurse) {
    if (effect.scheduler) {
      effect.scheduler();
    } else {
      effect.run();
    }
  }
}
const isNonTrackableKeys = /* @__PURE__ */ makeMap(`__proto__,__v_isRef,__isVue`);
const builtInSymbols = new Set(/* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol));
const get = /* @__PURE__ */ createGetter();
const shallowGet = /* @__PURE__ */ createGetter(false, true);
const readonlyGet = /* @__PURE__ */ createGetter(true);
const arrayInstrumentations = /* @__PURE__ */ createArrayInstrumentations();
function createArrayInstrumentations() {
  const instrumentations = {};
  ["includes", "indexOf", "lastIndexOf"].forEach((key) => {
    instrumentations[key] = function(...args) {
      const arr = toRaw(this);
      for (let i = 0, l = this.length; i < l; i++) {
        track(arr, "get", i + "");
      }
      const res = arr[key](...args);
      if (res === -1 || res === false) {
        return arr[key](...args.map(toRaw));
      } else {
        return res;
      }
    };
  });
  ["push", "pop", "shift", "unshift", "splice"].forEach((key) => {
    instrumentations[key] = function(...args) {
      pauseTracking();
      const res = toRaw(this)[key].apply(this, args);
      resetTracking();
      return res;
    };
  });
  return instrumentations;
}
function createGetter(isReadonly2 = false, shallow = false) {
  return function get2(target, key, receiver) {
    if (key === "__v_isReactive") {
      return !isReadonly2;
    } else if (key === "__v_isReadonly") {
      return isReadonly2;
    } else if (key === "__v_isShallow") {
      return shallow;
    } else if (key === "__v_raw" && receiver === (isReadonly2 ? shallow ? shallowReadonlyMap : readonlyMap : shallow ? shallowReactiveMap : reactiveMap).get(target)) {
      return target;
    }
    const targetIsArray = isArray(target);
    if (!isReadonly2 && targetIsArray && hasOwn(arrayInstrumentations, key)) {
      return Reflect.get(arrayInstrumentations, key, receiver);
    }
    const res = Reflect.get(target, key, receiver);
    if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
      return res;
    }
    if (!isReadonly2) {
      track(target, "get", key);
    }
    if (shallow) {
      return res;
    }
    if (isRef(res)) {
      return targetIsArray && isIntegerKey(key) ? res : res.value;
    }
    if (isObject(res)) {
      return isReadonly2 ? readonly(res) : reactive(res);
    }
    return res;
  };
}
const set = /* @__PURE__ */ createSetter();
const shallowSet = /* @__PURE__ */ createSetter(true);
function createSetter(shallow = false) {
  return function set2(target, key, value, receiver) {
    let oldValue = target[key];
    if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) {
      return false;
    }
    if (!shallow && !isReadonly(value)) {
      if (!isShallow(value)) {
        value = toRaw(value);
        oldValue = toRaw(oldValue);
      }
      if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
        oldValue.value = value;
        return true;
      }
    }
    const hadKey = isArray(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn(target, key);
    const result = Reflect.set(target, key, value, receiver);
    if (target === toRaw(receiver)) {
      if (!hadKey) {
        trigger(target, "add", key, value);
      } else if (hasChanged(value, oldValue)) {
        trigger(target, "set", key, value);
      }
    }
    return result;
  };
}
function deleteProperty(target, key) {
  const hadKey = hasOwn(target, key);
  target[key];
  const result = Reflect.deleteProperty(target, key);
  if (result && hadKey) {
    trigger(target, "delete", key, void 0);
  }
  return result;
}
function has(target, key) {
  const result = Reflect.has(target, key);
  if (!isSymbol(key) || !builtInSymbols.has(key)) {
    track(target, "has", key);
  }
  return result;
}
function ownKeys(target) {
  track(target, "iterate", isArray(target) ? "length" : ITERATE_KEY);
  return Reflect.ownKeys(target);
}
const mutableHandlers = {
  get,
  set,
  deleteProperty,
  has,
  ownKeys
};
const readonlyHandlers = {
  get: readonlyGet,
  set(target, key) {
    return true;
  },
  deleteProperty(target, key) {
    return true;
  }
};
const shallowReactiveHandlers = /* @__PURE__ */ extend({}, mutableHandlers, {
  get: shallowGet,
  set: shallowSet
});
const toShallow = (value) => value;
const getProto = (v) => Reflect.getPrototypeOf(v);
function get$1(target, key, isReadonly2 = false, isShallow2 = false) {
  target = target["__v_raw"];
  const rawTarget = toRaw(target);
  const rawKey = toRaw(key);
  if (!isReadonly2) {
    if (key !== rawKey) {
      track(rawTarget, "get", key);
    }
    track(rawTarget, "get", rawKey);
  }
  const { has: has2 } = getProto(rawTarget);
  const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive;
  if (has2.call(rawTarget, key)) {
    return wrap(target.get(key));
  } else if (has2.call(rawTarget, rawKey)) {
    return wrap(target.get(rawKey));
  } else if (target !== rawTarget) {
    target.get(key);
  }
}
function has$1(key, isReadonly2 = false) {
  const target = this["__v_raw"];
  const rawTarget = toRaw(target);
  const rawKey = toRaw(key);
  if (!isReadonly2) {
    if (key !== rawKey) {
      track(rawTarget, "has", key);
    }
    track(rawTarget, "has", rawKey);
  }
  return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey);
}
function size(target, isReadonly2 = false) {
  target = target["__v_raw"];
  !isReadonly2 && track(toRaw(target), "iterate", ITERATE_KEY);
  return Reflect.get(target, "size", target);
}
function add(value) {
  value = toRaw(value);
  const target = toRaw(this);
  const proto = getProto(target);
  const hadKey = proto.has.call(target, value);
  if (!hadKey) {
    target.add(value);
    trigger(target, "add", value, value);
  }
  return this;
}
function set$1(key, value) {
  value = toRaw(value);
  const target = toRaw(this);
  const { has: has2, get: get2 } = getProto(target);
  let hadKey = has2.call(target, key);
  if (!hadKey) {
    key = toRaw(key);
    hadKey = has2.call(target, key);
  }
  const oldValue = get2.call(target, key);
  target.set(key, value);
  if (!hadKey) {
    trigger(target, "add", key, value);
  } else if (hasChanged(value, oldValue)) {
    trigger(target, "set", key, value);
  }
  return this;
}
function deleteEntry(key) {
  const target = toRaw(this);
  const { has: has2, get: get2 } = getProto(target);
  let hadKey = has2.call(target, key);
  if (!hadKey) {
    key = toRaw(key);
    hadKey = has2.call(target, key);
  }
  get2 ? get2.call(target, key) : void 0;
  const result = target.delete(key);
  if (hadKey) {
    trigger(target, "delete", key, void 0);
  }
  return result;
}
function clear() {
  const target = toRaw(this);
  const hadItems = target.size !== 0;
  const result = target.clear();
  if (hadItems) {
    trigger(target, "clear", void 0, void 0);
  }
  return result;
}
function createForEach(isReadonly2, isShallow2) {
  return function forEach(callback, thisArg) {
    const observed = this;
    const target = observed["__v_raw"];
    const rawTarget = toRaw(target);
    const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive;
    !isReadonly2 && track(rawTarget, "iterate", ITERATE_KEY);
    return target.forEach((value, key) => {
      return callback.call(thisArg, wrap(value), wrap(key), observed);
    });
  };
}
function createIterableMethod(method, isReadonly2, isShallow2) {
  return function(...args) {
    const target = this["__v_raw"];
    const rawTarget = toRaw(target);
    const targetIsMap = isMap(rawTarget);
    const isPair = method === "entries" || method === Symbol.iterator && targetIsMap;
    const isKeyOnly = method === "keys" && targetIsMap;
    const innerIterator = target[method](...args);
    const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive;
    !isReadonly2 && track(rawTarget, "iterate", isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
    return {
      next() {
        const { value, done } = innerIterator.next();
        return done ? { value, done } : {
          value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
          done
        };
      },
      [Symbol.iterator]() {
        return this;
      }
    };
  };
}
function createReadonlyMethod(type) {
  return function(...args) {
    return type === "delete" ? false : this;
  };
}
function createInstrumentations() {
  const mutableInstrumentations2 = {
    get(key) {
      return get$1(this, key);
    },
    get size() {
      return size(this);
    },
    has: has$1,
    add,
    set: set$1,
    delete: deleteEntry,
    clear,
    forEach: createForEach(false, false)
  };
  const shallowInstrumentations2 = {
    get(key) {
      return get$1(this, key, false, true);
    },
    get size() {
      return size(this);
    },
    has: has$1,
    add,
    set: set$1,
    delete: deleteEntry,
    clear,
    forEach: createForEach(false, true)
  };
  const readonlyInstrumentations2 = {
    get(key) {
      return get$1(this, key, true);
    },
    get size() {
      return size(this, true);
    },
    has(key) {
      return has$1.call(this, key, true);
    },
    add: createReadonlyMethod("add"),
    set: createReadonlyMethod("set"),
    delete: createReadonlyMethod("delete"),
    clear: createReadonlyMethod("clear"),
    forEach: createForEach(true, false)
  };
  const shallowReadonlyInstrumentations2 = {
    get(key) {
      return get$1(this, key, true, true);
    },
    get size() {
      return size(this, true);
    },
    has(key) {
      return has$1.call(this, key, true);
    },
    add: createReadonlyMethod("add"),
    set: createReadonlyMethod("set"),
    delete: createReadonlyMethod("delete"),
    clear: createReadonlyMethod("clear"),
    forEach: createForEach(true, true)
  };
  const iteratorMethods = ["keys", "values", "entries", Symbol.iterator];
  iteratorMethods.forEach((method) => {
    mutableInstrumentations2[method] = createIterableMethod(method, false, false);
    readonlyInstrumentations2[method] = createIterableMethod(method, true, false);
    shallowInstrumentations2[method] = createIterableMethod(method, false, true);
    shallowReadonlyInstrumentations2[method] = createIterableMethod(method, true, true);
  });
  return [
    mutableInstrumentations2,
    readonlyInstrumentations2,
    shallowInstrumentations2,
    shallowReadonlyInstrumentations2
  ];
}
const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* @__PURE__ */ createInstrumentations();
function createInstrumentationGetter(isReadonly2, shallow) {
  const instrumentations = shallow ? isReadonly2 ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly2 ? readonlyInstrumentations : mutableInstrumentations;
  return (target, key, receiver) => {
    if (key === "__v_isReactive") {
      return !isReadonly2;
    } else if (key === "__v_isReadonly") {
      return isReadonly2;
    } else if (key === "__v_raw") {
      return target;
    }
    return Reflect.get(hasOwn(instrumentations, key) && key in target ? instrumentations : target, key, receiver);
  };
}
const mutableCollectionHandlers = {
  get: /* @__PURE__ */ createInstrumentationGetter(false, false)
};
const shallowCollectionHandlers = {
  get: /* @__PURE__ */ createInstrumentationGetter(false, true)
};
const readonlyCollectionHandlers = {
  get: /* @__PURE__ */ createInstrumentationGetter(true, false)
};
const reactiveMap = /* @__PURE__ */ new WeakMap();
const shallowReactiveMap = /* @__PURE__ */ new WeakMap();
const readonlyMap = /* @__PURE__ */ new WeakMap();
const shallowReadonlyMap = /* @__PURE__ */ new WeakMap();
function targetTypeMap(rawType) {
  switch (rawType) {
    case "Object":
    case "Array":
      return 1;
    case "Map":
    case "Set":
    case "WeakMap":
    case "WeakSet":
      return 2;
    default:
      return 0;
  }
}
function getTargetType(value) {
  return value["__v_skip"] || !Object.isExtensible(value) ? 0 : targetTypeMap(toRawType(value));
}
function reactive(target) {
  if (isReadonly(target)) {
    return target;
  }
  return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
}
function shallowReactive(target) {
  return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
}
function readonly(target) {
  return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
}
function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) {
  if (!isObject(target)) {
    return target;
  }
  if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) {
    return target;
  }
  const existingProxy = proxyMap.get(target);
  if (existingProxy) {
    return existingProxy;
  }
  const targetType = getTargetType(target);
  if (targetType === 0) {
    return target;
  }
  const proxy = new Proxy(target, targetType === 2 ? collectionHandlers : baseHandlers);
  proxyMap.set(target, proxy);
  return proxy;
}
function isReactive(value) {
  if (isReadonly(value)) {
    return isReactive(value["__v_raw"]);
  }
  return !!(value && value["__v_isReactive"]);
}
function isReadonly(value) {
  return !!(value && value["__v_isReadonly"]);
}
function isShallow(value) {
  return !!(value && value["__v_isShallow"]);
}
function isProxy(value) {
  return isReactive(value) || isReadonly(value);
}
function toRaw(observed) {
  const raw = observed && observed["__v_raw"];
  return raw ? toRaw(raw) : observed;
}
function markRaw(value) {
  def(value, "__v_skip", true);
  return value;
}
const toReactive = (value) => isObject(value) ? reactive(value) : value;
const toReadonly = (value) => isObject(value) ? readonly(value) : value;
function trackRefValue(ref2) {
  if (shouldTrack && activeEffect) {
    ref2 = toRaw(ref2);
    {
      trackEffects(ref2.dep || (ref2.dep = createDep()));
    }
  }
}
function triggerRefValue(ref2, newVal) {
  ref2 = toRaw(ref2);
  if (ref2.dep) {
    {
      triggerEffects(ref2.dep);
    }
  }
}
function isRef(r) {
  return !!(r && r.__v_isRef === true);
}
function ref(value) {
  return createRef(value, false);
}
function createRef(rawValue, shallow) {
  if (isRef(rawValue)) {
    return rawValue;
  }
  return new RefImpl(rawValue, shallow);
}
class RefImpl {
  constructor(value, __v_isShallow) {
    this.__v_isShallow = __v_isShallow;
    this.dep = void 0;
    this.__v_isRef = true;
    this._rawValue = __v_isShallow ? value : toRaw(value);
    this._value = __v_isShallow ? value : toReactive(value);
  }
  get value() {
    trackRefValue(this);
    return this._value;
  }
  set value(newVal) {
    newVal = this.__v_isShallow ? newVal : toRaw(newVal);
    if (hasChanged(newVal, this._rawValue)) {
      this._rawValue = newVal;
      this._value = this.__v_isShallow ? newVal : toReactive(newVal);
      triggerRefValue(this);
    }
  }
}
function unref(ref2) {
  return isRef(ref2) ? ref2.value : ref2;
}
const shallowUnwrapHandlers = {
  get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
  set: (target, key, value, receiver) => {
    const oldValue = target[key];
    if (isRef(oldValue) && !isRef(value)) {
      oldValue.value = value;
      return true;
    } else {
      return Reflect.set(target, key, value, receiver);
    }
  }
};
function proxyRefs(objectWithRefs) {
  return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers);
}
class ComputedRefImpl {
  constructor(getter, _setter, isReadonly2, isSSR) {
    this._setter = _setter;
    this.dep = void 0;
    this.__v_isRef = true;
    this._dirty = true;
    this.effect = new ReactiveEffect(getter, () => {
      if (!this._dirty) {
        this._dirty = true;
        triggerRefValue(this);
      }
    });
    this.effect.computed = this;
    this.effect.active = this._cacheable = !isSSR;
    this["__v_isReadonly"] = isReadonly2;
  }
  get value() {
    const self2 = toRaw(this);
    trackRefValue(self2);
    if (self2._dirty || !self2._cacheable) {
      self2._dirty = false;
      self2._value = self2.effect.run();
    }
    return self2._value;
  }
  set value(newValue) {
    this._setter(newValue);
  }
}
function computed$1(getterOrOptions, debugOptions, isSSR = false) {
  let getter;
  let setter;
  const onlyGetter = isFunction(getterOrOptions);
  if (onlyGetter) {
    getter = getterOrOptions;
    setter = NOOP;
  } else {
    getter = getterOrOptions.get;
    setter = getterOrOptions.set;
  }
  const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);
  return cRef;
}
function callWithErrorHandling(fn, instance, type, args) {
  let res;
  try {
    res = args ? fn(...args) : fn();
  } catch (err) {
    handleError(err, instance, type);
  }
  return res;
}
function callWithAsyncErrorHandling(fn, instance, type, args) {
  if (isFunction(fn)) {
    const res = callWithErrorHandling(fn, instance, type, args);
    if (res && isPromise(res)) {
      res.catch((err) => {
        handleError(err, instance, type);
      });
    }
    return res;
  }
  const values = [];
  for (let i = 0; i < fn.length; i++) {
    values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
  }
  return values;
}
function handleError(err, instance, type, throwInDev = true) {
  const contextVNode = instance ? instance.vnode : null;
  if (instance) {
    let cur = instance.parent;
    const exposedInstance = instance.proxy;
    const errorInfo = type;
    while (cur) {
      const errorCapturedHooks = cur.ec;
      if (errorCapturedHooks) {
        for (let i = 0; i < errorCapturedHooks.length; i++) {
          if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
            return;
          }
        }
      }
      cur = cur.parent;
    }
    const appErrorHandler = instance.appContext.config.errorHandler;
    if (appErrorHandler) {
      callWithErrorHandling(appErrorHandler, null, 10, [err, exposedInstance, errorInfo]);
      return;
    }
  }
  logError(err, type, contextVNode, throwInDev);
}
function logError(err, type, contextVNode, throwInDev = true) {
  {
    console.error(err);
  }
}
let isFlushing = false;
let isFlushPending = false;
const queue = [];
let flushIndex = 0;
const pendingPreFlushCbs = [];
let activePreFlushCbs = null;
let preFlushIndex = 0;
const pendingPostFlushCbs = [];
let activePostFlushCbs = null;
let postFlushIndex = 0;
const resolvedPromise = /* @__PURE__ */ Promise.resolve();
let currentFlushPromise = null;
let currentPreFlushParentJob = null;
function nextTick(fn) {
  const p2 = currentFlushPromise || resolvedPromise;
  return fn ? p2.then(this ? fn.bind(this) : fn) : p2;
}
function findInsertionIndex(id) {
  let start = flushIndex + 1;
  let end = queue.length;
  while (start < end) {
    const middle = start + end >>> 1;
    const middleJobId = getId(queue[middle]);
    middleJobId < id ? start = middle + 1 : end = middle;
  }
  return start;
}
function queueJob(job) {
  if ((!queue.length || !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) && job !== currentPreFlushParentJob) {
    if (job.id == null) {
      queue.push(job);
    } else {
      queue.splice(findInsertionIndex(job.id), 0, job);
    }
    queueFlush();
  }
}
function queueFlush() {
  if (!isFlushing && !isFlushPending) {
    isFlushPending = true;
    currentFlushPromise = resolvedPromise.then(flushJobs);
  }
}
function invalidateJob(job) {
  const i = queue.indexOf(job);
  if (i > flushIndex) {
    queue.splice(i, 1);
  }
}
function queueCb(cb, activeQueue, pendingQueue, index) {
  if (!isArray(cb)) {
    if (!activeQueue || !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
      pendingQueue.push(cb);
    }
  } else {
    pendingQueue.push(...cb);
  }
  queueFlush();
}
function queuePreFlushCb(cb) {
  queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
}
function queuePostFlushCb(cb) {
  queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
}
function flushPreFlushCbs(seen, parentJob = null) {
  if (pendingPreFlushCbs.length) {
    currentPreFlushParentJob = parentJob;
    activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
    pendingPreFlushCbs.length = 0;
    for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
      activePreFlushCbs[preFlushIndex]();
    }
    activePreFlushCbs = null;
    preFlushIndex = 0;
    currentPreFlushParentJob = null;
    flushPreFlushCbs(seen, parentJob);
  }
}
function flushPostFlushCbs(seen) {
  flushPreFlushCbs();
  if (pendingPostFlushCbs.length) {
    const deduped = [...new Set(pendingPostFlushCbs)];
    pendingPostFlushCbs.length = 0;
    if (activePostFlushCbs) {
      activePostFlushCbs.push(...deduped);
      return;
    }
    activePostFlushCbs = deduped;
    activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
    for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
      activePostFlushCbs[postFlushIndex]();
    }
    activePostFlushCbs = null;
    postFlushIndex = 0;
  }
}
const getId = (job) => job.id == null ? Infinity : job.id;
function flushJobs(seen) {
  isFlushPending = false;
  isFlushing = true;
  flushPreFlushCbs(seen);
  queue.sort((a, b) => getId(a) - getId(b));
  const check = NOOP;
  try {
    for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
      const job = queue[flushIndex];
      if (job && job.active !== false) {
        if (false)
          ;
        callWithErrorHandling(job, null, 14);
      }
    }
  } finally {
    flushIndex = 0;
    queue.length = 0;
    flushPostFlushCbs();
    isFlushing = false;
    currentFlushPromise = null;
    if (queue.length || pendingPreFlushCbs.length || pendingPostFlushCbs.length) {
      flushJobs(seen);
    }
  }
}
function emit$1(instance, event, ...rawArgs) {
  if (instance.isUnmounted)
    return;
  const props = instance.vnode.props || EMPTY_OBJ;
  let args = rawArgs;
  const isModelListener2 = event.startsWith("update:");
  const modelArg = isModelListener2 && event.slice(7);
  if (modelArg && modelArg in props) {
    const modifiersKey = `${modelArg === "modelValue" ? "model" : modelArg}Modifiers`;
    const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
    if (trim) {
      args = rawArgs.map((a) => a.trim());
    }
    if (number) {
      args = rawArgs.map(toNumber);
    }
  }
  let handlerName;
  let handler = props[handlerName = toHandlerKey(event)] || props[handlerName = toHandlerKey(camelize(event))];
  if (!handler && isModelListener2) {
    handler = props[handlerName = toHandlerKey(hyphenate(event))];
  }
  if (handler) {
    callWithAsyncErrorHandling(handler, instance, 6, args);
  }
  const onceHandler = props[handlerName + `Once`];
  if (onceHandler) {
    if (!instance.emitted) {
      instance.emitted = {};
    } else if (instance.emitted[handlerName]) {
      return;
    }
    instance.emitted[handlerName] = true;
    callWithAsyncErrorHandling(onceHandler, instance, 6, args);
  }
}
function normalizeEmitsOptions(comp, appContext, asMixin = false) {
  const cache = appContext.emitsCache;
  const cached = cache.get(comp);
  if (cached !== void 0) {
    return cached;
  }
  const raw = comp.emits;
  let normalized = {};
  let hasExtends = false;
  if (!isFunction(comp)) {
    const extendEmits = (raw2) => {
      const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true);
      if (normalizedFromExtend) {
        hasExtends = true;
        extend(normalized, normalizedFromExtend);
      }
    };
    if (!asMixin && appContext.mixins.length) {
      appContext.mixins.forEach(extendEmits);
    }
    if (comp.extends) {
      extendEmits(comp.extends);
    }
    if (comp.mixins) {
      comp.mixins.forEach(extendEmits);
    }
  }
  if (!raw && !hasExtends) {
    cache.set(comp, null);
    return null;
  }
  if (isArray(raw)) {
    raw.forEach((key) => normalized[key] = null);
  } else {
    extend(normalized, raw);
  }
  cache.set(comp, normalized);
  return normalized;
}
function isEmitListener(options, key) {
  if (!options || !isOn(key)) {
    return false;
  }
  key = key.slice(2).replace(/Once$/, "");
  return hasOwn(options, key[0].toLowerCase() + key.slice(1)) || hasOwn(options, hyphenate(key)) || hasOwn(options, key);
}
let currentRenderingInstance = null;
let currentScopeId = null;
function setCurrentRenderingInstance(instance) {
  const prev = currentRenderingInstance;
  currentRenderingInstance = instance;
  currentScopeId = instance && instance.type.__scopeId || null;
  return prev;
}
function pushScopeId(id) {
  currentScopeId = id;
}
function popScopeId() {
  currentScopeId = null;
}
function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) {
  if (!ctx)
    return fn;
  if (fn._n) {
    return fn;
  }
  const renderFnWithContext = (...args) => {
    if (renderFnWithContext._d) {
      setBlockTracking(-1);
    }
    const prevInstance = setCurrentRenderingInstance(ctx);
    const res = fn(...args);
    setCurrentRenderingInstance(prevInstance);
    if (renderFnWithContext._d) {
      setBlockTracking(1);
    }
    return res;
  };
  renderFnWithContext._n = true;
  renderFnWithContext._c = true;
  renderFnWithContext._d = true;
  return renderFnWithContext;
}
function markAttrsAccessed() {
}
function renderComponentRoot(instance) {
  const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
  let result;
  let fallthroughAttrs;
  const prev = setCurrentRenderingInstance(instance);
  try {
    if (vnode.shapeFlag & 4) {
      const proxyToUse = withProxy || proxy;
      result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
      fallthroughAttrs = attrs;
    } else {
      const render2 = Component;
      if (false)
        ;
      result = normalizeVNode(render2.length > 1 ? render2(props, false ? {
        get attrs() {
          markAttrsAccessed();
          return attrs;
        },
        slots,
        emit
      } : { attrs, slots, emit }) : render2(props, null));
      fallthroughAttrs = Component.props ? attrs : getFunctionalFallthrough(attrs);
    }
  } catch (err) {
    blockStack.length = 0;
    handleError(err, instance, 1);
    result = createVNode(Comment);
  }
  let root = result;
  if (fallthroughAttrs && inheritAttrs !== false) {
    const keys = Object.keys(fallthroughAttrs);
    const { shapeFlag } = root;
    if (keys.length) {
      if (shapeFlag & (1 | 6)) {
        if (propsOptions && keys.some(isModelListener)) {
          fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
        }
        root = cloneVNode(root, fallthroughAttrs);
      }
    }
  }
  if (vnode.dirs) {
    root = cloneVNode(root);
    root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
  }
  if (vnode.transition) {
    root.transition = vnode.transition;
  }
  {
    result = root;
  }
  setCurrentRenderingInstance(prev);
  return result;
}
const getFunctionalFallthrough = (attrs) => {
  let res;
  for (const key in attrs) {
    if (key === "class" || key === "style" || isOn(key)) {
      (res || (res = {}))[key] = attrs[key];
    }
  }
  return res;
};
const filterModelListeners = (attrs, props) => {
  const res = {};
  for (const key in attrs) {
    if (!isModelListener(key) || !(key.slice(9) in props)) {
      res[key] = attrs[key];
    }
  }
  return res;
};
function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
  const { props: prevProps, children: prevChildren, component } = prevVNode;
  const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
  const emits = component.emitsOptions;
  if (nextVNode.dirs || nextVNode.transition) {
    return true;
  }
  if (optimized && patchFlag >= 0) {
    if (patchFlag & 1024) {
      return true;
    }
    if (patchFlag & 16) {
      if (!prevProps) {
        return !!nextProps;
      }
      return hasPropsChanged(prevProps, nextProps, emits);
    } else if (patchFlag & 8) {
      const dynamicProps = nextVNode.dynamicProps;
      for (let i = 0; i < dynamicProps.length; i++) {
        const key = dynamicProps[i];
        if (nextProps[key] !== prevProps[key] && !isEmitListener(emits, key)) {
          return true;
        }
      }
    }
  } else {
    if (prevChildren || nextChildren) {
      if (!nextChildren || !nextChildren.$stable) {
        return true;
      }
    }
    if (prevProps === nextProps) {
      return false;
    }
    if (!prevProps) {
      return !!nextProps;
    }
    if (!nextProps) {
      return true;
    }
    return hasPropsChanged(prevProps, nextProps, emits);
  }
  return false;
}
function hasPropsChanged(prevProps, nextProps, emitsOptions) {
  const nextKeys = Object.keys(nextProps);
  if (nextKeys.length !== Object.keys(prevProps).length) {
    return true;
  }
  for (let i = 0; i < nextKeys.length; i++) {
    const key = nextKeys[i];
    if (nextProps[key] !== prevProps[key] && !isEmitListener(emitsOptions, key)) {
      return true;
    }
  }
  return false;
}
function updateHOCHostEl({ vnode, parent }, el) {
  while (parent && parent.subTree === vnode) {
    (vnode = parent.vnode).el = el;
    parent = parent.parent;
  }
}
const isSuspense = (type) => type.__isSuspense;
function queueEffectWithSuspense(fn, suspense) {
  if (suspense && suspense.pendingBranch) {
    if (isArray(fn)) {
      suspense.effects.push(...fn);
    } else {
      suspense.effects.push(fn);
    }
  } else {
    queuePostFlushCb(fn);
  }
}
function provide(key, value) {
  if (!currentInstance)
    ;
  else {
    let provides = currentInstance.provides;
    const parentProvides = currentInstance.parent && currentInstance.parent.provides;
    if (parentProvides === provides) {
      provides = currentInstance.provides = Object.create(parentProvides);
    }
    provides[key] = value;
  }
}
function inject(key, defaultValue, treatDefaultAsFactory = false) {
  const instance = currentInstance || currentRenderingInstance;
  if (instance) {
    const provides = instance.parent == null ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides;
    if (provides && key in provides) {
      return provides[key];
    } else if (arguments.length > 1) {
      return treatDefaultAsFactory && isFunction(defaultValue) ? defaultValue.call(instance.proxy) : defaultValue;
    } else
      ;
  }
}
const INITIAL_WATCHER_VALUE = {};
function watch(source, cb, options) {
  return doWatch(source, cb, options);
}
function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
  const instance = currentInstance;
  let getter;
  let forceTrigger = false;
  let isMultiSource = false;
  if (isRef(source)) {
    getter = () => source.value;
    forceTrigger = isShallow(source);
  } else if (isReactive(source)) {
    getter = () => source;
    deep = true;
  } else if (isArray(source)) {
    isMultiSource = true;
    forceTrigger = source.some((s) => isReactive(s) || isShallow(s));
    getter = () => source.map((s) => {
      if (isRef(s)) {
        return s.value;
      } else if (isReactive(s)) {
        return traverse(s);
      } else if (isFunction(s)) {
        return callWithErrorHandling(s, instance, 2);
      } else
        ;
    });
  } else if (isFunction(source)) {
    if (cb) {
      getter = () => callWithErrorHandling(source, instance, 2);
    } else {
      getter = () => {
        if (instance && instance.isUnmounted) {
          return;
        }
        if (cleanup) {
          cleanup();
        }
        return callWithAsyncErrorHandling(source, instance, 3, [onCleanup]);
      };
    }
  } else {
    getter = NOOP;
  }
  if (cb && deep) {
    const baseGetter = getter;
    getter = () => traverse(baseGetter());
  }
  let cleanup;
  let onCleanup = (fn) => {
    cleanup = effect.onStop = () => {
      callWithErrorHandling(fn, instance, 4);
    };
  };
  if (isInSSRComponentSetup) {
    onCleanup = NOOP;
    if (!cb) {
      getter();
    } else if (immediate) {
      callWithAsyncErrorHandling(cb, instance, 3, [
        getter(),
        isMultiSource ? [] : void 0,
        onCleanup
      ]);
    }
    return NOOP;
  }
  let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE;
  const job = () => {
    if (!effect.active) {
      return;
    }
    if (cb) {
      const newValue = effect.run();
      if (deep || forceTrigger || (isMultiSource ? newValue.some((v, i) => hasChanged(v, oldValue[i])) : hasChanged(newValue, oldValue)) || false) {
        if (cleanup) {
          cleanup();
        }
        callWithAsyncErrorHandling(cb, instance, 3, [
          newValue,
          oldValue === INITIAL_WATCHER_VALUE ? void 0 : oldValue,
          onCleanup
        ]);
        oldValue = newValue;
      }
    } else {
      effect.run();
    }
  };
  job.allowRecurse = !!cb;
  let scheduler;
  if (flush === "sync") {
    scheduler = job;
  } else if (flush === "post") {
    scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
  } else {
    scheduler = () => queuePreFlushCb(job);
  }
  const effect = new ReactiveEffect(getter, scheduler);
  if (cb) {
    if (immediate) {
      job();
    } else {
      oldValue = effect.run();
    }
  } else if (flush === "post") {
    queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
  } else {
    effect.run();
  }
  return () => {
    effect.stop();
    if (instance && instance.scope) {
      remove(instance.scope.effects, effect);
    }
  };
}
function instanceWatch(source, value, options) {
  const publicThis = this.proxy;
  const getter = isString(source) ? source.includes(".") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis);
  let cb;
  if (isFunction(value)) {
    cb = value;
  } else {
    cb = value.handler;
    options = value;
  }
  const cur = currentInstance;
  setCurrentInstance(this);
  const res = doWatch(getter, cb.bind(publicThis), options);
  if (cur) {
    setCurrentInstance(cur);
  } else {
    unsetCurrentInstance();
  }
  return res;
}
function createPathGetter(ctx, path) {
  const segments = path.split(".");
  return () => {
    let cur = ctx;
    for (let i = 0; i < segments.length && cur; i++) {
      cur = cur[segments[i]];
    }
    return cur;
  };
}
function traverse(value, seen) {
  if (!isObject(value) || value["__v_skip"]) {
    return value;
  }
  seen = seen || /* @__PURE__ */ new Set();
  if (seen.has(value)) {
    return value;
  }
  seen.add(value);
  if (isRef(value)) {
    traverse(value.value, seen);
  } else if (isArray(value)) {
    for (let i = 0; i < value.length; i++) {
      traverse(value[i], seen);
    }
  } else if (isSet(value) || isMap(value)) {
    value.forEach((v) => {
      traverse(v, seen);
    });
  } else if (isPlainObject(value)) {
    for (const key in value) {
      traverse(value[key], seen);
    }
  }
  return value;
}
function defineComponent(options) {
  return isFunction(options) ? { setup: options, name: options.name } : options;
}
const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
function onActivated(hook, target) {
  registerKeepAliveHook(hook, "a", target);
}
function onDeactivated(hook, target) {
  registerKeepAliveHook(hook, "da", target);
}
function registerKeepAliveHook(hook, type, target = currentInstance) {
  const wrappedHook = hook.__wdc || (hook.__wdc = () => {
    let current = target;
    while (current) {
      if (current.isDeactivated) {
        return;
      }
      current = current.parent;
    }
    return hook();
  });
  injectHook(type, wrappedHook, target);
  if (target) {
    let current = target.parent;
    while (current && current.parent) {
      if (isKeepAlive(current.parent.vnode)) {
        injectToKeepAliveRoot(wrappedHook, type, target, current);
      }
      current = current.parent;
    }
  }
}
function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
  const injected = injectHook(type, hook, keepAliveRoot, true);
  onUnmounted(() => {
    remove(keepAliveRoot[type], injected);
  }, target);
}
function injectHook(type, hook, target = currentInstance, prepend = false) {
  if (target) {
    const hooks = target[type] || (target[type] = []);
    const wrappedHook = hook.__weh || (hook.__weh = (...args) => {
      if (target.isUnmounted) {
        return;
      }
      pauseTracking();
      setCurrentInstance(target);
      const res = callWithAsyncErrorHandling(hook, target, type, args);
      unsetCurrentInstance();
      resetTracking();
      return res;
    });
    if (prepend) {
      hooks.unshift(wrappedHook);
    } else {
      hooks.push(wrappedHook);
    }
    return wrappedHook;
  }
}
const createHook = (lifecycle) => (hook, target = currentInstance) => (!isInSSRComponentSetup || lifecycle === "sp") && injectHook(lifecycle, hook, target);
const onBeforeMount = createHook("bm");
const onMounted = createHook("m");
const onBeforeUpdate = createHook("bu");
const onUpdated = createHook("u");
const onBeforeUnmount = createHook("bum");
const onUnmounted = createHook("um");
const onServerPrefetch = createHook("sp");
const onRenderTriggered = createHook("rtg");
const onRenderTracked = createHook("rtc");
function onErrorCaptured(hook, target = currentInstance) {
  injectHook("ec", hook, target);
}
function invokeDirectiveHook(vnode, prevVNode, instance, name) {
  const bindings = vnode.dirs;
  const oldBindings = prevVNode && prevVNode.dirs;
  for (let i = 0; i < bindings.length; i++) {
    const binding = bindings[i];
    if (oldBindings) {
      binding.oldValue = oldBindings[i].value;
    }
    let hook = binding.dir[name];
    if (hook) {
      pauseTracking();
      callWithAsyncErrorHandling(hook, instance, 8, [
        vnode.el,
        binding,
        vnode,
        prevVNode
      ]);
      resetTracking();
    }
  }
}
const NULL_DYNAMIC_COMPONENT = Symbol();
function renderList(source, renderItem, cache, index) {
  let ret;
  const cached = cache && cache[index];
  if (isArray(source) || isString(source)) {
    ret = new Array(source.length);
    for (let i = 0, l = source.length; i < l; i++) {
      ret[i] = renderItem(source[i], i, void 0, cached && cached[i]);
    }
  } else if (typeof source === "number") {
    ret = new Array(source);
    for (let i = 0; i < source; i++) {
      ret[i] = renderItem(i + 1, i, void 0, cached && cached[i]);
    }
  } else if (isObject(source)) {
    if (source[Symbol.iterator]) {
      ret = Array.from(source, (item, i) => renderItem(item, i, void 0, cached && cached[i]));
    } else {
      const keys = Object.keys(source);
      ret = new Array(keys.length);
      for (let i = 0, l = keys.length; i < l; i++) {
        const key = keys[i];
        ret[i] = renderItem(source[key], key, i, cached && cached[i]);
      }
    }
  } else {
    ret = [];
  }
  if (cache) {
    cache[index] = ret;
  }
  return ret;
}
const getPublicInstance = (i) => {
  if (!i)
    return null;
  if (isStatefulComponent(i))
    return getExposeProxy(i) || i.proxy;
  return getPublicInstance(i.parent);
};
const publicPropertiesMap = /* @__PURE__ */ extend(/* @__PURE__ */ Object.create(null), {
  $: (i) => i,
  $el: (i) => i.vnode.el,
  $data: (i) => i.data,
  $props: (i) => i.props,
  $attrs: (i) => i.attrs,
  $slots: (i) => i.slots,
  $refs: (i) => i.refs,
  $parent: (i) => getPublicInstance(i.parent),
  $root: (i) => getPublicInstance(i.root),
  $emit: (i) => i.emit,
  $options: (i) => resolveMergedOptions(i),
  $forceUpdate: (i) => i.f || (i.f = () => queueJob(i.update)),
  $nextTick: (i) => i.n || (i.n = nextTick.bind(i.proxy)),
  $watch: (i) => instanceWatch.bind(i)
});
const PublicInstanceProxyHandlers = {
  get({ _: instance }, key) {
    const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
    let normalizedProps;
    if (key[0] !== "$") {
      const n = accessCache[key];
      if (n !== void 0) {
        switch (n) {
          case 1:
            return setupState[key];
          case 2:
            return data[key];
          case 4:
            return ctx[key];
          case 3:
            return props[key];
        }
      } else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
        accessCache[key] = 1;
        return setupState[key];
      } else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
        accessCache[key] = 2;
        return data[key];
      } else if ((normalizedProps = instance.propsOptions[0]) && hasOwn(normalizedProps, key)) {
        accessCache[key] = 3;
        return props[key];
      } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
        accessCache[key] = 4;
        return ctx[key];
      } else if (shouldCacheAccess) {
        accessCache[key] = 0;
      }
    }
    const publicGetter = publicPropertiesMap[key];
    let cssModule, globalProperties;
    if (publicGetter) {
      if (key === "$attrs") {
        track(instance, "get", key);
      }
      return publicGetter(instance);
    } else if ((cssModule = type.__cssModules) && (cssModule = cssModule[key])) {
      return cssModule;
    } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
      accessCache[key] = 4;
      return ctx[key];
    } else if (globalProperties = appContext.config.globalProperties, hasOwn(globalProperties, key)) {
      {
        return globalProperties[key];
      }
    } else
      ;
  },
  set({ _: instance }, key, value) {
    const { data, setupState, ctx } = instance;
    if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
      setupState[key] = value;
      return true;
    } else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
      data[key] = value;
      return true;
    } else if (hasOwn(instance.props, key)) {
      return false;
    }
    if (key[0] === "$" && key.slice(1) in instance) {
      return false;
    } else {
      {
        ctx[key] = value;
      }
    }
    return true;
  },
  has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
    let normalizedProps;
    return !!accessCache[key] || data !== EMPTY_OBJ && hasOwn(data, key) || setupState !== EMPTY_OBJ && hasOwn(setupState, key) || (normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key) || hasOwn(ctx, key) || hasOwn(publicPropertiesMap, key) || hasOwn(appContext.config.globalProperties, key);
  },
  defineProperty(target, key, descriptor) {
    if (descriptor.get != null) {
      target._.accessCache[key] = 0;
    } else if (hasOwn(descriptor, "value")) {
      this.set(target, key, descriptor.value, null);
    }
    return Reflect.defineProperty(target, key, descriptor);
  }
};
let shouldCacheAccess = true;
function applyOptions(instance) {
  const options = resolveMergedOptions(instance);
  const publicThis = instance.proxy;
  const ctx = instance.ctx;
  shouldCacheAccess = false;
  if (options.beforeCreate) {
    callHook(options.beforeCreate, instance, "bc");
  }
  const {
    data: dataOptions,
    computed: computedOptions,
    methods,
    watch: watchOptions,
    provide: provideOptions,
    inject: injectOptions,
    created,
    beforeMount,
    mounted,
    beforeUpdate,
    updated,
    activated,
    deactivated,
    beforeDestroy,
    beforeUnmount,
    destroyed,
    unmounted,
    render,
    renderTracked,
    renderTriggered,
    errorCaptured,
    serverPrefetch,
    expose,
    inheritAttrs,
    components,
    directives,
    filters
  } = options;
  const checkDuplicateProperties = null;
  if (injectOptions) {
    resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
  }
  if (methods) {
    for (const key in methods) {
      const methodHandler = methods[key];
      if (isFunction(methodHandler)) {
        {
          ctx[key] = methodHandler.bind(publicThis);
        }
      }
    }
  }
  if (dataOptions) {
    const data = dataOptions.call(publicThis, publicThis);
    if (!isObject(data))
      ;
    else {
      instance.data = reactive(data);
    }
  }
  shouldCacheAccess = true;
  if (computedOptions) {
    for (const key in computedOptions) {
      const opt = computedOptions[key];
      const get2 = isFunction(opt) ? opt.bind(publicThis, publicThis) : isFunction(opt.get) ? opt.get.bind(publicThis, publicThis) : NOOP;
      const set2 = !isFunction(opt) && isFunction(opt.set) ? opt.set.bind(publicThis) : NOOP;
      const c = computed({
        get: get2,
        set: set2
      });
      Object.defineProperty(ctx, key, {
        enumerable: true,
        configurable: true,
        get: () => c.value,
        set: (v) => c.value = v
      });
    }
  }
  if (watchOptions) {
    for (const key in watchOptions) {
      createWatcher(watchOptions[key], ctx, publicThis, key);
    }
  }
  if (provideOptions) {
    const provides = isFunction(provideOptions) ? provideOptions.call(publicThis) : provideOptions;
    Reflect.ownKeys(provides).forEach((key) => {
      provide(key, provides[key]);
    });
  }
  if (created) {
    callHook(created, instance, "c");
  }
  function registerLifecycleHook(register, hook) {
    if (isArray(hook)) {
      hook.forEach((_hook) => register(_hook.bind(publicThis)));
    } else if (hook) {
      register(hook.bind(publicThis));
    }
  }
  registerLifecycleHook(onBeforeMount, beforeMount);
  registerLifecycleHook(onMounted, mounted);
  registerLifecycleHook(onBeforeUpdate, beforeUpdate);
  registerLifecycleHook(onUpdated, updated);
  registerLifecycleHook(onActivated, activated);
  registerLifecycleHook(onDeactivated, deactivated);
  registerLifecycleHook(onErrorCaptured, errorCaptured);
  registerLifecycleHook(onRenderTracked, renderTracked);
  registerLifecycleHook(onRenderTriggered, renderTriggered);
  registerLifecycleHook(onBeforeUnmount, beforeUnmount);
  registerLifecycleHook(onUnmounted, unmounted);
  registerLifecycleHook(onServerPrefetch, serverPrefetch);
  if (isArray(expose)) {
    if (expose.length) {
      const exposed = instance.exposed || (instance.exposed = {});
      expose.forEach((key) => {
        Object.defineProperty(exposed, key, {
          get: () => publicThis[key],
          set: (val) => publicThis[key] = val
        });
      });
    } else if (!instance.exposed) {
      instance.exposed = {};
    }
  }
  if (render && instance.render === NOOP) {
    instance.render = render;
  }
  if (inheritAttrs != null) {
    instance.inheritAttrs = inheritAttrs;
  }
  if (components)
    instance.components = components;
  if (directives)
    instance.directives = directives;
}
function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
  if (isArray(injectOptions)) {
    injectOptions = normalizeInject(injectOptions);
  }
  for (const key in injectOptions) {
    const opt = injectOptions[key];
    let injected;
    if (isObject(opt)) {
      if ("default" in opt) {
        injected = inject(opt.from || key, opt.default, true);
      } else {
        injected = inject(opt.from || key);
      }
    } else {
      injected = inject(opt);
    }
    if (isRef(injected)) {
      if (unwrapRef) {
        Object.defineProperty(ctx, key, {
          enumerable: true,
          configurable: true,
          get: () => injected.value,
          set: (v) => injected.value = v
        });
      } else {
        ctx[key] = injected;
      }
    } else {
      ctx[key] = injected;
    }
  }
}
function callHook(hook, instance, type) {
  callWithAsyncErrorHandling(isArray(hook) ? hook.map((h) => h.bind(instance.proxy)) : hook.bind(instance.proxy), instance, type);
}
function createWatcher(raw, ctx, publicThis, key) {
  const getter = key.includes(".") ? createPathGetter(publicThis, key) : () => publicThis[key];
  if (isString(raw)) {
    const handler = ctx[raw];
    if (isFunction(handler)) {
      watch(getter, handler);
    }
  } else if (isFunction(raw)) {
    watch(getter, raw.bind(publicThis));
  } else if (isObject(raw)) {
    if (isArray(raw)) {
      raw.forEach((r) => createWatcher(r, ctx, publicThis, key));
    } else {
      const handler = isFunction(raw.handler) ? raw.handler.bind(publicThis) : ctx[raw.handler];
      if (isFunction(handler)) {
        watch(getter, handler, raw);
      }
    }
  } else
    ;
}
function resolveMergedOptions(instance) {
  const base2 = instance.type;
  const { mixins, extends: extendsOptions } = base2;
  const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
  const cached = cache.get(base2);
  let resolved;
  if (cached) {
    resolved = cached;
  } else if (!globalMixins.length && !mixins && !extendsOptions) {
    {
      resolved = base2;
    }
  } else {
    resolved = {};
    if (globalMixins.length) {
      globalMixins.forEach((m) => mergeOptions(resolved, m, optionMergeStrategies, true));
    }
    mergeOptions(resolved, base2, optionMergeStrategies);
  }
  cache.set(base2, resolved);
  return resolved;
}
function mergeOptions(to, from, strats, asMixin = false) {
  const { mixins, extends: extendsOptions } = from;
  if (extendsOptions) {
    mergeOptions(to, extendsOptions, strats, true);
  }
  if (mixins) {
    mixins.forEach((m) => mergeOptions(to, m, strats, true));
  }
  for (const key in from) {
    if (asMixin && key === "expose")
      ;
    else {
      const strat = internalOptionMergeStrats[key] || strats && strats[key];
      to[key] = strat ? strat(to[key], from[key]) : from[key];
    }
  }
  return to;
}
const internalOptionMergeStrats = {
  data: mergeDataFn,
  props: mergeObjectOptions,
  emits: mergeObjectOptions,
  methods: mergeObjectOptions,
  computed: mergeObjectOptions,
  beforeCreate: mergeAsArray,
  created: mergeAsArray,
  beforeMount: mergeAsArray,
  mounted: mergeAsArray,
  beforeUpdate: mergeAsArray,
  updated: mergeAsArray,
  beforeDestroy: mergeAsArray,
  beforeUnmount: mergeAsArray,
  destroyed: mergeAsArray,
  unmounted: mergeAsArray,
  activated: mergeAsArray,
  deactivated: mergeAsArray,
  errorCaptured: mergeAsArray,
  serverPrefetch: mergeAsArray,
  components: mergeObjectOptions,
  directives: mergeObjectOptions,
  watch: mergeWatchOptions,
  provide: mergeDataFn,
  inject: mergeInject
};
function mergeDataFn(to, from) {
  if (!from) {
    return to;
  }
  if (!to) {
    return from;
  }
  return function mergedDataFn() {
    return extend(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
  };
}
function mergeInject(to, from) {
  return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
}
function normalizeInject(raw) {
  if (isArray(raw)) {
    const res = {};
    for (let i = 0; i < raw.length; i++) {
      res[raw[i]] = raw[i];
    }
    return res;
  }
  return raw;
}
function mergeAsArray(to, from) {
  return to ? [...new Set([].concat(to, from))] : from;
}
function mergeObjectOptions(to, from) {
  return to ? extend(extend(/* @__PURE__ */ Object.create(null), to), from) : from;
}
function mergeWatchOptions(to, from) {
  if (!to)
    return from;
  if (!from)
    return to;
  const merged = extend(/* @__PURE__ */ Object.create(null), to);
  for (const key in from) {
    merged[key] = mergeAsArray(to[key], from[key]);
  }
  return merged;
}
function initProps(instance, rawProps, isStateful, isSSR = false) {
  const props = {};
  const attrs = {};
  def(attrs, InternalObjectKey, 1);
  instance.propsDefaults = /* @__PURE__ */ Object.create(null);
  setFullProps(instance, rawProps, props, attrs);
  for (const key in instance.propsOptions[0]) {
    if (!(key in props)) {
      props[key] = void 0;
    }
  }
  if (isStateful) {
    instance.props = isSSR ? props : shallowReactive(props);
  } else {
    if (!instance.type.props) {
      instance.props = attrs;
    } else {
      instance.props = props;
    }
  }
  instance.attrs = attrs;
}
function updateProps(instance, rawProps, rawPrevProps, optimized) {
  const { props, attrs, vnode: { patchFlag } } = instance;
  const rawCurrentProps = toRaw(props);
  const [options] = instance.propsOptions;
  let hasAttrsChanged = false;
  if ((optimized || patchFlag > 0) && !(patchFlag & 16)) {
    if (patchFlag & 8) {
      const propsToUpdate = instance.vnode.dynamicProps;
      for (let i = 0; i < propsToUpdate.length; i++) {
        let key = propsToUpdate[i];
        if (isEmitListener(instance.emitsOptions, key)) {
          continue;
        }
        const value = rawProps[key];
        if (options) {
          if (hasOwn(attrs, key)) {
            if (value !== attrs[key]) {
              attrs[key] = value;
              hasAttrsChanged = true;
            }
          } else {
            const camelizedKey = camelize(key);
            props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false);
          }
        } else {
          if (value !== attrs[key]) {
            attrs[key] = value;
            hasAttrsChanged = true;
          }
        }
      }
    }
  } else {
    if (setFullProps(instance, rawProps, props, attrs)) {
      hasAttrsChanged = true;
    }
    let kebabKey;
    for (const key in rawCurrentProps) {
      if (!rawProps || !hasOwn(rawProps, key) && ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey))) {
        if (options) {
          if (rawPrevProps && (rawPrevProps[key] !== void 0 || rawPrevProps[kebabKey] !== void 0)) {
            props[key] = resolvePropValue(options, rawCurrentProps, key, void 0, instance, true);
          }
        } else {
          delete props[key];
        }
      }
    }
    if (attrs !== rawCurrentProps) {
      for (const key in attrs) {
        if (!rawProps || !hasOwn(rawProps, key) && true) {
          delete attrs[key];
          hasAttrsChanged = true;
        }
      }
    }
  }
  if (hasAttrsChanged) {
    trigger(instance, "set", "$attrs");
  }
}
function setFullProps(instance, rawProps, props, attrs) {
  const [options, needCastKeys] = instance.propsOptions;
  let hasAttrsChanged = false;
  let rawCastValues;
  if (rawProps) {
    for (let key in rawProps) {
      if (isReservedProp(key)) {
        continue;
      }
      const value = rawProps[key];
      let camelKey;
      if (options && hasOwn(options, camelKey = camelize(key))) {
        if (!needCastKeys || !needCastKeys.includes(camelKey)) {
          props[camelKey] = value;
        } else {
          (rawCastValues || (rawCastValues = {}))[camelKey] = value;
        }
      } else if (!isEmitListener(instance.emitsOptions, key)) {
        if (!(key in attrs) || value !== attrs[key]) {
          attrs[key] = value;
          hasAttrsChanged = true;
        }
      }
    }
  }
  if (needCastKeys) {
    const rawCurrentProps = toRaw(props);
    const castValues = rawCastValues || EMPTY_OBJ;
    for (let i = 0; i < needCastKeys.length; i++) {
      const key = needCastKeys[i];
      props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
    }
  }
  return hasAttrsChanged;
}
function resolvePropValue(options, props, key, value, instance, isAbsent) {
  const opt = options[key];
  if (opt != null) {
    const hasDefault = hasOwn(opt, "default");
    if (hasDefault && value === void 0) {
      const defaultValue = opt.default;
      if (opt.type !== Function && isFunction(defaultValue)) {
        const { propsDefaults } = instance;
        if (key in propsDefaults) {
          value = propsDefaults[key];
        } else {
          setCurrentInstance(instance);
          value = propsDefaults[key] = defaultValue.call(null, props);
          unsetCurrentInstance();
        }
      } else {
        value = defaultValue;
      }
    }
    if (opt[0]) {
      if (isAbsent && !hasDefault) {
        value = false;
      } else if (opt[1] && (value === "" || value === hyphenate(key))) {
        value = true;
      }
    }
  }
  return value;
}
function normalizePropsOptions(comp, appContext, asMixin = false) {
  const cache = appContext.propsCache;
  const cached = cache.get(comp);
  if (cached) {
    return cached;
  }
  const raw = comp.props;
  const normalized = {};
  const needCastKeys = [];
  let hasExtends = false;
  if (!isFunction(comp)) {
    const extendProps = (raw2) => {
      hasExtends = true;
      const [props, keys] = normalizePropsOptions(raw2, appContext, true);
      extend(normalized, props);
      if (keys)
        needCastKeys.push(...keys);
    };
    if (!asMixin && appContext.mixins.length) {
      appContext.mixins.forEach(extendProps);
    }
    if (comp.extends) {
      extendProps(comp.extends);
    }
    if (comp.mixins) {
      comp.mixins.forEach(extendProps);
    }
  }
  if (!raw && !hasExtends) {
    cache.set(comp, EMPTY_ARR);
    return EMPTY_ARR;
  }
  if (isArray(raw)) {
    for (let i = 0; i < raw.length; i++) {
      const normalizedKey = camelize(raw[i]);
      if (validatePropName(normalizedKey)) {
        normalized[normalizedKey] = EMPTY_OBJ;
      }
    }
  } else if (raw) {
    for (const key in raw) {
      const normalizedKey = camelize(key);
      if (validatePropName(normalizedKey)) {
        const opt = raw[key];
        const prop = normalized[normalizedKey] = isArray(opt) || isFunction(opt) ? { type: opt } : opt;
        if (prop) {
          const booleanIndex = getTypeIndex(Boolean, prop.type);
          const stringIndex = getTypeIndex(String, prop.type);
          prop[0] = booleanIndex > -1;
          prop[1] = stringIndex < 0 || booleanIndex < stringIndex;
          if (booleanIndex > -1 || hasOwn(prop, "default")) {
            needCastKeys.push(normalizedKey);
          }
        }
      }
    }
  }
  const res = [normalized, needCastKeys];
  cache.set(comp, res);
  return res;
}
function validatePropName(key) {
  if (key[0] !== "$") {
    return true;
  }
  return false;
}
function getType(ctor) {
  const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
  return match ? match[1] : ctor === null ? "null" : "";
}
function isSameType(a, b) {
  return getType(a) === getType(b);
}
function getTypeIndex(type, expectedTypes) {
  if (isArray(expectedTypes)) {
    return expectedTypes.findIndex((t) => isSameType(t, type));
  } else if (isFunction(expectedTypes)) {
    return isSameType(expectedTypes, type) ? 0 : -1;
  }
  return -1;
}
const isInternalKey = (key) => key[0] === "_" || key === "$stable";
const normalizeSlotValue = (value) => isArray(value) ? value.map(normalizeVNode) : [normalizeVNode(value)];
const normalizeSlot = (key, rawSlot, ctx) => {
  if (rawSlot._n) {
    return rawSlot;
  }
  const normalized = withCtx((...args) => {
    return normalizeSlotValue(rawSlot(...args));
  }, ctx);
  normalized._c = false;
  return normalized;
};
const normalizeObjectSlots = (rawSlots, slots, instance) => {
  const ctx = rawSlots._ctx;
  for (const key in rawSlots) {
    if (isInternalKey(key))
      continue;
    const value = rawSlots[key];
    if (isFunction(value)) {
      slots[key] = normalizeSlot(key, value, ctx);
    } else if (value != null) {
      const normalized = normalizeSlotValue(value);
      slots[key] = () => normalized;
    }
  }
};
const normalizeVNodeSlots = (instance, children) => {
  const normalized = normalizeSlotValue(children);
  instance.slots.default = () => normalized;
};
const initSlots = (instance, children) => {
  if (instance.vnode.shapeFlag & 32) {
    const type = children._;
    if (type) {
      instance.slots = toRaw(children);
      def(children, "_", type);
    } else {
      normalizeObjectSlots(children, instance.slots = {});
    }
  } else {
    instance.slots = {};
    if (children) {
      normalizeVNodeSlots(instance, children);
    }
  }
  def(instance.slots, InternalObjectKey, 1);
};
const updateSlots = (instance, children, optimized) => {
  const { vnode, slots } = instance;
  let needDeletionCheck = true;
  let deletionComparisonTarget = EMPTY_OBJ;
  if (vnode.shapeFlag & 32) {
    const type = children._;
    if (type) {
      if (optimized && type === 1) {
        needDeletionCheck = false;
      } else {
        extend(slots, children);
        if (!optimized && type === 1) {
          delete slots._;
        }
      }
    } else {
      needDeletionCheck = !children.$stable;
      normalizeObjectSlots(children, slots);
    }
    deletionComparisonTarget = children;
  } else if (children) {
    normalizeVNodeSlots(instance, children);
    deletionComparisonTarget = { default: 1 };
  }
  if (needDeletionCheck) {
    for (const key in slots) {
      if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
        delete slots[key];
      }
    }
  }
};
function createAppContext() {
  return {
    app: null,
    config: {
      isNativeTag: NO,
      performance: false,
      globalProperties: {},
      optionMergeStrategies: {},
      errorHandler: void 0,
      warnHandler: void 0,
      compilerOptions: {}
    },
    mixins: [],
    components: {},
    directives: {},
    provides: /* @__PURE__ */ Object.create(null),
    optionsCache: /* @__PURE__ */ new WeakMap(),
    propsCache: /* @__PURE__ */ new WeakMap(),
    emitsCache: /* @__PURE__ */ new WeakMap()
  };
}
let uid = 0;
function createAppAPI(render, hydrate) {
  return function createApp2(rootComponent, rootProps = null) {
    if (!isFunction(rootComponent)) {
      rootComponent = Object.assign({}, rootComponent);
    }
    if (rootProps != null && !isObject(rootProps)) {
      rootProps = null;
    }
    const context = createAppContext();
    const installedPlugins = /* @__PURE__ */ new Set();
    let isMounted = false;
    const app = context.app = {
      _uid: uid++,
      _component: rootComponent,
      _props: rootProps,
      _container: null,
      _context: context,
      _instance: null,
      version,
      get config() {
        return context.config;
      },
      set config(v) {
      },
      use(plugin, ...options) {
        if (installedPlugins.has(plugin))
          ;
        else if (plugin && isFunction(plugin.install)) {
          installedPlugins.add(plugin);
          plugin.install(app, ...options);
        } else if (isFunction(plugin)) {
          installedPlugins.add(plugin);
          plugin(app, ...options);
        } else
          ;
        return app;
      },
      mixin(mixin) {
        {
          if (!context.mixins.includes(mixin)) {
            context.mixins.push(mixin);
          }
        }
        return app;
      },
      component(name, component) {
        if (!component) {
          return context.components[name];
        }
        context.components[name] = component;
        return app;
      },
      directive(name, directive) {
        if (!directive) {
          return context.directives[name];
        }
        context.directives[name] = directive;
        return app;
      },
      mount(rootContainer, isHydrate, isSVG) {
        if (!isMounted) {
          const vnode = createVNode(rootComponent, rootProps);
          vnode.appContext = context;
          if (isHydrate && hydrate) {
            hydrate(vnode, rootContainer);
          } else {
            render(vnode, rootContainer, isSVG);
          }
          isMounted = true;
          app._container = rootContainer;
          rootContainer.__vue_app__ = app;
          return getExposeProxy(vnode.component) || vnode.component.proxy;
        }
      },
      unmount() {
        if (isMounted) {
          render(null, app._container);
          delete app._container.__vue_app__;
        }
      },
      provide(key, value) {
        context.provides[key] = value;
        return app;
      }
    };
    return app;
  };
}
function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
  if (isArray(rawRef)) {
    rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
    return;
  }
  if (isAsyncWrapper(vnode) && !isUnmount) {
    return;
  }
  const refValue = vnode.shapeFlag & 4 ? getExposeProxy(vnode.component) || vnode.component.proxy : vnode.el;
  const value = isUnmount ? null : refValue;
  const { i: owner, r: ref2 } = rawRef;
  const oldRef = oldRawRef && oldRawRef.r;
  const refs = owner.refs === EMPTY_OBJ ? owner.refs = {} : owner.refs;
  const setupState = owner.setupState;
  if (oldRef != null && oldRef !== ref2) {
    if (isString(oldRef)) {
      refs[oldRef] = null;
      if (hasOwn(setupState, oldRef)) {
        setupState[oldRef] = null;
      }
    } else if (isRef(oldRef)) {
      oldRef.value = null;
    }
  }
  if (isFunction(ref2)) {
    callWithErrorHandling(ref2, owner, 12, [value, refs]);
  } else {
    const _isString = isString(ref2);
    const _isRef = isRef(ref2);
    if (_isString || _isRef) {
      const doSet = () => {
        if (rawRef.f) {
          const existing = _isString ? refs[ref2] : ref2.value;
          if (isUnmount) {
            isArray(existing) && remove(existing, refValue);
          } else {
            if (!isArray(existing)) {
              if (_isString) {
                refs[ref2] = [refValue];
                if (hasOwn(setupState, ref2)) {
                  setupState[ref2] = refs[ref2];
                }
              } else {
                ref2.value = [refValue];
                if (rawRef.k)
                  refs[rawRef.k] = ref2.value;
              }
            } else if (!existing.includes(refValue)) {
              existing.push(refValue);
            }
          }
        } else if (_isString) {
          refs[ref2] = value;
          if (hasOwn(setupState, ref2)) {
            setupState[ref2] = value;
          }
        } else if (_isRef) {
          ref2.value = value;
          if (rawRef.k)
            refs[rawRef.k] = value;
        } else
          ;
      };
      if (value) {
        doSet.id = -1;
        queuePostRenderEffect(doSet, parentSuspense);
      } else {
        doSet();
      }
    }
  }
}
const queuePostRenderEffect = queueEffectWithSuspense;
function createRenderer(options) {
  return baseCreateRenderer(options);
}
function baseCreateRenderer(options, createHydrationFns) {
  const target = getGlobalThis();
  target.__VUE__ = true;
  const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options;
  const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = !!n2.dynamicChildren) => {
    if (n1 === n2) {
      return;
    }
    if (n1 && !isSameVNodeType(n1, n2)) {
      anchor = getNextHostNode(n1);
      unmount(n1, parentComponent, parentSuspense, true);
      n1 = null;
    }
    if (n2.patchFlag === -2) {
      optimized = false;
      n2.dynamicChildren = null;
    }
    const { type, ref: ref2, shapeFlag } = n2;
    switch (type) {
      case Text$1:
        processText(n1, n2, container, anchor);
        break;
      case Comment:
        processCommentNode(n1, n2, container, anchor);
        break;
      case Static:
        if (n1 == null) {
          mountStaticNode(n2, container, anchor, isSVG);
        }
        break;
      case Fragment:
        processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
        break;
      default:
        if (shapeFlag & 1) {
          processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
        } else if (shapeFlag & 6) {
          processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
        } else if (shapeFlag & 64) {
          type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
        } else if (shapeFlag & 128) {
          type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
        } else
          ;
    }
    if (ref2 != null && parentComponent) {
      setRef(ref2, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
    }
  };
  const processText = (n1, n2, container, anchor) => {
    if (n1 == null) {
      hostInsert(n2.el = hostCreateText(n2.children), container, anchor);
    } else {
      const el = n2.el = n1.el;
      if (n2.children !== n1.children) {
        hostSetText(el, n2.children);
      }
    }
  };
  const processCommentNode = (n1, n2, container, anchor) => {
    if (n1 == null) {
      hostInsert(n2.el = hostCreateComment(n2.children || ""), container, anchor);
    } else {
      n2.el = n1.el;
    }
  };
  const mountStaticNode = (n2, container, anchor, isSVG) => {
    [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG, n2.el, n2.anchor);
  };
  const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
    let next;
    while (el && el !== anchor) {
      next = hostNextSibling(el);
      hostInsert(el, container, nextSibling);
      el = next;
    }
    hostInsert(anchor, container, nextSibling);
  };
  const removeStaticNode = ({ el, anchor }) => {
    let next;
    while (el && el !== anchor) {
      next = hostNextSibling(el);
      hostRemove(el);
      el = next;
    }
    hostRemove(anchor);
  };
  const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
    isSVG = isSVG || n2.type === "svg";
    if (n1 == null) {
      mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
    } else {
      patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
    }
  };
  const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
    let el;
    let vnodeHook;
    const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
    if (vnode.el && hostCloneNode !== void 0 && patchFlag === -1) {
      el = vnode.el = hostCloneNode(vnode.el);
    } else {
      el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
      if (shapeFlag & 8) {
        hostSetElementText(el, vnode.children);
      } else if (shapeFlag & 16) {
        mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== "foreignObject", slotScopeIds, optimized);
      }
      if (dirs) {
        invokeDirectiveHook(vnode, null, parentComponent, "created");
      }
      if (props) {
        for (const key in props) {
          if (key !== "value" && !isReservedProp(key)) {
            hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
          }
        }
        if ("value" in props) {
          hostPatchProp(el, "value", null, props.value);
        }
        if (vnodeHook = props.onVnodeBeforeMount) {
          invokeVNodeHook(vnodeHook, parentComponent, vnode);
        }
      }
      setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
    }
    if (dirs) {
      invokeDirectiveHook(vnode, null, parentComponent, "beforeMount");
    }
    const needCallTransitionHooks = (!parentSuspense || parentSuspense && !parentSuspense.pendingBranch) && transition && !transition.persisted;
    if (needCallTransitionHooks) {
      transition.beforeEnter(el);
    }
    hostInsert(el, container, anchor);
    if ((vnodeHook = props && props.onVnodeMounted) || needCallTransitionHooks || dirs) {
      queuePostRenderEffect(() => {
        vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
        needCallTransitionHooks && transition.enter(el);
        dirs && invokeDirectiveHook(vnode, null, parentComponent, "mounted");
      }, parentSuspense);
    }
  };
  const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
    if (scopeId) {
      hostSetScopeId(el, scopeId);
    }
    if (slotScopeIds) {
      for (let i = 0; i < slotScopeIds.length; i++) {
        hostSetScopeId(el, slotScopeIds[i]);
      }
    }
    if (parentComponent) {
      let subTree = parentComponent.subTree;
      if (vnode === subTree) {
        const parentVNode = parentComponent.vnode;
        setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
      }
    }
  };
  const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
    for (let i = start; i < children.length; i++) {
      const child = children[i] = optimized ? cloneIfMounted(children[i]) : normalizeVNode(children[i]);
      patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
    }
  };
  const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
    const el = n2.el = n1.el;
    let { patchFlag, dynamicChildren, dirs } = n2;
    patchFlag |= n1.patchFlag & 16;
    const oldProps = n1.props || EMPTY_OBJ;
    const newProps = n2.props || EMPTY_OBJ;
    let vnodeHook;
    parentComponent && toggleRecurse(parentComponent, false);
    if (vnodeHook = newProps.onVnodeBeforeUpdate) {
      invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
    }
    if (dirs) {
      invokeDirectiveHook(n2, n1, parentComponent, "beforeUpdate");
    }
    parentComponent && toggleRecurse(parentComponent, true);
    const areChildrenSVG = isSVG && n2.type !== "foreignObject";
    if (dynamicChildren) {
      patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
    } else if (!optimized) {
      patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
    }
    if (patchFlag > 0) {
      if (patchFlag & 16) {
        patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
      } else {
        if (patchFlag & 2) {
          if (oldProps.class !== newProps.class) {
            hostPatchProp(el, "class", null, newProps.class, isSVG);
          }
        }
        if (patchFlag & 4) {
          hostPatchProp(el, "style", oldProps.style, newProps.style, isSVG);
        }
        if (patchFlag & 8) {
          const propsToUpdate = n2.dynamicProps;
          for (let i = 0; i < propsToUpdate.length; i++) {
            const key = propsToUpdate[i];
            const prev = oldProps[key];
            const next = newProps[key];
            if (next !== prev || key === "value") {
              hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
            }
          }
        }
      }
      if (patchFlag & 1) {
        if (n1.children !== n2.children) {
          hostSetElementText(el, n2.children);
        }
      }
    } else if (!optimized && dynamicChildren == null) {
      patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
    }
    if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
      queuePostRenderEffect(() => {
        vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
        dirs && invokeDirectiveHook(n2, n1, parentComponent, "updated");
      }, parentSuspense);
    }
  };
  const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
    for (let i = 0; i < newChildren.length; i++) {
      const oldVNode = oldChildren[i];
      const newVNode = newChildren[i];
      const container = oldVNode.el && (oldVNode.type === Fragment || !isSameVNodeType(oldVNode, newVNode) || oldVNode.shapeFlag & (6 | 64)) ? hostParentNode(oldVNode.el) : fallbackContainer;
      patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
    }
  };
  const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
    if (oldProps !== newProps) {
      for (const key in newProps) {
        if (isReservedProp(key))
          continue;
        const next = newProps[key];
        const prev = oldProps[key];
        if (next !== prev && key !== "value") {
          hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
        }
      }
      if (oldProps !== EMPTY_OBJ) {
        for (const key in oldProps) {
          if (!isReservedProp(key) && !(key in newProps)) {
            hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
          }
        }
      }
      if ("value" in newProps) {
        hostPatchProp(el, "value", oldProps.value, newProps.value);
      }
    }
  };
  const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
    const fragmentStartAnchor = n2.el = n1 ? n1.el : hostCreateText("");
    const fragmentEndAnchor = n2.anchor = n1 ? n1.anchor : hostCreateText("");
    let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
    if (fragmentSlotScopeIds) {
      slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds;
    }
    if (n1 == null) {
      hostInsert(fragmentStartAnchor, container, anchor);
      hostInsert(fragmentEndAnchor, container, anchor);
      mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
    } else {
      if (patchFlag > 0 && patchFlag & 64 && dynamicChildren && n1.dynamicChildren) {
        patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
        if (n2.key != null || parentComponent && n2 === parentComponent.subTree) {
          traverseStaticChildren(n1, n2, true);
        }
      } else {
        patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
      }
    }
  };
  const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
    n2.slotScopeIds = slotScopeIds;
    if (n1 == null) {
      if (n2.shapeFlag & 512) {
        parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
      } else {
        mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
      }
    } else {
      updateComponent(n1, n2, optimized);
    }
  };
  const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
    const instance = initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense);
    if (isKeepAlive(initialVNode)) {
      instance.ctx.renderer = internals;
    }
    {
      setupComponent(instance);
    }
    if (instance.asyncDep) {
      parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
      if (!initialVNode.el) {
        const placeholder = instance.subTree = createVNode(Comment);
        processCommentNode(null, placeholder, container, anchor);
      }
      return;
    }
    setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
  };
  const updateComponent = (n1, n2, optimized) => {
    const instance = n2.component = n1.component;
    if (shouldUpdateComponent(n1, n2, optimized)) {
      if (instance.asyncDep && !instance.asyncResolved) {
        updateComponentPreRender(instance, n2, optimized);
        return;
      } else {
        instance.next = n2;
        invalidateJob(instance.update);
        instance.update();
      }
    } else {
      n2.el = n1.el;
      instance.vnode = n2;
    }
  };
  const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
    const componentUpdateFn = () => {
      if (!instance.isMounted) {
        let vnodeHook;
        const { el, props } = initialVNode;
        const { bm, m, parent } = instance;
        const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
        toggleRecurse(instance, false);
        if (bm) {
          invokeArrayFns(bm);
        }
        if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeBeforeMount)) {
          invokeVNodeHook(vnodeHook, parent, initialVNode);
        }
        toggleRecurse(instance, true);
        if (el && hydrateNode) {
          const hydrateSubTree = () => {
            instance.subTree = renderComponentRoot(instance);
            hydrateNode(el, instance.subTree, instance, parentSuspense, null);
          };
          if (isAsyncWrapperVNode) {
            initialVNode.type.__asyncLoader().then(() => !instance.isUnmounted && hydrateSubTree());
          } else {
            hydrateSubTree();
          }
        } else {
          const subTree = instance.subTree = renderComponentRoot(instance);
          patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
          initialVNode.el = subTree.el;
        }
        if (m) {
          queuePostRenderEffect(m, parentSuspense);
        }
        if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeMounted)) {
          const scopedInitialVNode = initialVNode;
          queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
        }
        if (initialVNode.shapeFlag & 256 || parent && isAsyncWrapper(parent.vnode) && parent.vnode.shapeFlag & 256) {
          instance.a && queuePostRenderEffect(instance.a, parentSuspense);
        }
        instance.isMounted = true;
        initialVNode = container = anchor = null;
      } else {
        let { next, bu, u, parent, vnode } = instance;
        let originNext = next;
        let vnodeHook;
        toggleRecurse(instance, false);
        if (next) {
          next.el = vnode.el;
          updateComponentPreRender(instance, next, optimized);
        } else {
          next = vnode;
        }
        if (bu) {
          invokeArrayFns(bu);
        }
        if (vnodeHook = next.props && next.props.onVnodeBeforeUpdate) {
          invokeVNodeHook(vnodeHook, parent, next, vnode);
        }
        toggleRecurse(instance, true);
        const nextTree = renderComponentRoot(instance);
        const prevTree = instance.subTree;
        instance.subTree = nextTree;
        patch(prevTree, nextTree, hostParentNode(prevTree.el), getNextHostNode(prevTree), instance, parentSuspense, isSVG);
        next.el = nextTree.el;
        if (originNext === null) {
          updateHOCHostEl(instance, nextTree.el);
        }
        if (u) {
          queuePostRenderEffect(u, parentSuspense);
        }
        if (vnodeHook = next.props && next.props.onVnodeUpdated) {
          queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
        }
      }
    };
    const effect = instance.effect = new ReactiveEffect(componentUpdateFn, () => queueJob(update), instance.scope);
    const update = instance.update = () => effect.run();
    update.id = instance.uid;
    toggleRecurse(instance, true);
    update();
  };
  const updateComponentPreRender = (instance, nextVNode, optimized) => {
    nextVNode.component = instance;
    const prevProps = instance.vnode.props;
    instance.vnode = nextVNode;
    instance.next = null;
    updateProps(instance, nextVNode.props, prevProps, optimized);
    updateSlots(instance, nextVNode.children, optimized);
    pauseTracking();
    flushPreFlushCbs(void 0, instance.update);
    resetTracking();
  };
  const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
    const c1 = n1 && n1.children;
    const prevShapeFlag = n1 ? n1.shapeFlag : 0;
    const c2 = n2.children;
    const { patchFlag, shapeFlag } = n2;
    if (patchFlag > 0) {
      if (patchFlag & 128) {
        patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
        return;
      } else if (patchFlag & 256) {
        patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
        return;
      }
    }
    if (shapeFlag & 8) {
      if (prevShapeFlag & 16) {
        unmountChildren(c1, parentComponent, parentSuspense);
      }
      if (c2 !== c1) {
        hostSetElementText(container, c2);
      }
    } else {
      if (prevShapeFlag & 16) {
        if (shapeFlag & 16) {
          patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
        } else {
          unmountChildren(c1, parentComponent, parentSuspense, true);
        }
      } else {
        if (prevShapeFlag & 8) {
          hostSetElementText(container, "");
        }
        if (shapeFlag & 16) {
          mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
        }
      }
    }
  };
  const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
    c1 = c1 || EMPTY_ARR;
    c2 = c2 || EMPTY_ARR;
    const oldLength = c1.length;
    const newLength = c2.length;
    const commonLength = Math.min(oldLength, newLength);
    let i;
    for (i = 0; i < commonLength; i++) {
      const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]);
      patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
    }
    if (oldLength > newLength) {
      unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
    } else {
      mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
    }
  };
  const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
    let i = 0;
    const l2 = c2.length;
    let e1 = c1.length - 1;
    let e2 = l2 - 1;
    while (i <= e1 && i <= e2) {
      const n1 = c1[i];
      const n2 = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]);
      if (isSameVNodeType(n1, n2)) {
        patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
      } else {
        break;
      }
      i++;
    }
    while (i <= e1 && i <= e2) {
      const n1 = c1[e1];
      const n2 = c2[e2] = optimized ? cloneIfMounted(c2[e2]) : normalizeVNode(c2[e2]);
      if (isSameVNodeType(n1, n2)) {
        patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
      } else {
        break;
      }
      e1--;
      e2--;
    }
    if (i > e1) {
      if (i <= e2) {
        const nextPos = e2 + 1;
        const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
        while (i <= e2) {
          patch(null, c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
          i++;
        }
      }
    } else if (i > e2) {
      while (i <= e1) {
        unmount(c1[i], parentComponent, parentSuspense, true);
        i++;
      }
    } else {
      const s1 = i;
      const s2 = i;
      const keyToNewIndexMap = /* @__PURE__ */ new Map();
      for (i = s2; i <= e2; i++) {
        const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]);
        if (nextChild.key != null) {
          keyToNewIndexMap.set(nextChild.key, i);
        }
      }
      let j;
      let patched = 0;
      const toBePatched = e2 - s2 + 1;
      let moved = false;
      let maxNewIndexSoFar = 0;
      const newIndexToOldIndexMap = new Array(toBePatched);
      for (i = 0; i < toBePatched; i++)
        newIndexToOldIndexMap[i] = 0;
      for (i = s1; i <= e1; i++) {
        const prevChild = c1[i];
        if (patched >= toBePatched) {
          unmount(prevChild, parentComponent, parentSuspense, true);
          continue;
        }
        let newIndex;
        if (prevChild.key != null) {
          newIndex = keyToNewIndexMap.get(prevChild.key);
        } else {
          for (j = s2; j <= e2; j++) {
            if (newIndexToOldIndexMap[j - s2] === 0 && isSameVNodeType(prevChild, c2[j])) {
              newIndex = j;
              break;
            }
          }
        }
        if (newIndex === void 0) {
          unmount(prevChild, parentComponent, parentSuspense, true);
        } else {
          newIndexToOldIndexMap[newIndex - s2] = i + 1;
          if (newIndex >= maxNewIndexSoFar) {
            maxNewIndexSoFar = newIndex;
          } else {
            moved = true;
          }
          patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
          patched++;
        }
      }
      const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : EMPTY_ARR;
      j = increasingNewIndexSequence.length - 1;
      for (i = toBePatched - 1; i >= 0; i--) {
        const nextIndex = s2 + i;
        const nextChild = c2[nextIndex];
        const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
        if (newIndexToOldIndexMap[i] === 0) {
          patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
        } else if (moved) {
          if (j < 0 || i !== increasingNewIndexSequence[j]) {
            move(nextChild, container, anchor, 2);
          } else {
            j--;
          }
        }
      }
    }
  };
  const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
    const { el, type, transition, children, shapeFlag } = vnode;
    if (shapeFlag & 6) {
      move(vnode.component.subTree, container, anchor, moveType);
      return;
    }
    if (shapeFlag & 128) {
      vnode.suspense.move(container, anchor, moveType);
      return;
    }
    if (shapeFlag & 64) {
      type.move(vnode, container, anchor, internals);
      return;
    }
    if (type === Fragment) {
      hostInsert(el, container, anchor);
      for (let i = 0; i < children.length; i++) {
        move(children[i], container, anchor, moveType);
      }
      hostInsert(vnode.anchor, container, anchor);
      return;
    }
    if (type === Static) {
      moveStaticNode(vnode, container, anchor);
      return;
    }
    const needTransition = moveType !== 2 && shapeFlag & 1 && transition;
    if (needTransition) {
      if (moveType === 0) {
        transition.beforeEnter(el);
        hostInsert(el, container, anchor);
        queuePostRenderEffect(() => transition.enter(el), parentSuspense);
      } else {
        const { leave, delayLeave, afterLeave } = transition;
        const remove3 = () => hostInsert(el, container, anchor);
        const performLeave = () => {
          leave(el, () => {
            remove3();
            afterLeave && afterLeave();
          });
        };
        if (delayLeave) {
          delayLeave(el, remove3, performLeave);
        } else {
          performLeave();
        }
      }
    } else {
      hostInsert(el, container, anchor);
    }
  };
  const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
    const { type, props, ref: ref2, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
    if (ref2 != null) {
      setRef(ref2, null, parentSuspense, vnode, true);
    }
    if (shapeFlag & 256) {
      parentComponent.ctx.deactivate(vnode);
      return;
    }
    const shouldInvokeDirs = shapeFlag & 1 && dirs;
    const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
    let vnodeHook;
    if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeBeforeUnmount)) {
      invokeVNodeHook(vnodeHook, parentComponent, vnode);
    }
    if (shapeFlag & 6) {
      unmountComponent(vnode.component, parentSuspense, doRemove);
    } else {
      if (shapeFlag & 128) {
        vnode.suspense.unmount(parentSuspense, doRemove);
        return;
      }
      if (shouldInvokeDirs) {
        invokeDirectiveHook(vnode, null, parentComponent, "beforeUnmount");
      }
      if (shapeFlag & 64) {
        vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
      } else if (dynamicChildren && (type !== Fragment || patchFlag > 0 && patchFlag & 64)) {
        unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
      } else if (type === Fragment && patchFlag & (128 | 256) || !optimized && shapeFlag & 16) {
        unmountChildren(children, parentComponent, parentSuspense);
      }
      if (doRemove) {
        remove2(vnode);
      }
    }
    if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs) {
      queuePostRenderEffect(() => {
        vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
        shouldInvokeDirs && invokeDirectiveHook(vnode, null, parentComponent, "unmounted");
      }, parentSuspense);
    }
  };
  const remove2 = (vnode) => {
    const { type, el, anchor, transition } = vnode;
    if (type === Fragment) {
      {
        removeFragment(el, anchor);
      }
      return;
    }
    if (type === Static) {
      removeStaticNode(vnode);
      return;
    }
    const performRemove = () => {
      hostRemove(el);
      if (transition && !transition.persisted && transition.afterLeave) {
        transition.afterLeave();
      }
    };
    if (vnode.shapeFlag & 1 && transition && !transition.persisted) {
      const { leave, delayLeave } = transition;
      const performLeave = () => leave(el, performRemove);
      if (delayLeave) {
        delayLeave(vnode.el, performRemove, performLeave);
      } else {
        performLeave();
      }
    } else {
      performRemove();
    }
  };
  const removeFragment = (cur, end) => {
    let next;
    while (cur !== end) {
      next = hostNextSibling(cur);
      hostRemove(cur);
      cur = next;
    }
    hostRemove(end);
  };
  const unmountComponent = (instance, parentSuspense, doRemove) => {
    const { bum, scope, update, subTree, um } = instance;
    if (bum) {
      invokeArrayFns(bum);
    }
    scope.stop();
    if (update) {
      update.active = false;
      unmount(subTree, instance, parentSuspense, doRemove);
    }
    if (um) {
      queuePostRenderEffect(um, parentSuspense);
    }
    queuePostRenderEffect(() => {
      instance.isUnmounted = true;
    }, parentSuspense);
    if (parentSuspense && parentSuspense.pendingBranch && !parentSuspense.isUnmounted && instance.asyncDep && !instance.asyncResolved && instance.suspenseId === parentSuspense.pendingId) {
      parentSuspense.deps--;
      if (parentSuspense.deps === 0) {
        parentSuspense.resolve();
      }
    }
  };
  const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
    for (let i = start; i < children.length; i++) {
      unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
    }
  };
  const getNextHostNode = (vnode) => {
    if (vnode.shapeFlag & 6) {
      return getNextHostNode(vnode.component.subTree);
    }
    if (vnode.shapeFlag & 128) {
      return vnode.suspense.next();
    }
    return hostNextSibling(vnode.anchor || vnode.el);
  };
  const render = (vnode, container, isSVG) => {
    if (vnode == null) {
      if (container._vnode) {
        unmount(container._vnode, null, null, true);
      }
    } else {
      patch(container._vnode || null, vnode, container, null, null, null, isSVG);
    }
    flushPostFlushCbs();
    container._vnode = vnode;
  };
  const internals = {
    p: patch,
    um: unmount,
    m: move,
    r: remove2,
    mt: mountComponent,
    mc: mountChildren,
    pc: patchChildren,
    pbc: patchBlockChildren,
    n: getNextHostNode,
    o: options
  };
  let hydrate;
  let hydrateNode;
  if (createHydrationFns) {
    [hydrate, hydrateNode] = createHydrationFns(internals);
  }
  return {
    render,
    hydrate,
    createApp: createAppAPI(render, hydrate)
  };
}
function toggleRecurse({ effect, update }, allowed) {
  effect.allowRecurse = update.allowRecurse = allowed;
}
function traverseStaticChildren(n1, n2, shallow = false) {
  const ch1 = n1.children;
  const ch2 = n2.children;
  if (isArray(ch1) && isArray(ch2)) {
    for (let i = 0; i < ch1.length; i++) {
      const c1 = ch1[i];
      let c2 = ch2[i];
      if (c2.shapeFlag & 1 && !c2.dynamicChildren) {
        if (c2.patchFlag <= 0 || c2.patchFlag === 32) {
          c2 = ch2[i] = cloneIfMounted(ch2[i]);
          c2.el = c1.el;
        }
        if (!shallow)
          traverseStaticChildren(c1, c2);
      }
    }
  }
}
function getSequence(arr) {
  const p2 = arr.slice();
  const result = [0];
  let i, j, u, v, c;
  const len = arr.length;
  for (i = 0; i < len; i++) {
    const arrI = arr[i];
    if (arrI !== 0) {
      j = result[result.length - 1];
      if (arr[j] < arrI) {
        p2[i] = j;
        result.push(i);
        continue;
      }
      u = 0;
      v = result.length - 1;
      while (u < v) {
        c = u + v >> 1;
        if (arr[result[c]] < arrI) {
          u = c + 1;
        } else {
          v = c;
        }
      }
      if (arrI < arr[result[u]]) {
        if (u > 0) {
          p2[i] = result[u - 1];
        }
        result[u] = i;
      }
    }
  }
  u = result.length;
  v = result[u - 1];
  while (u-- > 0) {
    result[u] = v;
    v = p2[v];
  }
  return result;
}
const isTeleport = (type) => type.__isTeleport;
const Fragment = Symbol(void 0);
const Text$1 = Symbol(void 0);
const Comment = Symbol(void 0);
const Static = Symbol(void 0);
const blockStack = [];
let currentBlock = null;
function openBlock(disableTracking = false) {
  blockStack.push(currentBlock = disableTracking ? null : []);
}
function closeBlock() {
  blockStack.pop();
  currentBlock = blockStack[blockStack.length - 1] || null;
}
let isBlockTreeEnabled = 1;
function setBlockTracking(value) {
  isBlockTreeEnabled += value;
}
function setupBlock(vnode) {
  vnode.dynamicChildren = isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
  closeBlock();
  if (isBlockTreeEnabled > 0 && currentBlock) {
    currentBlock.push(vnode);
  }
  return vnode;
}
function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
  return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true));
}
function createBlock(type, props, children, patchFlag, dynamicProps) {
  return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true));
}
function isVNode(value) {
  return value ? value.__v_isVNode === true : false;
}
function isSameVNodeType(n1, n2) {
  return n1.type === n2.type && n1.key === n2.key;
}
const InternalObjectKey = `__vInternal`;
const normalizeKey = ({ key }) => key != null ? key : null;
const normalizeRef = ({ ref: ref2, ref_key, ref_for }) => {
  return ref2 != null ? isString(ref2) || isRef(ref2) || isFunction(ref2) ? { i: currentRenderingInstance, r: ref2, k: ref_key, f: !!ref_for } : ref2 : null;
};
function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1, isBlockNode = false, needFullChildrenNormalization = false) {
  const vnode = {
    __v_isVNode: true,
    __v_skip: true,
    type,
    props,
    key: props && normalizeKey(props),
    ref: props && normalizeRef(props),
    scopeId: currentScopeId,
    slotScopeIds: null,
    children,
    component: null,
    suspense: null,
    ssContent: null,
    ssFallback: null,
    dirs: null,
    transition: null,
    el: null,
    anchor: null,
    target: null,
    targetAnchor: null,
    staticCount: 0,
    shapeFlag,
    patchFlag,
    dynamicProps,
    dynamicChildren: null,
    appContext: null
  };
  if (needFullChildrenNormalization) {
    normalizeChildren(vnode, children);
    if (shapeFlag & 128) {
      type.normalize(vnode);
    }
  } else if (children) {
    vnode.shapeFlag |= isString(children) ? 8 : 16;
  }
  if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock && (vnode.patchFlag > 0 || shapeFlag & 6) && vnode.patchFlag !== 32) {
    currentBlock.push(vnode);
  }
  return vnode;
}
const createVNode = _createVNode;
function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
  if (!type || type === NULL_DYNAMIC_COMPONENT) {
    type = Comment;
  }
  if (isVNode(type)) {
    const cloned = cloneVNode(type, props, true);
    if (children) {
      normalizeChildren(cloned, children);
    }
    if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) {
      if (cloned.shapeFlag & 6) {
        currentBlock[currentBlock.indexOf(type)] = cloned;
      } else {
        currentBlock.push(cloned);
      }
    }
    cloned.patchFlag |= -2;
    return cloned;
  }
  if (isClassComponent(type)) {
    type = type.__vccOpts;
  }
  if (props) {
    props = guardReactiveProps(props);
    let { class: klass, style } = props;
    if (klass && !isString(klass)) {
      props.class = normalizeClass(klass);
    }
    if (isObject(style)) {
      if (isProxy(style) && !isArray(style)) {
        style = extend({}, style);
      }
      props.style = normalizeStyle(style);
    }
  }
  const shapeFlag = isString(type) ? 1 : isSuspense(type) ? 128 : isTeleport(type) ? 64 : isObject(type) ? 4 : isFunction(type) ? 2 : 0;
  return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
}
function guardReactiveProps(props) {
  if (!props)
    return null;
  return isProxy(props) || InternalObjectKey in props ? extend({}, props) : props;
}
function cloneVNode(vnode, extraProps, mergeRef = false) {
  const { props, ref: ref2, patchFlag, children } = vnode;
  const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
  const cloned = {
    __v_isVNode: true,
    __v_skip: true,
    type: vnode.type,
    props: mergedProps,
    key: mergedProps && normalizeKey(mergedProps),
    ref: extraProps && extraProps.ref ? mergeRef && ref2 ? isArray(ref2) ? ref2.concat(normalizeRef(extraProps)) : [ref2, normalizeRef(extraProps)] : normalizeRef(extraProps) : ref2,
    scopeId: vnode.scopeId,
    slotScopeIds: vnode.slotScopeIds,
    children,
    target: vnode.target,
    targetAnchor: vnode.targetAnchor,
    staticCount: vnode.staticCount,
    shapeFlag: vnode.shapeFlag,
    patchFlag: extraProps && vnode.type !== Fragment ? patchFlag === -1 ? 16 : patchFlag | 16 : patchFlag,
    dynamicProps: vnode.dynamicProps,
    dynamicChildren: vnode.dynamicChildren,
    appContext: vnode.appContext,
    dirs: vnode.dirs,
    transition: vnode.transition,
    component: vnode.component,
    suspense: vnode.suspense,
    ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
    ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
    el: vnode.el,
    anchor: vnode.anchor
  };
  return cloned;
}
function createTextVNode(text = " ", flag = 0) {
  return createVNode(Text$1, null, text, flag);
}
function createCommentVNode(text = "", asBlock = false) {
  return asBlock ? (openBlock(), createBlock(Comment, null, text)) : createVNode(Comment, null, text);
}
function normalizeVNode(child) {
  if (child == null || typeof child === "boolean") {
    return createVNode(Comment);
  } else if (isArray(child)) {
    return createVNode(Fragment, null, child.slice());
  } else if (typeof child === "object") {
    return cloneIfMounted(child);
  } else {
    return createVNode(Text$1, null, String(child));
  }
}
function cloneIfMounted(child) {
  return child.el === null || child.memo ? child : cloneVNode(child);
}
function normalizeChildren(vnode, children) {
  let type = 0;
  const { shapeFlag } = vnode;
  if (children == null) {
    children = null;
  } else if (isArray(children)) {
    type = 16;
  } else if (typeof children === "object") {
    if (shapeFlag & (1 | 64)) {
      const slot = children.default;
      if (slot) {
        slot._c && (slot._d = false);
        normalizeChildren(vnode, slot());
        slot._c && (slot._d = true);
      }
      return;
    } else {
      type = 32;
      const slotFlag = children._;
      if (!slotFlag && !(InternalObjectKey in children)) {
        children._ctx = currentRenderingInstance;
      } else if (slotFlag === 3 && currentRenderingInstance) {
        if (currentRenderingInstance.slots._ === 1) {
          children._ = 1;
        } else {
          children._ = 2;
          vnode.patchFlag |= 1024;
        }
      }
    }
  } else if (isFunction(children)) {
    children = { default: children, _ctx: currentRenderingInstance };
    type = 32;
  } else {
    children = String(children);
    if (shapeFlag & 64) {
      type = 16;
      children = [createTextVNode(children)];
    } else {
      type = 8;
    }
  }
  vnode.children = children;
  vnode.shapeFlag |= type;
}
function mergeProps(...args) {
  const ret = {};
  for (let i = 0; i < args.length; i++) {
    const toMerge = args[i];
    for (const key in toMerge) {
      if (key === "class") {
        if (ret.class !== toMerge.class) {
          ret.class = normalizeClass([ret.class, toMerge.class]);
        }
      } else if (key === "style") {
        ret.style = normalizeStyle([ret.style, toMerge.style]);
      } else if (isOn(key)) {
        const existing = ret[key];
        const incoming = toMerge[key];
        if (incoming && existing !== incoming && !(isArray(existing) && existing.includes(incoming))) {
          ret[key] = existing ? [].concat(existing, incoming) : incoming;
        }
      } else if (key !== "") {
        ret[key] = toMerge[key];
      }
    }
  }
  return ret;
}
function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
  callWithAsyncErrorHandling(hook, instance, 7, [
    vnode,
    prevVNode
  ]);
}
const emptyAppContext = createAppContext();
let uid$1 = 0;
function createComponentInstance(vnode, parent, suspense) {
  const type = vnode.type;
  const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
  const instance = {
    uid: uid$1++,
    vnode,
    type,
    parent,
    appContext,
    root: null,
    next: null,
    subTree: null,
    effect: null,
    update: null,
    scope: new EffectScope(true),
    render: null,
    proxy: null,
    exposed: null,
    exposeProxy: null,
    withProxy: null,
    provides: parent ? parent.provides : Object.create(appContext.provides),
    accessCache: null,
    renderCache: [],
    components: null,
    directives: null,
    propsOptions: normalizePropsOptions(type, appContext),
    emitsOptions: normalizeEmitsOptions(type, appContext),
    emit: null,
    emitted: null,
    propsDefaults: EMPTY_OBJ,
    inheritAttrs: type.inheritAttrs,
    ctx: EMPTY_OBJ,
    data: EMPTY_OBJ,
    props: EMPTY_OBJ,
    attrs: EMPTY_OBJ,
    slots: EMPTY_OBJ,
    refs: EMPTY_OBJ,
    setupState: EMPTY_OBJ,
    setupContext: null,
    suspense,
    suspenseId: suspense ? suspense.pendingId : 0,
    asyncDep: null,
    asyncResolved: false,
    isMounted: false,
    isUnmounted: false,
    isDeactivated: false,
    bc: null,
    c: null,
    bm: null,
    m: null,
    bu: null,
    u: null,
    um: null,
    bum: null,
    da: null,
    a: null,
    rtg: null,
    rtc: null,
    ec: null,
    sp: null
  };
  {
    instance.ctx = { _: instance };
  }
  instance.root = parent ? parent.root : instance;
  instance.emit = emit$1.bind(null, instance);
  if (vnode.ce) {
    vnode.ce(instance);
  }
  return instance;
}
let currentInstance = null;
const setCurrentInstance = (instance) => {
  currentInstance = instance;
  instance.scope.on();
};
const unsetCurrentInstance = () => {
  currentInstance && currentInstance.scope.off();
  currentInstance = null;
};
function isStatefulComponent(instance) {
  return instance.vnode.shapeFlag & 4;
}
let isInSSRComponentSetup = false;
function setupComponent(instance, isSSR = false) {
  isInSSRComponentSetup = isSSR;
  const { props, children } = instance.vnode;
  const isStateful = isStatefulComponent(instance);
  initProps(instance, props, isStateful, isSSR);
  initSlots(instance, children);
  const setupResult = isStateful ? setupStatefulComponent(instance, isSSR) : void 0;
  isInSSRComponentSetup = false;
  return setupResult;
}
function setupStatefulComponent(instance, isSSR) {
  const Component = instance.type;
  instance.accessCache = /* @__PURE__ */ Object.create(null);
  instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
  const { setup } = Component;
  if (setup) {
    const setupContext = instance.setupContext = setup.length > 1 ? createSetupContext(instance) : null;
    setCurrentInstance(instance);
    pauseTracking();
    const setupResult = callWithErrorHandling(setup, instance, 0, [instance.props, setupContext]);
    resetTracking();
    unsetCurrentInstance();
    if (isPromise(setupResult)) {
      setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
      if (isSSR) {
        return setupResult.then((resolvedResult) => {
          handleSetupResult(instance, resolvedResult, isSSR);
        }).catch((e) => {
          handleError(e, instance, 0);
        });
      } else {
        instance.asyncDep = setupResult;
      }
    } else {
      handleSetupResult(instance, setupResult, isSSR);
    }
  } else {
    finishComponentSetup(instance, isSSR);
  }
}
function handleSetupResult(instance, setupResult, isSSR) {
  if (isFunction(setupResult)) {
    if (instance.type.__ssrInlineRender) {
      instance.ssrRender = setupResult;
    } else {
      instance.render = setupResult;
    }
  } else if (isObject(setupResult)) {
    instance.setupState = proxyRefs(setupResult);
  } else
    ;
  finishComponentSetup(instance, isSSR);
}
let compile;
function finishComponentSetup(instance, isSSR, skipOptions) {
  const Component = instance.type;
  if (!instance.render) {
    if (!isSSR && compile && !Component.render) {
      const template = Component.template;
      if (template) {
        const { isCustomElement, compilerOptions } = instance.appContext.config;
        const { delimiters, compilerOptions: componentCompilerOptions } = Component;
        const finalCompilerOptions = extend(extend({
          isCustomElement,
          delimiters
        }, compilerOptions), componentCompilerOptions);
        Component.render = compile(template, finalCompilerOptions);
      }
    }
    instance.render = Component.render || NOOP;
  }
  {
    setCurrentInstance(instance);
    pauseTracking();
    applyOptions(instance);
    resetTracking();
    unsetCurrentInstance();
  }
}
function createAttrsProxy(instance) {
  return new Proxy(instance.attrs, {
    get(target, key) {
      track(instance, "get", "$attrs");
      return target[key];
    }
  });
}
function createSetupContext(instance) {
  const expose = (exposed) => {
    instance.exposed = exposed || {};
  };
  let attrs;
  {
    return {
      get attrs() {
        return attrs || (attrs = createAttrsProxy(instance));
      },
      slots: instance.slots,
      emit: instance.emit,
      expose
    };
  }
}
function getExposeProxy(instance) {
  if (instance.exposed) {
    return instance.exposeProxy || (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
      get(target, key) {
        if (key in target) {
          return target[key];
        } else if (key in publicPropertiesMap) {
          return publicPropertiesMap[key](instance);
        }
      }
    }));
  }
}
function isClassComponent(value) {
  return isFunction(value) && "__vccOpts" in value;
}
const computed = (getterOrOptions, debugOptions) => {
  return computed$1(getterOrOptions, debugOptions, isInSSRComponentSetup);
};
const version = "3.2.37";
const svgNS = "http://www.w3.org/2000/svg";
const doc = typeof document !== "undefined" ? document : null;
const templateContainer = doc && /* @__PURE__ */ doc.createElement("template");
const nodeOps = {
  insert: (child, parent, anchor) => {
    parent.insertBefore(child, anchor || null);
  },
  remove: (child) => {
    const parent = child.parentNode;
    if (parent) {
      parent.removeChild(child);
    }
  },
  createElement: (tag, isSVG, is, props) => {
    const el = isSVG ? doc.createElementNS(svgNS, tag) : doc.createElement(tag, is ? { is } : void 0);
    if (tag === "select" && props && props.multiple != null) {
      el.setAttribute("multiple", props.multiple);
    }
    return el;
  },
  createText: (text) => doc.createTextNode(text),
  createComment: (text) => doc.createComment(text),
  setText: (node, text) => {
    node.nodeValue = text;
  },
  setElementText: (el, text) => {
    el.textContent = text;
  },
  parentNode: (node) => node.parentNode,
  nextSibling: (node) => node.nextSibling,
  querySelector: (selector) => doc.querySelector(selector),
  setScopeId(el, id) {
    el.setAttribute(id, "");
  },
  cloneNode(el) {
    const cloned = el.cloneNode(true);
    if (`_value` in el) {
      cloned._value = el._value;
    }
    return cloned;
  },
  insertStaticContent(content, parent, anchor, isSVG, start, end) {
    const before = anchor ? anchor.previousSibling : parent.lastChild;
    if (start && (start === end || start.nextSibling)) {
      while (true) {
        parent.insertBefore(start.cloneNode(true), anchor);
        if (start === end || !(start = start.nextSibling))
          break;
      }
    } else {
      templateContainer.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
      const template = templateContainer.content;
      if (isSVG) {
        const wrapper = template.firstChild;
        while (wrapper.firstChild) {
          template.appendChild(wrapper.firstChild);
        }
        template.removeChild(wrapper);
      }
      parent.insertBefore(template, anchor);
    }
    return [
      before ? before.nextSibling : parent.firstChild,
      anchor ? anchor.previousSibling : parent.lastChild
    ];
  }
};
function patchClass(el, value, isSVG) {
  const transitionClasses = el._vtc;
  if (transitionClasses) {
    value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(" ");
  }
  if (value == null) {
    el.removeAttribute("class");
  } else if (isSVG) {
    el.setAttribute("class", value);
  } else {
    el.className = value;
  }
}
function patchStyle(el, prev, next) {
  const style = el.style;
  const isCssString = isString(next);
  if (next && !isCssString) {
    for (const key in next) {
      setStyle(style, key, next[key]);
    }
    if (prev && !isString(prev)) {
      for (const key in prev) {
        if (next[key] == null) {
          setStyle(style, key, "");
        }
      }
    }
  } else {
    const currentDisplay = style.display;
    if (isCssString) {
      if (prev !== next) {
        style.cssText = next;
      }
    } else if (prev) {
      el.removeAttribute("style");
    }
    if ("_vod" in el) {
      style.display = currentDisplay;
    }
  }
}
const importantRE = /\s*!important$/;
function setStyle(style, name, val) {
  if (isArray(val)) {
    val.forEach((v) => setStyle(style, name, v));
  } else {
    if (val == null)
      val = "";
    if (name.startsWith("--")) {
      style.setProperty(name, val);
    } else {
      const prefixed = autoPrefix(style, name);
      if (importantRE.test(val)) {
        style.setProperty(hyphenate(prefixed), val.replace(importantRE, ""), "important");
      } else {
        style[prefixed] = val;
      }
    }
  }
}
const prefixes = ["Webkit", "Moz", "ms"];
const prefixCache = {};
function autoPrefix(style, rawName) {
  const cached = prefixCache[rawName];
  if (cached) {
    return cached;
  }
  let name = camelize(rawName);
  if (name !== "filter" && name in style) {
    return prefixCache[rawName] = name;
  }
  name = capitalize(name);
  for (let i = 0; i < prefixes.length; i++) {
    const prefixed = prefixes[i] + name;
    if (prefixed in style) {
      return prefixCache[rawName] = prefixed;
    }
  }
  return rawName;
}
const xlinkNS = "http://www.w3.org/1999/xlink";
function patchAttr(el, key, value, isSVG, instance) {
  if (isSVG && key.startsWith("xlink:")) {
    if (value == null) {
      el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
    } else {
      el.setAttributeNS(xlinkNS, key, value);
    }
  } else {
    const isBoolean = isSpecialBooleanAttr(key);
    if (value == null || isBoolean && !includeBooleanAttr(value)) {
      el.removeAttribute(key);
    } else {
      el.setAttribute(key, isBoolean ? "" : value);
    }
  }
}
function patchDOMProp(el, key, value, prevChildren, parentComponent, parentSuspense, unmountChildren) {
  if (key === "innerHTML" || key === "textContent") {
    if (prevChildren) {
      unmountChildren(prevChildren, parentComponent, parentSuspense);
    }
    el[key] = value == null ? "" : value;
    return;
  }
  if (key === "value" && el.tagName !== "PROGRESS" && !el.tagName.includes("-")) {
    el._value = value;
    const newValue = value == null ? "" : value;
    if (el.value !== newValue || el.tagName === "OPTION") {
      el.value = newValue;
    }
    if (value == null) {
      el.removeAttribute(key);
    }
    return;
  }
  let needRemove = false;
  if (value === "" || value == null) {
    const type = typeof el[key];
    if (type === "boolean") {
      value = includeBooleanAttr(value);
    } else if (value == null && type === "string") {
      value = "";
      needRemove = true;
    } else if (type === "number") {
      value = 0;
      needRemove = true;
    }
  }
  try {
    el[key] = value;
  } catch (e) {
  }
  needRemove && el.removeAttribute(key);
}
const [_getNow, skipTimestampCheck] = /* @__PURE__ */ (() => {
  let _getNow2 = Date.now;
  let skipTimestampCheck2 = false;
  if (typeof window !== "undefined") {
    if (Date.now() > document.createEvent("Event").timeStamp) {
      _getNow2 = performance.now.bind(performance);
    }
    const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
    skipTimestampCheck2 = !!(ffMatch && Number(ffMatch[1]) <= 53);
  }
  return [_getNow2, skipTimestampCheck2];
})();
let cachedNow = 0;
const p = /* @__PURE__ */ Promise.resolve();
const reset = () => {
  cachedNow = 0;
};
const getNow = () => cachedNow || (p.then(reset), cachedNow = _getNow());
function addEventListener(el, event, handler, options) {
  el.addEventListener(event, handler, options);
}
function removeEventListener(el, event, handler, options) {
  el.removeEventListener(event, handler, options);
}
function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
  const invokers = el._vei || (el._vei = {});
  const existingInvoker = invokers[rawName];
  if (nextValue && existingInvoker) {
    existingInvoker.value = nextValue;
  } else {
    const [name, options] = parseName(rawName);
    if (nextValue) {
      const invoker = invokers[rawName] = createInvoker(nextValue, instance);
      addEventListener(el, name, invoker, options);
    } else if (existingInvoker) {
      removeEventListener(el, name, existingInvoker, options);
      invokers[rawName] = void 0;
    }
  }
}
const optionsModifierRE = /(?:Once|Passive|Capture)$/;
function parseName(name) {
  let options;
  if (optionsModifierRE.test(name)) {
    options = {};
    let m;
    while (m = name.match(optionsModifierRE)) {
      name = name.slice(0, name.length - m[0].length);
      options[m[0].toLowerCase()] = true;
    }
  }
  return [hyphenate(name.slice(2)), options];
}
function createInvoker(initialValue, instance) {
  const invoker = (e) => {
    const timeStamp = e.timeStamp || _getNow();
    if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
      callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5, [e]);
    }
  };
  invoker.value = initialValue;
  invoker.attached = getNow();
  return invoker;
}
function patchStopImmediatePropagation(e, value) {
  if (isArray(value)) {
    const originalStop = e.stopImmediatePropagation;
    e.stopImmediatePropagation = () => {
      originalStop.call(e);
      e._stopped = true;
    };
    return value.map((fn) => (e2) => !e2._stopped && fn && fn(e2));
  } else {
    return value;
  }
}
const nativeOnRE = /^on[a-z]/;
const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
  if (key === "class") {
    patchClass(el, nextValue, isSVG);
  } else if (key === "style") {
    patchStyle(el, prevValue, nextValue);
  } else if (isOn(key)) {
    if (!isModelListener(key)) {
      patchEvent(el, key, prevValue, nextValue, parentComponent);
    }
  } else if (key[0] === "." ? (key = key.slice(1), true) : key[0] === "^" ? (key = key.slice(1), false) : shouldSetAsProp(el, key, nextValue, isSVG)) {
    patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
  } else {
    if (key === "true-value") {
      el._trueValue = nextValue;
    } else if (key === "false-value") {
      el._falseValue = nextValue;
    }
    patchAttr(el, key, nextValue, isSVG);
  }
};
function shouldSetAsProp(el, key, value, isSVG) {
  if (isSVG) {
    if (key === "innerHTML" || key === "textContent") {
      return true;
    }
    if (key in el && nativeOnRE.test(key) && isFunction(value)) {
      return true;
    }
    return false;
  }
  if (key === "spellcheck" || key === "draggable" || key === "translate") {
    return false;
  }
  if (key === "form") {
    return false;
  }
  if (key === "list" && el.tagName === "INPUT") {
    return false;
  }
  if (key === "type" && el.tagName === "TEXTAREA") {
    return false;
  }
  if (nativeOnRE.test(key) && isString(value)) {
    return false;
  }
  return key in el;
}
const systemModifiers = ["ctrl", "shift", "alt", "meta"];
const modifierGuards = {
  stop: (e) => e.stopPropagation(),
  prevent: (e) => e.preventDefault(),
  self: (e) => e.target !== e.currentTarget,
  ctrl: (e) => !e.ctrlKey,
  shift: (e) => !e.shiftKey,
  alt: (e) => !e.altKey,
  meta: (e) => !e.metaKey,
  left: (e) => "button" in e && e.button !== 0,
  middle: (e) => "button" in e && e.button !== 1,
  right: (e) => "button" in e && e.button !== 2,
  exact: (e, modifiers) => systemModifiers.some((m) => e[`${m}Key`] && !modifiers.includes(m))
};
const withModifiers = (fn, modifiers) => {
  return (event, ...args) => {
    for (let i = 0; i < modifiers.length; i++) {
      const guard = modifierGuards[modifiers[i]];
      if (guard && guard(event, modifiers))
        return;
    }
    return fn(event, ...args);
  };
};
const rendererOptions = /* @__PURE__ */ extend({ patchProp }, nodeOps);
let renderer;
function ensureRenderer() {
  return renderer || (renderer = createRenderer(rendererOptions));
}
const createApp = (...args) => {
  const app = ensureRenderer().createApp(...args);
  const { mount } = app;
  app.mount = (containerOrSelector) => {
    const container = normalizeContainer(containerOrSelector);
    if (!container)
      return;
    const component = app._component;
    if (!isFunction(component) && !component.render && !component.template) {
      component.template = container.innerHTML;
    }
    container.innerHTML = "";
    const proxy = mount(container, false, container instanceof SVGElement);
    if (container instanceof Element) {
      container.removeAttribute("v-cloak");
      container.setAttribute("data-v-app", "");
    }
    return proxy;
  };
  return app;
};
function normalizeContainer(container) {
  if (isString(container)) {
    const res = document.querySelector(container);
    return res;
  }
  return container;
}
var extendStatics = function(d, b) {
  extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
    d2.__proto__ = b2;
  } || function(d2, b2) {
    for (var p2 in b2)
      if (Object.prototype.hasOwnProperty.call(b2, p2))
        d2[p2] = b2[p2];
  };
  return extendStatics(d, b);
};
function __extends(d, b) {
  if (typeof b !== "function" && b !== null)
    throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  extendStatics(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign$1 = function() {
  __assign$1 = Object.assign || function __assign2(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p2 in s)
        if (Object.prototype.hasOwnProperty.call(s, p2))
          t[p2] = s[p2];
    }
    return t;
  };
  return __assign$1.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _ = { label: 0, sent: function() {
    if (t[0] & 1)
      throw t[1];
    return t[1];
  }, trys: [], ops: [] }, f, y, t, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n) {
    return function(v) {
      return step([n, v]);
    };
  }
  function step(op) {
    if (f)
      throw new TypeError("Generator is already executing.");
    while (_)
      try {
        if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
          return t;
        if (y = 0, t)
          op = [op[0] & 2, t.value];
        switch (op[0]) {
          case 0:
          case 1:
            t = op;
            break;
          case 4:
            _.label++;
            return { value: op[1], done: false };
          case 5:
            _.label++;
            y = op[1];
            op = [0];
            continue;
          case 7:
            op = _.ops.pop();
            _.trys.pop();
            continue;
          default:
            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _ = 0;
              continue;
            }
            if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
              _.label = op[1];
              break;
            }
            if (op[0] === 6 && _.label < t[1]) {
              _.label = t[1];
              t = op;
              break;
            }
            if (t && _.label < t[2]) {
              _.label = t[2];
              _.ops.push(op);
              break;
            }
            if (t[2])
              _.ops.pop();
            _.trys.pop();
            continue;
        }
        op = body.call(thisArg, _);
      } catch (e) {
        op = [6, e];
        y = 0;
      } finally {
        f = t = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __values(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  if (m)
    return m.call(o);
  if (o && typeof o.length === "number")
    return {
      next: function() {
        if (o && i >= o.length)
          o = void 0;
        return { value: o && o[i++], done: !o };
      }
    };
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m)
    return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
      ar.push(r.value);
  } catch (error) {
    e = { error };
  } finally {
    try {
      if (r && !r.done && (m = i["return"]))
        m.call(i);
    } finally {
      if (e)
        throw e.error;
    }
  }
  return ar;
}
function __spreadArray(to, from, pack) {
  if (pack || arguments.length === 2)
    for (var i = 0, l = from.length, ar; i < l; i++) {
      if (ar || !(i in from)) {
        if (!ar)
          ar = Array.prototype.slice.call(from, 0, i);
        ar[i] = from[i];
      }
    }
  return to.concat(ar || Array.prototype.slice.call(from));
}
var PREFERRED_LANGUAGES_LOCAL_STORAGE_KEY = "__tolgee_preferredLanguages";
var CURRENT_LANGUAGE_LOCAL_STORAGE_KEY = "__tolgee_currentLanguage";
var Properties = function() {
  function Properties2() {
  }
  Object.defineProperty(Properties2.prototype, "currentLanguage", {
    get: function() {
      var _a2;
      if ((_a2 = this.config) === null || _a2 === void 0 ? void 0 : _a2.forceLanguage) {
        return this.config.forceLanguage;
      }
      if (!this._currentLanguage) {
        this._currentLanguage = this.getInitialLanguage();
      }
      return this._currentLanguage;
    },
    set: function(language) {
      var _a2;
      if (!language) {
        throw new Error("Setting invalid language value ".concat(language));
      }
      this._currentLanguage = language;
      if (((_a2 = this.config) === null || _a2 === void 0 ? void 0 : _a2.enableLanguageStore) && typeof localStorage !== "undefined") {
        localStorage.setItem(CURRENT_LANGUAGE_LOCAL_STORAGE_KEY, language);
      }
    },
    enumerable: false,
    configurable: true
  });
  Object.defineProperty(Properties2.prototype, "preferredLanguages", {
    get: function() {
      return new Set(JSON.parse(localStorage.getItem(PREFERRED_LANGUAGES_LOCAL_STORAGE_KEY)));
    },
    set: function(languages) {
      localStorage.setItem(PREFERRED_LANGUAGES_LOCAL_STORAGE_KEY, JSON.stringify(Array.from(languages)));
    },
    enumerable: false,
    configurable: true
  });
  Properties2.prototype.getInitialLanguage = function() {
    if (this.config.enableLanguageStore) {
      var storedLanguage = this.getStoredLanguage();
      if (storedLanguage) {
        return storedLanguage;
      }
    }
    if (this.config.enableLanguageDetection) {
      var detectedLanguage = this.getLanguageByNavigator();
      if (detectedLanguage) {
        return detectedLanguage;
      }
    }
    return this.config.defaultLanguage;
  };
  Properties2.prototype.getStoredLanguage = function() {
    if (typeof localStorage !== "undefined") {
      var storedLanguage = localStorage.getItem(CURRENT_LANGUAGE_LOCAL_STORAGE_KEY);
      if (!this.config.availableLanguages) {
        return storedLanguage;
      }
      var isSavedLanguageAvailable = this.config.availableLanguages.indexOf(storedLanguage) > -1;
      if (isSavedLanguageAvailable) {
        return storedLanguage;
      }
    }
  };
  Properties2.prototype.getLanguageByNavigator = function() {
    if (typeof window !== "undefined" && this.config.availableLanguages) {
      var preferred_1 = window.navigator.language;
      var exactMatch = this.config.availableLanguages.find(function(l) {
        return l === preferred_1;
      });
      if (exactMatch) {
        return exactMatch;
      }
      var getTwoLetters_1 = function(fullTag) {
        return fullTag.replace(/^(.+?)(-.*)?$/, "$1");
      };
      var preferredTwoLetter_1 = getTwoLetters_1(window.navigator.language);
      var twoLetterMatch = this.config.availableLanguages.find(function(l) {
        return getTwoLetters_1(l) === preferredTwoLetter_1;
      });
      if (twoLetterMatch) {
        return twoLetterMatch;
      }
    }
  };
  return Properties2;
}();
var Subscription = function() {
  function Subscription2(onUnsubscribe) {
    this.onUnsubscribe = onUnsubscribe;
  }
  Subscription2.prototype.unsubscribe = function() {
    this.onUnsubscribe();
  };
  return Subscription2;
}();
var EventEmitterImpl = function() {
  function EventEmitterImpl2() {
    this.idCounter = 0;
    this._subscriptions = /* @__PURE__ */ new Map();
  }
  Object.defineProperty(EventEmitterImpl2.prototype, "subscriptions", {
    get: function() {
      return this._subscriptions;
    },
    enumerable: false,
    configurable: true
  });
  EventEmitterImpl2.prototype.emit = function(data) {
    var e_1, _a2;
    var promiseReturns = [];
    try {
      for (var _b = __values(this.subscriptions.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
        var callback = _c.value;
        var returned = callback(data);
        if (typeof (returned === null || returned === void 0 ? void 0 : returned["then"]) === "function") {
          promiseReturns.push(returned);
        }
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (_c && !_c.done && (_a2 = _b.return))
          _a2.call(_b);
      } finally {
        if (e_1)
          throw e_1.error;
      }
    }
    if (promiseReturns.length === 0) {
      return;
    }
    return new Promise(function(resolve) {
      return Promise.all(promiseReturns).then(function() {
        return resolve();
      });
    });
  };
  EventEmitterImpl2.prototype.subscribe = function(callback) {
    var _this = this;
    var newId = this.idCounter++;
    var subscription = new Subscription(function() {
      return _this.unsubscribe(newId);
    });
    this.subscriptions.set(newId, callback);
    return subscription;
  };
  EventEmitterImpl2.prototype.unsubscribe = function(id) {
    var wasPresent = this._subscriptions.delete(id);
    if (!wasPresent) {
      console.warn("Event to unsubscribe was not found");
    }
  };
  return EventEmitterImpl2;
}();
var EventService = function() {
  function EventService2() {
    this.TRANSLATION_CHANGED = new EventEmitterImpl();
    this.LANGUAGE_CHANGED = new EventEmitterImpl();
    this.LANGUAGE_LOADED = new EventEmitterImpl();
    this.ELEMENT_REGISTERED = new EventEmitterImpl();
  }
  return EventService2;
}();
var ApiHttpError = function(_super) {
  __extends(ApiHttpError2, _super);
  function ApiHttpError2(response, code) {
    var _this = _super.call(this, "Api http error") || this;
    _this.response = response;
    _this.code = code;
    Object.setPrototypeOf(_this, ApiHttpError2.prototype);
    return _this;
  }
  return ApiHttpError2;
}(Error);
var ApiHttpService = function() {
  function ApiHttpService2(properties) {
    this.properties = properties;
  }
  ApiHttpService2.handleErrors = function(response) {
    return __awaiter(this, void 0, void 0, function() {
      var error, data;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            if (!(response.status >= 400))
              return [3, 5];
            error = new ApiHttpError(response);
            _a2.label = 1;
          case 1:
            _a2.trys.push([1, 3, , 4]);
            return [4, response.json()];
          case 2:
            data = _a2.sent();
            error.code = data.code;
            return [3, 4];
          case 3:
            _a2.sent();
            console.warn("Tolgee server responded with invalid status code.");
            return [3, 4];
          case 4:
            throw error;
          case 5:
            return [2, response];
        }
      });
    });
  };
  ApiHttpService2.prototype.fetch = function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    return __awaiter(this, void 0, void 0, function() {
      var _a2, url, rest;
      return __generator(this, function(_b) {
        if (typeof args[0] === "object") {
          return [2, fetch(__assign$1(__assign$1({}, args[0]), { url: this.getUrl(args[0].url) })).then(function(r) {
            return ApiHttpService2.handleErrors(r);
          })];
        }
        _a2 = __read(args), url = _a2[0], rest = _a2.slice(1);
        return [2, fetch.apply(void 0, __spreadArray([this.getUrl(url)], __read(rest), false)).then(function(r) {
          return ApiHttpService2.handleErrors(r);
        })];
      });
    });
  };
  ApiHttpService2.prototype.fetchJson = function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    return __awaiter(this, void 0, void 0, function() {
      return __generator(this, function(_a2) {
        return [2, this.fetch.apply(this, __spreadArray([], __read(args), false)).then(function(res) {
          return res.json();
        })];
      });
    });
  };
  ApiHttpService2.prototype.post = function(url, body, init) {
    if (init === void 0) {
      init = {};
    }
    var rest = [];
    for (var _i = 3; _i < arguments.length; _i++) {
      rest[_i - 3] = arguments[_i];
    }
    return __awaiter(this, void 0, void 0, function() {
      return __generator(this, function(_a2) {
        return [2, this.fetch.apply(this, __spreadArray([url, __assign$1({ body: JSON.stringify(body), method: "POST", headers: {
          "Content-Type": "application/json"
        } }, init)], __read(rest), false))];
      });
    });
  };
  ApiHttpService2.prototype.postJson = function(url, body, init) {
    if (init === void 0) {
      init = {};
    }
    var rest = [];
    for (var _i = 3; _i < arguments.length; _i++) {
      rest[_i - 3] = arguments[_i];
    }
    return __awaiter(this, void 0, void 0, function() {
      return __generator(this, function(_a2) {
        return [2, this.post.apply(this, __spreadArray([url, body, init], __read(rest), false)).then(function(res) {
          return res.json();
        })];
      });
    });
  };
  ApiHttpService2.prototype.getUrl = function(path) {
    var querySeparator = path.indexOf("?") < 0 ? "?" : "&";
    return "".concat(this.properties.config.apiUrl, "/").concat(path).concat(querySeparator, "ak=").concat(this.properties.config.apiKey);
  };
  return ApiHttpService2;
}();
var TranslationData = function() {
  function TranslationData2(key, translations, id) {
    this.key = key;
    this.translations = translations;
    this.id = id;
  }
  return TranslationData2;
}();
var TranslationService = function() {
  function TranslationService2(properties, coreService, apiHttpService, eventService) {
    var _this = this;
    this.properties = properties;
    this.coreService = coreService;
    this.apiHttpService = apiHttpService;
    this.eventService = eventService;
    this.translationsCache = /* @__PURE__ */ new Map();
    this.fetchPromises = {};
    this.fetchedDev = {};
    this.updateTranslationInCache = function(data) {
      return __awaiter(_this, void 0, void 0, function() {
        var result;
        var _this2 = this;
        return __generator(this, function(_a2) {
          switch (_a2.label) {
            case 0:
              result = {};
              Object.entries(data.translations).forEach(function(_a3) {
                var _b = __read(_a3, 2), lang = _b[0], translation = _b[1];
                var cachedData = _this2.translationsCache.get(lang);
                if (cachedData) {
                  cachedData[data.name] = translation.text;
                }
                result[lang] = translation.text;
              });
              return [4, this.eventService.TRANSLATION_CHANGED.emit(new TranslationData(data.name, result, data.id))];
            case 1:
              _a2.sent();
              return [2];
          }
        });
      });
    };
    this.getTranslationsOfKey = function(key, languages) {
      if (languages === void 0) {
        languages = /* @__PURE__ */ new Set([_this.properties.currentLanguage]);
      }
      return __awaiter(_this, void 0, void 0, function() {
        var languagesArray, languagesQuery, data, translationData_1, firstItem, langs, e_1, _a2;
        var _b, _c, _d;
        return __generator(this, function(_e) {
          switch (_e.label) {
            case 0:
              this.coreService.checkScope("translations.view");
              _e.label = 1;
            case 1:
              _e.trys.push([1, 3, , 7]);
              languagesArray = __spreadArray([], __read(languages), false);
              languagesQuery = languagesArray.map(function(l) {
                return "languages=".concat(l);
              }).join("&");
              return [4, this.apiHttpService.fetchJson("v2/projects/translations?".concat(languagesQuery, "&filterKeyName=").concat(encodeURIComponent(key)))];
            case 2:
              data = _e.sent();
              translationData_1 = languagesArray.reduce(function(acc, curr) {
                var _a3;
                return __assign$1(__assign$1({}, acc), (_a3 = {}, _a3[curr] = "", _a3));
              }, {});
              firstItem = (_c = (_b = data._embedded) === null || _b === void 0 ? void 0 : _b.keys) === null || _c === void 0 ? void 0 : _c[0];
              if (firstItem === null || firstItem === void 0 ? void 0 : firstItem.translations) {
                Object.entries(firstItem.translations).forEach(function(_a3) {
                  var _b2 = __read(_a3, 2), language = _b2[0], translation = _b2[1];
                  return translationData_1[language] = translation.text;
                });
              }
              langs = (_d = data.selectedLanguages) === null || _d === void 0 ? void 0 : _d.map(function(l) {
                return l.tag;
              });
              return [2, [firstItem, langs]];
            case 3:
              e_1 = _e.sent();
              if (!(e_1 instanceof ApiHttpError && e_1.response.status === 404 && e_1.code === "language_not_found"))
                return [3, 5];
              _a2 = this.properties;
              return [4, this.coreService.getLanguages()];
            case 4:
              _a2.preferredLanguages = _e.sent();
              console.error("Requested language not found, refreshing the page!");
              location.reload();
              return [3, 6];
            case 5:
              throw e_1;
            case 6:
              return [3, 7];
            case 7:
              return [2];
          }
        });
      });
    };
  }
  TranslationService2.translationByValue = function(message, defaultValue) {
    if (message) {
      return message;
    }
    if (defaultValue) {
      return defaultValue;
    }
    return void 0;
  };
  TranslationService2.prototype.initStatic = function() {
    var _this = this;
    var _a2;
    if (typeof ((_a2 = this.properties.config) === null || _a2 === void 0 ? void 0 : _a2.staticData) === "object") {
      Object.entries(this.properties.config.staticData).forEach(function(_a3) {
        var _b = __read(_a3, 2), language = _b[0], data = _b[1];
        if (typeof data !== "function") {
          _this.setLanguageData(language, data);
        }
      });
    }
  };
  TranslationService2.prototype.getCachedTranslations = function() {
    return this.translationsCache;
  };
  TranslationService2.prototype.loadTranslations = function(lang) {
    if (lang === void 0) {
      lang = this.properties.currentLanguage;
    }
    return __awaiter(this, void 0, void 0, function() {
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            if (!this.isFetchNeeded(lang))
              return [3, 2];
            if (!(this.fetchPromises[lang] instanceof Promise)) {
              this.fetchPromises[lang] = this.fetchTranslations(lang);
            }
            return [4, this.fetchPromises[lang]];
          case 1:
            _a2.sent();
            this.eventService.LANGUAGE_LOADED.emit(lang);
            _a2.label = 2;
          case 2:
            this.fetchPromises[lang] = void 0;
            return [2, this.translationsCache.get(lang)];
        }
      });
    });
  };
  TranslationService2.prototype.getTranslation = function(key, lang, defaultValue) {
    if (lang === void 0) {
      lang = this.properties.currentLanguage;
    }
    return __awaiter(this, void 0, void 0, function() {
      var message, fallbackLang;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            if (!this.isFetchNeeded(lang))
              return [3, 2];
            return [4, this.loadTranslations(lang)];
          case 1:
            _a2.sent();
            _a2.label = 2;
          case 2:
            message = this.getFromCache(key, lang);
            if (!!message)
              return [3, 5];
            fallbackLang = this.properties.config.fallbackLanguage;
            if (!this.isFetchNeeded(fallbackLang))
              return [3, 4];
            return [4, this.loadTranslations(this.properties.config.fallbackLanguage)];
          case 3:
            _a2.sent();
            _a2.label = 4;
          case 4:
            message = this.getFromCache(key, this.properties.config.fallbackLanguage);
            _a2.label = 5;
          case 5:
            return [2, TranslationService2.translationByValue(message, defaultValue)];
        }
      });
    });
  };
  TranslationService2.prototype.updateKeyComplex = function(id, data) {
    var _a2, _b;
    return __awaiter(this, void 0, void 0, function() {
      var result;
      return __generator(this, function(_c) {
        switch (_c.label) {
          case 0:
            this.coreService.checkScope("translations.edit");
            return [4, this.apiHttpService.postJson("v2/projects/keys/".concat(id, "/complex-update"), __assign$1(__assign$1({}, data), { screenshotUploadedImageIds: ((_a2 = data.screenshotUploadedImageIds) === null || _a2 === void 0 ? void 0 : _a2.length) ? data.screenshotUploadedImageIds : void 0, screenshotIdsToDelete: ((_b = data.screenshotIdsToDelete) === null || _b === void 0 ? void 0 : _b.length) ? data.screenshotIdsToDelete : void 0 }), { method: "put" })];
          case 1:
            result = _c.sent();
            return [4, this.updateTranslationInCache(result)];
          case 2:
            _c.sent();
            return [2, result];
        }
      });
    });
  };
  TranslationService2.prototype.createKey = function(data) {
    var _a2;
    return __awaiter(this, void 0, void 0, function() {
      var result;
      return __generator(this, function(_b) {
        switch (_b.label) {
          case 0:
            this.coreService.checkScope("keys.edit");
            return [4, this.apiHttpService.postJson("v2/projects/keys/create", __assign$1(__assign$1({}, data), { screenshotUploadedImageIds: ((_a2 = data.screenshotUploadedImageIds) === null || _a2 === void 0 ? void 0 : _a2.length) ? data.screenshotUploadedImageIds : void 0 }))];
          case 1:
            result = _b.sent();
            return [4, this.updateTranslationInCache(result)];
          case 2:
            _b.sent();
            return [2, result];
        }
      });
    });
  };
  TranslationService2.prototype.setTranslations = function(translationData) {
    return __awaiter(this, void 0, void 0, function() {
      var result;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            this.coreService.checkScope("translations.edit");
            return [4, this.apiHttpService.postJson("v2/projects/translations", translationData)];
          case 1:
            result = _a2.sent();
            return [4, this.updateTranslationInCache({
              id: result.keyId,
              name: result.keyName,
              translations: result.translations
            })];
          case 2:
            _a2.sent();
            return [2, result];
        }
      });
    });
  };
  TranslationService2.prototype.changeTranslations = function(_a2) {
    var key = _a2.key, translations = _a2.translations;
    return __awaiter(this, void 0, void 0, function() {
      var old;
      var _this = this;
      return __generator(this, function(_b) {
        switch (_b.label) {
          case 0:
            old = {};
            Object.entries(translations).forEach(function(_a3) {
              var _b2 = __read(_a3, 2), language = _b2[0], value = _b2[1];
              var data = _this.translationsCache.get(language);
              if (data) {
                old[language] = data[key];
                data[key] = value;
              }
            });
            return [4, this.eventService.TRANSLATION_CHANGED.emit({
              key,
              translations
            })];
          case 1:
            _b.sent();
            return [2, function() {
              return __awaiter(_this, void 0, void 0, function() {
                var _this2 = this;
                return __generator(this, function(_a3) {
                  switch (_a3.label) {
                    case 0:
                      Object.entries(old).forEach(function(_a4) {
                        var _b2 = __read(_a4, 2), language = _b2[0], value = _b2[1];
                        var data = _this2.translationsCache.get(language);
                        if (data) {
                          data[key] = value;
                        }
                      });
                      return [4, this.eventService.TRANSLATION_CHANGED.emit({
                        key,
                        translations: old
                      })];
                    case 1:
                      _a3.sent();
                      return [2];
                  }
                });
              });
            }];
        }
      });
    });
  };
  TranslationService2.prototype.getFromCacheOrFallback = function(key, lang, defaultValue) {
    if (lang === void 0) {
      lang = this.properties.currentLanguage;
    }
    var fallbackLang = this.properties.config.fallbackLanguage;
    var message = this.getFromCache(key, lang) || this.getFromCache(key, fallbackLang);
    if (!message && (!this.isLoaded(lang) || !this.isLoaded(fallbackLang))) {
      return void 0;
    }
    return TranslationService2.translationByValue(message, defaultValue);
  };
  TranslationService2.prototype.isFetchNeeded = function(lang) {
    var isDevMode = this.properties.mode === "development";
    var dataPresent = this.translationsCache.get(lang) !== void 0;
    var devFetched = Boolean(this.fetchedDev[lang]);
    return isDevMode && !devFetched || !dataPresent;
  };
  TranslationService2.prototype.isLoaded = function(lang) {
    return this.translationsCache.get(lang) !== void 0;
  };
  TranslationService2.prototype.fetchTranslations = function(lang) {
    return __awaiter(this, void 0, void 0, function() {
      var isDevMode;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            isDevMode = this.properties.mode === "development";
            if (!isDevMode)
              return [3, 2];
            return [4, this.fetchTranslationsDevelopment(lang)];
          case 1:
            return [2, _a2.sent()];
          case 2:
            return [4, this.fetchTranslationsProduction(lang)];
          case 3:
            return [2, _a2.sent()];
        }
      });
    });
  };
  TranslationService2.prototype.fetchTranslationsProduction = function(language) {
    var _a2, _b;
    return __awaiter(this, void 0, void 0, function() {
      var langStaticData, data, url, result, data;
      return __generator(this, function(_c) {
        switch (_c.label) {
          case 0:
            langStaticData = (_b = (_a2 = this.properties.config) === null || _a2 === void 0 ? void 0 : _a2.staticData) === null || _b === void 0 ? void 0 : _b[language];
            if (!(typeof langStaticData === "function"))
              return [3, 2];
            return [4, langStaticData()];
          case 1:
            data = _c.sent();
            this.setLanguageData(language, data);
            return [2];
          case 2:
            if (langStaticData !== void 0) {
              this.setLanguageData(language, langStaticData);
              return [2];
            }
            _c.label = 3;
          case 3:
            url = "".concat(this.properties.config.filesUrlPrefix || "/").concat(language, ".json");
            _c.label = 4;
          case 4:
            _c.trys.push([4, 10, , 11]);
            return [4, fetch(url)];
          case 5:
            result = _c.sent();
            if (result.status >= 400) {
              console.error("Server responded with error status while loading localization data.");
              this.setLanguageData(language, {});
              return [2];
            }
            _c.label = 6;
          case 6:
            _c.trys.push([6, 8, , 9]);
            return [4, result.json()];
          case 7:
            data = _c.sent();
            this.setLanguageData(language, data);
            return [3, 9];
          case 8:
            _c.sent();
            console.error("Error parsing json retrieved from ".concat(url, "."));
            this.setEmptyLanguageData(language);
            return [3, 9];
          case 9:
            return [3, 11];
          case 10:
            _c.sent();
            console.error("Error fetching localization data from ".concat(url, "."));
            this.setEmptyLanguageData(language);
            return [3, 11];
          case 11:
            return [2];
        }
      });
    });
  };
  TranslationService2.prototype.fetchTranslationsDevelopment = function(language) {
    return __awaiter(this, void 0, void 0, function() {
      var data, e_4;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            return [4, this.coreService.loadApiKeyDetails()];
          case 1:
            _a2.sent();
            this.coreService.checkScope("translations.view");
            _a2.label = 2;
          case 2:
            _a2.trys.push([2, 4, , 5]);
            return [4, this.apiHttpService.fetchJson("v2/projects/translations/".concat(language))];
          case 3:
            data = _a2.sent();
            this.fetchedDev[language] = true;
            this.setLanguageData(language, data[language] || {});
            return [3, 5];
          case 4:
            e_4 = _a2.sent();
            console.error("Error while fetching localization data from API.", e_4);
            this.setEmptyLanguageData(language);
            return [2];
          case 5:
            return [2];
        }
      });
    });
  };
  TranslationService2.prototype.setEmptyLanguageData = function(language) {
    this.translationsCache.set(language, {});
  };
  TranslationService2.prototype.setLanguageData = function(language, data) {
    var makeFlat = function(data2) {
      var result = {};
      Object.entries(data2).forEach(function(_a2) {
        var _b = __read(_a2, 2), key = _b[0], value = _b[1];
        if (!value) {
          return;
        }
        if (typeof value === "object") {
          Object.entries(makeFlat(value)).forEach(function(_a3) {
            var _b2 = __read(_a3, 2), flatKey = _b2[0], flatValue = _b2[1];
            result[key + "." + flatKey] = flatValue;
          });
          return;
        }
        result[key] = value;
      });
      return result;
    };
    this.translationsCache.set(language, makeFlat(data));
  };
  TranslationService2.prototype.getFromCache = function(key, lang) {
    if (lang === void 0) {
      lang = this.properties.currentLanguage;
    }
    var root = this.translationsCache.get(lang);
    if (root === void 0) {
      return void 0;
    }
    return root[key];
  };
  return TranslationService2;
}();
var TextService = function() {
  function TextService2(properties, translationService, moduleService) {
    var _this = this;
    this.properties = properties;
    this.translationService = translationService;
    this.moduleService = moduleService;
    this.format = function(translation, params, lang) {
      try {
        var result = translation;
        if (_this.moduleService.formatter) {
          result = _this.moduleService.formatter.format({
            translation: result,
            params,
            language: lang || _this.properties.currentLanguage
          });
        }
        return result;
      } catch (e) {
        console.error(e);
      }
    };
  }
  TextService2.prototype.translate = function(key, params, lang, orEmpty, defaultValue) {
    if (lang === void 0) {
      lang = this.properties.currentLanguage;
    }
    return __awaiter(this, void 0, void 0, function() {
      var translation;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            return [4, this.translationService.getTranslation(key, lang, defaultValue)];
          case 1:
            translation = _a2.sent();
            return [2, this.formatTranslation(key, translation, params, lang, orEmpty)];
        }
      });
    });
  };
  TextService2.prototype.instant = function(key, params, lang, orEmpty, defaultValue) {
    if (lang === void 0) {
      lang = this.properties.currentLanguage;
    }
    var translation = this.translationService.getFromCacheOrFallback(key, lang, defaultValue);
    return this.formatTranslation(key, translation, params, lang, orEmpty);
  };
  TextService2.prototype.formatTranslation = function(key, translation, params, lang, orEmpty) {
    if (translation !== void 0) {
      return this.format(translation, params, lang);
    }
    if (!orEmpty) {
      return key;
    }
    return "";
  };
  return TextService2;
}();
var ModifierKey;
(function(ModifierKey2) {
  ModifierKey2[ModifierKey2["Alt"] = 0] = "Alt";
  ModifierKey2[ModifierKey2["Control"] = 1] = "Control";
  ModifierKey2[ModifierKey2["Shift"] = 2] = "Shift";
  ModifierKey2[ModifierKey2["Meta"] = 3] = "Meta";
})(ModifierKey || (ModifierKey = {}));
var RESTRICTED_ASCENDANT_ATTRIBUTE = "data-tolgee-restricted";
var TOLGEE_ATTRIBUTE_NAME = "_tolgee";
var TOLGEE_TARGET_ATTRIBUTE = "_tolgee-target";
var TOLGEE_WRAPPED_ONLY_DATA_ATTRIBUTE = "data-tolgee-key-only";
var TOLGEE_HIGHLIGHTER_CLASS = "_tolgee-highlighter";
var DEVTOOLS_ID = "__tolgee_dev_tools";
var eCapture = {
  capture: true
};
var ePassive = {
  capture: true,
  passive: true
};
var MouseEventHandler = function() {
  function MouseEventHandler2(dependencies) {
    var _this = this;
    this.dependencies = dependencies;
    this.keysDown = /* @__PURE__ */ new Set();
    this.mouseOnChanged = new EventEmitterImpl();
    this.keysChanged = new EventEmitterImpl();
    this.highlight = function(el) {
      if (_this.highlighted !== el) {
        _this.unhighlight();
        if (el) {
          el._tolgee.preventClean = true;
          el._tolgee.highlight();
          _this.highlighted = el;
          _this.mouseOnChanged.emit(el);
        }
      }
    };
    this.unhighlight = function() {
      if (_this.highlighted) {
        _this.highlighted._tolgee.preventClean = false;
        _this.highlighted._tolgee.unhighlight();
        _this.highlighted = void 0;
        _this.mouseOnChanged.emit(_this.highlighted);
      }
    };
    this.blockEvents = function(e) {
      if (_this.areKeysDown() && !_this.isInUiDialog(e.target)) {
        e.stopPropagation();
        e.preventDefault();
      }
    };
    this.onMouseMove = function(e) {
      _this.updateCursorPosition({ x: e.clientX, y: e.clientY });
    };
    this.onBlur = function() {
      _this.keysDown = /* @__PURE__ */ new Set();
      _this.keysChanged.emit(_this.areKeysDown());
      _this.updateHighlight();
    };
    this.onKeyDown = function(e) {
      var modifierKey = ModifierKey[e.key];
      if (modifierKey !== void 0) {
        _this.keysDown.add(modifierKey);
        _this.keysChanged.emit(_this.areKeysDown());
      }
      _this.updateHighlight();
    };
    this.onKeyUp = function(e) {
      _this.keysDown.delete(ModifierKey[e.key]);
      _this.keysChanged.emit(_this.areKeysDown());
      _this.updateHighlight();
    };
    this.onScroll = function() {
      var _a2;
      (_a2 = _this.highlighted) === null || _a2 === void 0 ? void 0 : _a2._tolgee.highlight();
    };
    this.onClick = function(e) {
      _this.blockEvents(e);
      if (_this.areKeysDown()) {
        var element = _this.getClosestTolgeeElement(e.target);
        if (element && element === _this.highlighted) {
          _this.dependencies.translationHighlighter.translationEdit(e, element);
          _this.unhighlight();
        }
      }
    };
  }
  MouseEventHandler2.prototype.run = function() {
    if (typeof window !== "undefined") {
      this.initEventListeners();
    }
  };
  MouseEventHandler2.prototype.stop = function() {
    if (typeof window !== "undefined") {
      this.removeEventListeners();
    }
  };
  MouseEventHandler2.prototype.updateHighlight = function() {
    var position = this.cursorPosition;
    var newHighlighted;
    if (position && this.areKeysDown()) {
      newHighlighted = this.getClosestTolgeeElement(document.elementFromPoint(position.x, position.y));
    }
    this.highlight(newHighlighted);
  };
  MouseEventHandler2.prototype.updateCursorPosition = function(position) {
    this.cursorPosition = position;
    this.updateHighlight();
  };
  MouseEventHandler2.prototype.initEventListeners = function() {
    window.addEventListener("blur", this.onBlur, eCapture);
    window.addEventListener("keydown", this.onKeyDown, eCapture);
    window.addEventListener("keyup", this.onKeyUp, eCapture);
    window.addEventListener("mousemove", this.onMouseMove, ePassive);
    window.addEventListener("scroll", this.onScroll, ePassive);
    window.addEventListener("click", this.onClick, eCapture);
    window.addEventListener("mouseenter", this.blockEvents, eCapture);
    window.addEventListener("mouseover", this.blockEvents, eCapture);
    window.addEventListener("mouseout", this.blockEvents, eCapture);
    window.addEventListener("mouseleave", this.blockEvents, eCapture);
    window.addEventListener("mousedown", this.blockEvents, eCapture);
    window.addEventListener("mouseup", this.blockEvents, eCapture);
  };
  MouseEventHandler2.prototype.removeEventListeners = function() {
    window.removeEventListener("blur", this.onBlur, eCapture);
    window.removeEventListener("keydown", this.onKeyDown, eCapture);
    window.removeEventListener("keyup", this.onKeyUp, eCapture);
    window.removeEventListener("mousemove", this.onMouseMove, ePassive);
    window.removeEventListener("scroll", this.onScroll, ePassive);
    window.removeEventListener("click", this.onClick, eCapture);
    window.removeEventListener("mouseenter", this.blockEvents, eCapture);
    window.removeEventListener("mouseover", this.blockEvents, eCapture);
    window.removeEventListener("mouseout", this.blockEvents, eCapture);
    window.removeEventListener("mouseleave", this.blockEvents, eCapture);
    window.removeEventListener("mousedown", this.blockEvents, eCapture);
    window.removeEventListener("mouseup", this.blockEvents, eCapture);
  };
  MouseEventHandler2.prototype.isInUiDialog = function(element) {
    return Boolean(this.findAncestor(element, function(el) {
      return el.id === DEVTOOLS_ID;
    }));
  };
  MouseEventHandler2.prototype.getClosestTolgeeElement = function(element) {
    return this.findAncestor(element, function(el) {
      return el === null || el === void 0 ? void 0 : el._tolgee;
    });
  };
  MouseEventHandler2.prototype.findAncestor = function(element, func) {
    if (func(element)) {
      return element;
    }
    if (element === null || element === void 0 ? void 0 : element.parentElement) {
      return this.findAncestor(element.parentElement, func);
    }
    return void 0;
  };
  MouseEventHandler2.prototype.areKeysDown = function() {
    var e_1, _a2;
    try {
      for (var _b = __values(this.dependencies.properties.config.highlightKeys), _c = _b.next(); !_c.done; _c = _b.next()) {
        var key = _c.value;
        if (!this.keysDown.has(key)) {
          return false;
        }
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (_c && !_c.done && (_a2 = _b.return))
          _a2.call(_b);
      } finally {
        if (e_1)
          throw e_1.error;
      }
    }
    return true;
  };
  return MouseEventHandler2;
}();
var TranslationHighlighter = function() {
  function TranslationHighlighter2(dependencies) {
    var _this = this;
    this.dependencies = dependencies;
    this.translationEdit = function(e, element) {
      return __awaiter(_this, void 0, void 0, function() {
        var renderer2, key;
        return __generator(this, function(_a2) {
          switch (_a2.label) {
            case 0:
              return [4, this.getRenderer()];
            case 1:
              renderer2 = _a2.sent();
              if (!(typeof renderer2 === "object"))
                return [3, 3];
              return [4, this.getKeyAndDefault(e, element)];
            case 2:
              key = _a2.sent();
              if (key) {
                renderer2.renderViewer(key.key, key.defaultValue);
                return [2];
              }
              return [2];
            case 3:
              return [2];
          }
        });
      });
    };
  }
  TranslationHighlighter2.getKeyOptions = function(node) {
    var nodes = Array.from(node._tolgee.nodes);
    return nodes.reduce(function(acc, curr) {
      return __spreadArray(__spreadArray([], __read(acc), false), __read(curr._tolgee.keys.map(function(k) {
        return {
          key: k.key,
          defaultValue: k.defaultValue
        };
      })), false);
    }, []);
  };
  TranslationHighlighter2.prototype.listen = function(element) {
    this.dependencies.highlightFunctionInitializer.initFunctions(element);
  };
  TranslationHighlighter2.prototype.getRenderer = function() {
    return __awaiter(this, void 0, void 0, function() {
      var possibleProviders, possibleProviders_1, possibleProviders_1_1, possiblePromise, possibleObject, _a2, possibleProvider, e_1_1;
      var e_1, _b;
      return __generator(this, function(_c) {
        switch (_c.label) {
          case 0:
            if (!(this._renderer === void 0))
              return [3, 11];
            possibleProviders = [
              this.dependencies.properties.config.ui,
              window["@tolgee/ui"]
            ];
            _c.label = 1;
          case 1:
            _c.trys.push([1, 8, 9, 10]);
            possibleProviders_1 = __values(possibleProviders), possibleProviders_1_1 = possibleProviders_1.next();
            _c.label = 2;
          case 2:
            if (!!possibleProviders_1_1.done)
              return [3, 7];
            possiblePromise = possibleProviders_1_1.value;
            if (!(possiblePromise instanceof Promise))
              return [3, 4];
            return [4, possiblePromise];
          case 3:
            _a2 = _c.sent();
            return [3, 5];
          case 4:
            _a2 = possiblePromise;
            _c.label = 5;
          case 5:
            possibleObject = _a2;
            possibleProvider = typeof possibleObject === "object" ? possibleObject === null || possibleObject === void 0 ? void 0 : possibleObject.UI : possibleObject;
            if (typeof possibleProvider === "function") {
              this._renderer = new possibleProvider(this.dependencies);
              return [3, 7];
            }
            _c.label = 6;
          case 6:
            possibleProviders_1_1 = possibleProviders_1.next();
            return [3, 2];
          case 7:
            return [3, 10];
          case 8:
            e_1_1 = _c.sent();
            e_1 = { error: e_1_1 };
            return [3, 10];
          case 9:
            try {
              if (possibleProviders_1_1 && !possibleProviders_1_1.done && (_b = possibleProviders_1.return))
                _b.call(possibleProviders_1);
            } finally {
              if (e_1)
                throw e_1.error;
            }
            return [7];
          case 10:
            if (this._renderer === void 0) {
              console.warn('Tolgee UI is not provided. To translate interactively provide tolgee ui constructor to "ui" configuration property. To disable highlighting use production mode.');
            }
            _c.label = 11;
          case 11:
            return [2, this._renderer];
        }
      });
    });
  };
  TranslationHighlighter2.prototype.getKeyAndDefault = function(mouseEvent, element) {
    return __awaiter(this, void 0, void 0, function() {
      var keysWithDefaults, keySet, renderer2, selectedKey_1, found;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            if (element._tolgee.wrappedWithElementOnlyKey) {
              return [2, {
                key: element._tolgee.wrappedWithElementOnlyKey,
                defaultValue: element._tolgee.wrappedWithElementOnlyDefaultHtml
              }];
            }
            keysWithDefaults = TranslationHighlighter2.getKeyOptions(element);
            keySet = new Set(keysWithDefaults.map(function(keyWithDefault) {
              return keyWithDefault.key;
            }));
            if (!(keySet.size > 1))
              return [3, 3];
            return [4, this.getRenderer()];
          case 1:
            renderer2 = _a2.sent();
            return [4, renderer2.getKey({
              keys: keySet,
              openEvent: mouseEvent
            })];
          case 2:
            selectedKey_1 = _a2.sent();
            found = keysWithDefaults.find(function(kwd) {
              return kwd.key === selectedKey_1;
            });
            if (found) {
              return [2, found];
            }
            _a2.label = 3;
          case 3:
            if (keySet.size === 1) {
              return [2, keysWithDefaults[0]];
            }
            console.error("No key to translate. This seems like a bug in tolgee.");
            return [2];
        }
      });
    });
  };
  return TranslationHighlighter2;
}();
var NodeHelper = function() {
  function NodeHelper2() {
  }
  NodeHelper2.evaluate = function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    return Array.from(this.evaluateGenerator.apply(this, __spreadArray([], __read(args), false)));
  };
  NodeHelper2.evaluateToSingle = function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    var arr = this.evaluate.apply(this, __spreadArray([], __read(args), false));
    if (arr.length === 1) {
      return arr[0];
    }
    if (arr.length < 1) {
      throw new Error("No element found");
    }
    throw new Error("Multiple elements found");
  };
  NodeHelper2.closestElement = function(node) {
    if (node instanceof Text) {
      return node.parentElement;
    }
    return node;
  };
  NodeHelper2.getParentElement = function(node) {
    if (node.parentElement) {
      return node.parentElement;
    }
    if (node.ownerElement) {
      return node.ownerElement;
    }
  };
  NodeHelper2.isElementTargetElement = function(element) {
    return element.hasAttribute(TOLGEE_TARGET_ATTRIBUTE);
  };
  NodeHelper2.markElementAsTargetElement = function(element) {
    element.setAttribute(TOLGEE_TARGET_ATTRIBUTE, "");
  };
  NodeHelper2.unmarkElementAsTargetElement = function(element) {
    element.removeAttribute(TOLGEE_TARGET_ATTRIBUTE);
  };
  NodeHelper2.nodeContains = function(descendant, node) {
    if (descendant.contains(node)) {
      return true;
    }
    if (node instanceof Attr) {
      var ownerContainsAttr = node.ownerElement && Object.values(node.ownerElement.attributes).indexOf(node) > -1;
      if (descendant.contains(node.ownerElement) && ownerContainsAttr) {
        return true;
      }
    }
    return false;
  };
  NodeHelper2.evaluateGenerator = function(expression, targetNode) {
    var node, evaluated;
    return __generator(this, function(_a2) {
      switch (_a2.label) {
        case 0:
          evaluated = document.evaluate(expression, targetNode, void 0, XPathResult.ANY_TYPE);
          _a2.label = 1;
        case 1:
          if (!((node = evaluated.iterateNext()) !== null))
            return [3, 3];
          return [4, node];
        case 2:
          _a2.sent();
          return [3, 1];
        case 3:
          return [2];
      }
    });
  };
  NodeHelper2.getNodeText = function(node) {
    return node.textContent;
  };
  NodeHelper2.setNodeText = function(node, text) {
    node.textContent = text;
  };
  return NodeHelper2;
}();
var ElementRegistrar = function() {
  function ElementRegistrar2(properties, translationHighlighter, eventService) {
    this.properties = properties;
    this.translationHighlighter = translationHighlighter;
    this.eventService = eventService;
    this.registeredElements = /* @__PURE__ */ new Set();
  }
  ElementRegistrar2.prototype.register = function(element) {
    if (this.getActiveNodes(element).next().value === void 0 && !element._tolgee.wrappedWithElementOnlyKey) {
      return;
    }
    if (this.properties.mode === "development" && !this.registeredElements.has(element)) {
      this.translationHighlighter.listen(element);
    }
    this.registeredElements.add(element);
    this.eventService.ELEMENT_REGISTERED.emit(element);
  };
  ElementRegistrar2.prototype.refreshAll = function() {
    var e_1, _a2;
    try {
      for (var _b = __values(this.registeredElements), _c = _b.next(); !_c.done; _c = _b.next()) {
        var element = _c.value;
        if (!element._tolgee.preventClean) {
          this.cleanElementInactiveNodes(element);
          if (element._tolgee.nodes.size === 0 && !element._tolgee.wrappedWithElementOnlyKey) {
            this.cleanElement(element);
          }
        }
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (_c && !_c.done && (_a2 = _b.return))
          _a2.call(_b);
      } finally {
        if (e_1)
          throw e_1.error;
      }
    }
  };
  ElementRegistrar2.prototype.cleanAll = function() {
    var e_2, _a2;
    try {
      for (var _b = __values(this.registeredElements), _c = _b.next(); !_c.done; _c = _b.next()) {
        var registeredElement = _c.value;
        this.cleanElement(registeredElement);
      }
    } catch (e_2_1) {
      e_2 = { error: e_2_1 };
    } finally {
      try {
        if (_c && !_c.done && (_a2 = _b.return))
          _a2.call(_b);
      } finally {
        if (e_2)
          throw e_2.error;
      }
    }
  };
  ElementRegistrar2.prototype.findAllByKey = function(key) {
    var e_3, _a2, e_4, _b;
    var result = [];
    try {
      for (var _c = __values(this.registeredElements), _d = _c.next(); !_d.done; _d = _c.next()) {
        var registeredElement = _d.value;
        if (registeredElement._tolgee.wrappedWithElementOnlyKey === key) {
          result.push(registeredElement);
          continue;
        }
        try {
          for (var _e = (e_4 = void 0, __values(registeredElement._tolgee.nodes)), _f = _e.next(); !_f.done; _f = _e.next()) {
            var node = _f.value;
            if (node._tolgee.keys.findIndex(function(keyWithParams) {
              return keyWithParams.key === key;
            }) > -1) {
              result.push(registeredElement);
              break;
            }
          }
        } catch (e_4_1) {
          e_4 = { error: e_4_1 };
        } finally {
          try {
            if (_f && !_f.done && (_b = _e.return))
              _b.call(_e);
          } finally {
            if (e_4)
              throw e_4.error;
          }
        }
      }
    } catch (e_3_1) {
      e_3 = { error: e_3_1 };
    } finally {
      try {
        if (_d && !_d.done && (_a2 = _c.return))
          _a2.call(_c);
      } finally {
        if (e_3)
          throw e_3.error;
      }
    }
    return result;
  };
  ElementRegistrar2.prototype.cleanElementInactiveNodes = function(element) {
    if (this.isElementActive(element)) {
      element._tolgee.nodes = new Set(this.getActiveNodes(element));
      return;
    }
  };
  ElementRegistrar2.prototype.cleanElement = function(element) {
    if (!element._tolgee.preventClean) {
      if (element._tolgee.highlightEl) {
        element._tolgee.unhighlight();
      }
      element.removeAttribute(TOLGEE_ATTRIBUTE_NAME);
      delete element._tolgee;
      this.registeredElements.delete(element);
    }
  };
  ElementRegistrar2.prototype.getActiveNodes = function(element) {
    var _a2, _b, node, e_5_1;
    var e_5, _c;
    return __generator(this, function(_d) {
      switch (_d.label) {
        case 0:
          _d.trys.push([0, 5, 6, 7]);
          _a2 = __values(element._tolgee.nodes), _b = _a2.next();
          _d.label = 1;
        case 1:
          if (!!_b.done)
            return [3, 4];
          node = _b.value;
          if (!NodeHelper.nodeContains(this.properties.config.targetElement, node))
            return [3, 3];
          return [4, node];
        case 2:
          _d.sent();
          _d.label = 3;
        case 3:
          _b = _a2.next();
          return [3, 1];
        case 4:
          return [3, 7];
        case 5:
          e_5_1 = _d.sent();
          e_5 = { error: e_5_1 };
          return [3, 7];
        case 6:
          try {
            if (_b && !_b.done && (_c = _a2.return))
              _c.call(_a2);
          } finally {
            if (e_5)
              throw e_5.error;
          }
          return [7];
        case 7:
          return [2];
      }
    });
  };
  ElementRegistrar2.prototype.isElementActive = function(element) {
    return this.properties.config.targetElement.contains(element);
  };
  return ElementRegistrar2;
}();
var Observer = function() {
  function Observer2(properties, textWrapper, nodeRegistrar) {
    this.properties = properties;
    this.textWrapper = textWrapper;
    this.nodeRegistrar = nodeRegistrar;
    this._observer = void 0;
    this._observing = false;
  }
  Object.defineProperty(Observer2.prototype, "observer", {
    get: function() {
      var _this = this;
      if (!this._observer && typeof window !== "undefined") {
        this._observer = new MutationObserver(function(mutationsList) {
          return __awaiter(_this, void 0, void 0, function() {
            var mutationsList_1, mutationsList_1_1, mutation, e_1_1;
            var e_1, _a2;
            return __generator(this, function(_b) {
              switch (_b.label) {
                case 0:
                  _b.trys.push([0, 9, 10, 11]);
                  mutationsList_1 = __values(mutationsList), mutationsList_1_1 = mutationsList_1.next();
                  _b.label = 1;
                case 1:
                  if (!!mutationsList_1_1.done)
                    return [3, 8];
                  mutation = mutationsList_1_1.value;
                  if (!this._observing) {
                    return [2];
                  }
                  if (!(mutation.type === "characterData"))
                    return [3, 3];
                  return [4, this.textWrapper.handleText(mutation.target)];
                case 2:
                  _b.sent();
                  return [3, 7];
                case 3:
                  if (!(mutation.type === "childList"))
                    return [3, 5];
                  return [4, this.textWrapper.handleSubtree(mutation.target)];
                case 4:
                  _b.sent();
                  return [3, 7];
                case 5:
                  if (!(mutation.type === "attributes"))
                    return [3, 7];
                  return [4, this.textWrapper.handleAttribute(mutation.target)];
                case 6:
                  _b.sent();
                  _b.label = 7;
                case 7:
                  mutationsList_1_1 = mutationsList_1.next();
                  return [3, 1];
                case 8:
                  return [3, 11];
                case 9:
                  e_1_1 = _b.sent();
                  e_1 = { error: e_1_1 };
                  return [3, 11];
                case 10:
                  try {
                    if (mutationsList_1_1 && !mutationsList_1_1.done && (_a2 = mutationsList_1.return))
                      _a2.call(mutationsList_1);
                  } finally {
                    if (e_1)
                      throw e_1.error;
                  }
                  return [7];
                case 11:
                  this.nodeRegistrar.refreshAll();
                  return [2];
              }
            });
          });
        });
      }
      return this._observer;
    },
    enumerable: false,
    configurable: true
  });
  Observer2.prototype.observe = function() {
    if (!this.observer) {
      return;
    }
    if (this._observing) {
      return;
    }
    this._observing = true;
    this.observer.observe(this.properties.config.targetElement, {
      attributes: true,
      childList: true,
      subtree: true,
      characterData: true
    });
  };
  Observer2.prototype.stopObserving = function() {
    if (!this.observer) {
      return;
    }
    this._observing = false;
    this.observer.disconnect();
  };
  return Observer2;
}();
var CoreService = function() {
  function CoreService2(properties, apiHttpService) {
    this.properties = properties;
    this.apiHttpService = apiHttpService;
  }
  CoreService2.prototype.getLanguages = function() {
    return __awaiter(this, void 0, void 0, function() {
      var languages, _a2;
      return __generator(this, function(_b) {
        switch (_b.label) {
          case 0:
            if (!(this.languagePromise instanceof Promise)) {
              this.languagePromise = this.apiHttpService.fetchJson("v2/projects/languages?size=1000");
            }
            _a2 = Set.bind;
            return [4, this.languagePromise];
          case 1:
            languages = new (_a2.apply(Set, [void 0, _b.sent()._embedded.languages.map(function(l) {
              return l.tag;
            })]))();
            this.properties.preferredLanguages = new Set(Array.from(this.properties.preferredLanguages).filter(function(l) {
              return languages.has(l);
            }));
            return [2, languages];
        }
      });
    });
  };
  CoreService2.prototype.getLanguagesFull = function() {
    return __awaiter(this, void 0, void 0, function() {
      var languages;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            this.getLanguages();
            return [4, this.languagePromise];
          case 1:
            languages = _a2.sent();
            return [2, languages._embedded.languages];
        }
      });
    });
  };
  CoreService2.prototype.getApiKeyDetails = function() {
    return __awaiter(this, void 0, void 0, function() {
      var e_1;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            _a2.trys.push([0, 2, , 3]);
            return [4, this.apiHttpService.fetchJson("v2/api-keys/current")];
          case 1:
            return [2, _a2.sent()];
          case 2:
            e_1 = _a2.sent();
            console.error(e_1);
            console.error("Error getting scopes. Trying to switch to production mode!");
            this.properties.mode = "production";
            return [3, 3];
          case 3:
            return [2];
        }
      });
    });
  };
  CoreService2.prototype.isAuthorizedTo = function(scope) {
    return this.properties.scopes.indexOf(scope) > -1;
  };
  CoreService2.prototype.checkScope = function(scope) {
    if (!this.isAuthorizedTo(scope)) {
      throw new Error("Api key not permitted to do this, please add 'translations.view' scope.");
    }
  };
  CoreService2.prototype.loadApiKeyDetails = function() {
    return __awaiter(this, void 0, void 0, function() {
      var details;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            if (!(this.properties.scopes === void 0))
              return [3, 2];
            return [4, this.getApiKeyDetails()];
          case 1:
            details = _a2.sent();
            this.properties.scopes = details.scopes;
            this.properties.projectId = details.projectId;
            this.properties.permittedLanguageIds = details.permittedLanguageIds;
            _a2.label = 2;
          case 2:
            return [2];
        }
      });
    });
  };
  return CoreService2;
}();
var API_KEY_LOCAL_STORAGE = "__tolgee_apiKey";
var API_URL_LOCAL_STORAGE = "__tolgee_apiUrl";
var DEFAULT_TARGET_ELEMENT_SUPPLIER = function() {
  if (typeof document !== "undefined") {
    return document.body;
  }
};
var TolgeeConfig = function() {
  function TolgeeConfig2(config) {
    this.inputPrefix = "%-%tolgee:";
    this.inputSuffix = "%-%";
    this.defaultLanguage = "en";
    this.enableLanguageStore = true;
    this.enableLanguageDetection = true;
    this.filesUrlPrefix = "i18n/";
    this.tagAttributes = {
      textarea: ["placeholder"],
      input: ["value", "placeholder"],
      img: ["alt"],
      "*": ["aria-label", "title"]
    };
    this.highlightKeys = [ModifierKey.Alt];
    this.passToParent = ["option", "optgroup"];
    this.restrictedElements = ["script", "style"];
    this.highlightColor = "rgb(255, 0, 0)";
    this.highlightWidth = 5;
    this.wrapperMode = "text";
    this.preloadFallback = false;
    Object.defineProperty(this, "targetElement", {
      set: function(targetElement) {
        if (this.targetElement !== void 0) {
          throw new Error("Target element is already defined!");
        }
        if (targetElement === void 0) {
          this._targetElement = DEFAULT_TARGET_ELEMENT_SUPPLIER();
        }
        if (NodeHelper.isElementTargetElement(targetElement)) {
          console.error("Target element: ", this._targetElement);
          throw new Error("An tolgee instance is inited with provided target element");
        }
        this._targetElement = targetElement;
        NodeHelper.markElementAsTargetElement(this._targetElement);
      },
      get: function() {
        return this._targetElement;
      }
    });
    Object.assign(this, config || {});
    if (typeof sessionStorage !== "undefined") {
      this.apiUrl = sessionStorage.getItem(API_URL_LOCAL_STORAGE) || this.apiUrl;
      this.apiKey = sessionStorage.getItem(API_KEY_LOCAL_STORAGE) || this.apiKey;
    }
    if (this._targetElement === void 0) {
      this._targetElement = DEFAULT_TARGET_ELEMENT_SUPPLIER();
    }
    this.fallbackLanguage = this.fallbackLanguage || this.defaultLanguage;
    if (this.watch === void 0) {
      this.watch = Boolean(this.apiKey && this.apiUrl);
    }
    if (this.availableLanguages === void 0 && this.staticData) {
      this.availableLanguages = Object.keys(this.staticData);
    }
  }
  return TolgeeConfig2;
}();
var sleep = function(ms) {
  return new Promise(function(resolve) {
    return setTimeout(resolve, ms);
  });
};
var PluginManager = function() {
  function PluginManager2(messages, properties, eventService, elementRegistrar, translationService) {
    var _this = this;
    this.messages = messages;
    this.properties = properties;
    this.eventService = eventService;
    this.elementRegistrar = elementRegistrar;
    this.translationService = translationService;
    this.handshakeSucceed = false;
    this.takeScreenshot = function(translationData) {
      return new Promise(function(resolve, reject) {
        _this.translationService.changeTranslations(translationData).then(function(revertChange) {
          return __awaiter(_this, void 0, void 0, function() {
            var cancel_1, e_1;
            var _this2 = this;
            return __generator(this, function(_a2) {
              switch (_a2.label) {
                case 0:
                  _a2.trys.push([0, 2, , 3]);
                  this.highlightAllByKey(translationData.key);
                  return [4, sleep(100)];
                case 1:
                  _a2.sent();
                  this.messages.send("TOLGEE_TAKE_SCREENSHOT");
                  cancel_1 = this.messages.listen("TOLGEE_SCREENSHOT_TAKEN", function(data) {
                    _this2.unhighlightAllByKey(translationData.key);
                    resolve(data);
                    revertChange();
                    cancel_1();
                  });
                  return [3, 3];
                case 2:
                  e_1 = _a2.sent();
                  revertChange();
                  reject(e_1);
                  return [3, 3];
                case 3:
                  return [2];
              }
            });
          });
        }).catch(function(e) {
          reject(e);
        });
      });
    };
    this.handshake = function() {
      var sharedConfiguration = __assign$1(__assign$1({}, _this.properties), { config: __assign$1(__assign$1({}, _this.properties.config), {
        staticData: void 0,
        targetElement: void 0,
        _targetElement: void 0,
        ui: void 0
      }), uiPresent: Boolean(_this.properties.config.ui), uiVersion: "4.7.2" });
      var timer = null;
      var ping = function() {
        _this.messages.send("TOLGEE_READY", sharedConfiguration);
      };
      var finish = function() {
        clearInterval(timer);
      };
      _this.messages.listen("TOLGEE_PLUGIN_READY", function() {
        _this.handshakeSucceed = true;
        _this.messages.send("TOLGEE_READY", sharedConfiguration);
        finish();
      });
      ping();
      var counter = 0;
      timer = setInterval(function() {
        if (!_this.handshakeSucceed && counter < 5) {
          ping();
          counter += 1;
        } else {
          finish();
        }
      }, 200);
    };
  }
  PluginManager2.prototype.run = function() {
    try {
      this.messages.startListening();
      this.handshake();
    } catch (e) {
      console.warn(e);
      console.warn("Can not start communication with browser plugin. Check waning above.");
    }
  };
  PluginManager2.prototype.stop = function() {
    this.messages.stopListening();
  };
  PluginManager2.prototype.highlightAllByKey = function(key) {
    this.elementRegistrar.findAllByKey(key).forEach(function(el) {
      return el._tolgee.highlight();
    });
  };
  PluginManager2.prototype.unhighlightAllByKey = function(key) {
    this.elementRegistrar.findAllByKey(key).forEach(function(el) {
      return el._tolgee.unhighlight();
    });
  };
  return PluginManager2;
}();
var Messages = function() {
  function Messages2() {
    var _this = this;
    this.listeners = [];
    this.startListening = function() {
      var receiveMessage = function(event) {
        if (event.source != window) {
          return;
        }
        _this.listeners.forEach(function(listener) {
          if (listener.type == event.data.type) {
            listener.callback(event.data.data);
          }
        });
      };
      window.addEventListener("message", receiveMessage, false);
      typeof _this._stopListening === "function" && _this._stopListening();
      _this._stopListening = function() {
        window.removeEventListener("message", receiveMessage, false);
      };
    };
    this.listen = function(type, callback) {
      var listenerInfo = { type, callback };
      _this.listeners.push(listenerInfo);
      return function() {
        _this.listeners.splice(_this.listeners.indexOf(listenerInfo), 1);
      };
    };
    this.send = function(type, data) {
      try {
        window.postMessage({ type, data }, window.origin);
      } catch (e) {
        console.warn("Cannot send message.", e);
      }
    };
  }
  Messages2.prototype.stopListening = function() {
    this._stopListening();
  };
  return Messages2;
}();
var HIGHLIGHTER_BASE_STYLE = {
  pointerEvents: "none",
  position: "fixed",
  boxSizing: "content-box",
  zIndex: String(Number.MAX_SAFE_INTEGER),
  contain: "layout",
  display: "block",
  borderStyle: "solid",
  borderRadius: "4px"
};
var HighlightFunctionsInitializer = function() {
  function HighlightFunctionsInitializer2(properties) {
    this.properties = properties;
  }
  HighlightFunctionsInitializer2.prototype.initFunctions = function(element) {
    this.initHighlightFunction(element);
    this.initUnhighlightFunction(element);
  };
  HighlightFunctionsInitializer2.prototype.initHighlightFunction = function(element) {
    var _this = this;
    element._tolgee.highlight = function() {
      var highlightColor = _this.properties.config.highlightColor;
      var highlightWidth = _this.properties.config.highlightWidth;
      if (!element.isConnected) {
        return;
      }
      var highlightEl = element._tolgee.highlightEl;
      if (!highlightEl) {
        highlightEl = document.createElement("div");
        highlightEl.classList.add(TOLGEE_HIGHLIGHTER_CLASS);
        Object.entries(HIGHLIGHTER_BASE_STYLE).forEach(function(_a2) {
          var _b = __read(_a2, 2), key = _b[0], value = _b[1];
          highlightEl.style[key] = value;
        });
        highlightEl.style.borderColor = highlightColor;
        element._tolgee.highlightEl = highlightEl;
        document.body.appendChild(highlightEl);
      }
      var shape = element.getBoundingClientRect();
      highlightEl.style.borderWidth = highlightWidth + "px";
      highlightEl.style.top = shape.top - highlightWidth + "px";
      highlightEl.style.left = shape.left - highlightWidth + "px";
      highlightEl.style.width = shape.width + "px";
      highlightEl.style.height = shape.height + "px";
    };
  };
  HighlightFunctionsInitializer2.prototype.initUnhighlightFunction = function(element) {
    element._tolgee.unhighlight = function() {
      var _a2;
      (_a2 = element._tolgee.highlightEl) === null || _a2 === void 0 ? void 0 : _a2.remove();
      element._tolgee.highlightEl = null;
    };
  };
  return HighlightFunctionsInitializer2;
}();
var ScreenshotService = function() {
  function ScreenshotService2(coreService, apiHttpService) {
    this.coreService = coreService;
    this.apiHttpService = apiHttpService;
  }
  ScreenshotService2.prototype.uploadImage = function(blob) {
    return __awaiter(this, void 0, void 0, function() {
      var formData;
      return __generator(this, function(_a2) {
        formData = new FormData();
        formData.append("image", blob);
        return [2, this.apiHttpService.postJson("v2/image-upload", void 0, {
          headers: {},
          body: formData
        })];
      });
    });
  };
  ScreenshotService2.prototype.deleteImages = function(ids) {
    return __awaiter(this, void 0, void 0, function() {
      return __generator(this, function(_a2) {
        return [2, this.apiHttpService.post("v2/image-upload/".concat(ids.join(",")), void 0, {
          method: "delete"
        })];
      });
    });
  };
  return ScreenshotService2;
}();
var ModuleService = function() {
  function ModuleService2() {
    var _this = this;
    this.formatter = null;
    this.addModule = function(module) {
      if (module.type === "formatter") {
        var instance = new module();
        _this.formatter = instance;
      } else {
        throw new Error("Module with unknown type");
      }
    };
  }
  return ModuleService2;
}();
var NodeHandler = function() {
  function NodeHandler2(properties, elementRegistrar, wrapper) {
    this.properties = properties;
    this.elementRegistrar = elementRegistrar;
    this.wrapper = wrapper;
  }
  NodeHandler2.initParentElement = function(element) {
    if (element[TOLGEE_ATTRIBUTE_NAME] === void 0) {
      element[TOLGEE_ATTRIBUTE_NAME] = {
        nodes: /* @__PURE__ */ new Set()
      };
      element.setAttribute(TOLGEE_ATTRIBUTE_NAME, "");
    }
    return element;
  };
  NodeHandler2.prototype.filterRestricted = function(nodes) {
    var restrictedElements = this.properties.config.restrictedElements;
    return nodes.filter(function(n) {
      var e = NodeHelper.closestElement(n);
      if (!e) {
        return false;
      }
      return restrictedElements.indexOf(e.tagName.toLowerCase()) === -1 && e.closest("[".concat(RESTRICTED_ASCENDANT_ATTRIBUTE, '="true"]')) === null;
    });
  };
  NodeHandler2.prototype.handleNodes = function(nodes) {
    return __awaiter(this, void 0, void 0, function() {
      var nodes_1, nodes_1_1, textNode, tolgeeData, result, text, keys, translatedNode, parentElement, e_1_1;
      var e_1, _a2;
      return __generator(this, function(_b) {
        switch (_b.label) {
          case 0:
            _b.trys.push([0, 5, 6, 7]);
            nodes_1 = __values(nodes), nodes_1_1 = nodes_1.next();
            _b.label = 1;
          case 1:
            if (!!nodes_1_1.done)
              return [3, 4];
            textNode = nodes_1_1.value;
            if (textNode[TOLGEE_ATTRIBUTE_NAME] === void 0) {
              textNode[TOLGEE_ATTRIBUTE_NAME] = {};
            }
            tolgeeData = textNode[TOLGEE_ATTRIBUTE_NAME];
            if (!((tolgeeData === null || tolgeeData === void 0 ? void 0 : tolgeeData.locked) !== true))
              return [3, 3];
            this.lockNode(textNode);
            return [4, this.wrapper.unwrap(NodeHelper.getNodeText(textNode))];
          case 2:
            result = _b.sent();
            if (result) {
              text = result.text, keys = result.keys;
              translatedNode = this.translateChildNode(textNode, text, keys);
              parentElement = this.getParentElement(translatedNode);
              parentElement._tolgee.nodes.add(translatedNode);
              this.elementRegistrar.register(parentElement);
            }
            this.unlockNode(textNode);
            _b.label = 3;
          case 3:
            nodes_1_1 = nodes_1.next();
            return [3, 1];
          case 4:
            return [3, 7];
          case 5:
            e_1_1 = _b.sent();
            e_1 = { error: e_1_1 };
            return [3, 7];
          case 6:
            try {
              if (nodes_1_1 && !nodes_1_1.done && (_a2 = nodes_1.return))
                _a2.call(nodes_1);
            } finally {
              if (e_1)
                throw e_1.error;
            }
            return [7];
          case 7:
            return [2];
        }
      });
    });
  };
  NodeHandler2.prototype.translateChildNode = function(node, newValue, keys) {
    node[TOLGEE_ATTRIBUTE_NAME] = {
      oldTextContent: NodeHelper.getNodeText(node),
      keys
    };
    NodeHelper.setNodeText(node, newValue);
    return node;
  };
  NodeHandler2.prototype.lockNode = function(node) {
    if (node[TOLGEE_ATTRIBUTE_NAME] === void 0) {
      node[TOLGEE_ATTRIBUTE_NAME] = {};
    }
    var tolgeeData = node[TOLGEE_ATTRIBUTE_NAME];
    if ((tolgeeData === null || tolgeeData === void 0 ? void 0 : tolgeeData.locked) !== true) {
      tolgeeData.locked = true;
    }
    return node;
  };
  NodeHandler2.prototype.unlockNode = function(node) {
    if (node[TOLGEE_ATTRIBUTE_NAME]) {
      node[TOLGEE_ATTRIBUTE_NAME].locked = false;
    }
  };
  NodeHandler2.prototype.getParentElement = function(node) {
    var parent = this.getSuitableParent(node);
    return NodeHandler2.initParentElement(parent);
  };
  NodeHandler2.prototype.getSuitableParent = function(node) {
    var domParent = NodeHelper.getParentElement(node);
    if (domParent === void 0) {
      console.error(node);
      throw new Error("No suitable parent found for node above.");
    }
    if (!this.properties.config.passToParent) {
      return domParent;
    }
    if (Array.isArray(this.properties.config.passToParent)) {
      var tagNameEquals = function(elementTagName) {
        return domParent.tagName.toLowerCase() === elementTagName.toLowerCase();
      };
      if (this.properties.config.passToParent.findIndex(tagNameEquals) === -1) {
        return domParent;
      }
    }
    if (typeof this.properties.config.passToParent === "function") {
      if (!this.properties.config.passToParent(domParent)) {
        return domParent;
      }
    }
    return this.getSuitableParent(domParent);
  };
  return NodeHandler2;
}();
var AttributeHandler$1 = function() {
  function AttributeHandler2(properties, nodeHandler) {
    this.properties = properties;
    this.nodeHandler = nodeHandler;
  }
  AttributeHandler2.prototype.handle = function(node) {
    return __awaiter(this, void 0, void 0, function() {
      var inputPrefix, inputSuffix, _a2, _b, _c, tag, attributes, attributes_1, attributes_1_1, attribute, expression, nodes, e_1_1, e_2_1;
      var e_2, _d, e_1, _e;
      return __generator(this, function(_f) {
        switch (_f.label) {
          case 0:
            inputPrefix = this.properties.config.inputPrefix;
            inputSuffix = this.properties.config.inputSuffix;
            _f.label = 1;
          case 1:
            _f.trys.push([1, 12, 13, 14]);
            _a2 = __values(Object.entries(this.properties.config.tagAttributes)), _b = _a2.next();
            _f.label = 2;
          case 2:
            if (!!_b.done)
              return [3, 11];
            _c = __read(_b.value, 2), tag = _c[0], attributes = _c[1];
            _f.label = 3;
          case 3:
            _f.trys.push([3, 8, 9, 10]);
            attributes_1 = (e_1 = void 0, __values(attributes)), attributes_1_1 = attributes_1.next();
            _f.label = 4;
          case 4:
            if (!!attributes_1_1.done)
              return [3, 7];
            attribute = attributes_1_1.value;
            expression = "descendant-or-self::".concat(tag, "/@").concat(attribute, "[contains(., '").concat(inputPrefix, "') and contains(., '").concat(inputSuffix, "')]");
            nodes = NodeHelper.evaluate(expression, node);
            return [4, this.nodeHandler.handleNodes(nodes)];
          case 5:
            _f.sent();
            _f.label = 6;
          case 6:
            attributes_1_1 = attributes_1.next();
            return [3, 4];
          case 7:
            return [3, 10];
          case 8:
            e_1_1 = _f.sent();
            e_1 = { error: e_1_1 };
            return [3, 10];
          case 9:
            try {
              if (attributes_1_1 && !attributes_1_1.done && (_e = attributes_1.return))
                _e.call(attributes_1);
            } finally {
              if (e_1)
                throw e_1.error;
            }
            return [7];
          case 10:
            _b = _a2.next();
            return [3, 2];
          case 11:
            return [3, 14];
          case 12:
            e_2_1 = _f.sent();
            e_2 = { error: e_2_1 };
            return [3, 14];
          case 13:
            try {
              if (_b && !_b.done && (_d = _a2.return))
                _d.call(_a2);
            } finally {
              if (e_2)
                throw e_2.error;
            }
            return [7];
          case 14:
            return [2];
        }
      });
    });
  };
  return AttributeHandler2;
}();
var TextHelper = function() {
  function TextHelper2() {
  }
  TextHelper2.splitOnNonEscapedDelimiter = function(string, delimiter) {
    var result = [];
    var actual = "";
    var escaped = false;
    for (var i = 0; i < string.length; i++) {
      var char = string[i];
      if (char === "\\" && !escaped) {
        escaped = true;
        continue;
      }
      if (escaped) {
        escaped = false;
        actual += char;
        continue;
      }
      if (char === delimiter) {
        result.push(actual);
        actual = "";
        continue;
      }
      actual += char;
    }
    result.push(actual);
    return result;
  };
  TextHelper2.isCharEscaped = function(position, fullString) {
    var escapeCharsCount = 0;
    while (position > -1 && fullString[position - 1] === "\\") {
      escapeCharsCount++;
      position--;
    }
    return escapeCharsCount % 2 == 1;
  };
  TextHelper2.removeEscapes = function(string) {
    var result = "";
    var escaped = false;
    for (var i = 0; i < string.length; i++) {
      var char = string[i];
      if (char === "\\" && !escaped) {
        escaped = true;
        continue;
      }
      if (escaped) {
        escaped = false;
        result += char;
        continue;
      }
      result += char;
    }
    return result;
  };
  return TextHelper2;
}();
var Coder$1 = function() {
  function Coder2(properties, textService) {
    this.properties = properties;
    this.textService = textService;
    this.escapeForRegExp = function(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    };
    this.escapeParam = function(param) {
      if (typeof param === "string") {
        return param.replace(/[,:\\]/gs, "\\$&");
      }
      if (typeof param === "number" || typeof param === "bigint") {
        return param.toString();
      }
      console.warn('Parameters of type "'.concat(typeof param, '" are not supported in "text" wrapper mode.'));
      return param;
    };
  }
  Object.defineProperty(Coder2.prototype, "rawUnWrapRegex", {
    get: function() {
      var escapedPrefix = this.escapeForRegExp(this.properties.config.inputPrefix);
      var escapedSuffix = this.escapeForRegExp(this.properties.config.inputSuffix);
      return "(\\\\?)(".concat(escapedPrefix, "(.*?)").concat(escapedSuffix, ")");
    },
    enumerable: false,
    configurable: true
  });
  Coder2.parseUnwrapped = function(unwrappedString) {
    var e_1, _a2;
    var escaped = false;
    var actual = "";
    var paramName = "";
    var readingState = "KEY";
    var result = {
      key: "",
      params: {},
      defaultValue: void 0
    };
    try {
      for (var unwrappedString_1 = __values(unwrappedString), unwrappedString_1_1 = unwrappedString_1.next(); !unwrappedString_1_1.done; unwrappedString_1_1 = unwrappedString_1.next()) {
        var char = unwrappedString_1_1.value;
        if (char === "\\" && !escaped) {
          escaped = true;
          continue;
        }
        if (escaped) {
          escaped = false;
          actual += char;
          continue;
        }
        if (readingState === "KEY" && char === ",") {
          readingState = "DEFAULT_VALUE";
          result.key = actual;
          actual = "";
          continue;
        }
        if (readingState === "KEY" && char === ":") {
          readingState = "PARAM_NAME";
          result.key = actual;
          actual = "";
          continue;
        }
        if (readingState === "DEFAULT_VALUE" && char === ":") {
          readingState = "PARAM_NAME";
          result.defaultValue = actual;
          actual = "";
          continue;
        }
        if (readingState === "PARAM_NAME" && char === ":") {
          readingState = "PARAM_VALUE";
          paramName = actual;
          actual = "";
          continue;
        }
        if (readingState === "PARAM_VALUE" && char === ",") {
          readingState = "PARAM_NAME";
          result.params[paramName] = actual;
          actual = "";
          continue;
        }
        actual += char;
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (unwrappedString_1_1 && !unwrappedString_1_1.done && (_a2 = unwrappedString_1.return))
          _a2.call(unwrappedString_1);
      } finally {
        if (e_1)
          throw e_1.error;
      }
    }
    if (readingState === "KEY") {
      result.key = actual;
    }
    if (readingState === "DEFAULT_VALUE") {
      result.defaultValue = actual;
    }
    if (readingState === "PARAM_VALUE") {
      result.params[paramName] = actual;
    }
    return result;
  };
  Coder2.prototype.unwrap = function(text) {
    var matchRegexp = new RegExp(this.rawUnWrapRegex, "gs");
    var keysAndParams = [];
    var matched = false;
    var match;
    var start = 0;
    var result = "";
    while ((match = matchRegexp.exec(text)) !== null) {
      var pre = match[1];
      var _a2 = __read(match, 4), fullMatch = _a2[0];
      _a2[1];
      var wrapped = _a2[2], unwrapped = _a2[3];
      var index = match.index, input = match.input;
      result += input.substr(start, index - start);
      start = index + fullMatch.length;
      if (pre === "\\") {
        if (!TextHelper.isCharEscaped(index, text)) {
          result += wrapped;
          continue;
        }
        pre = "";
      }
      var translated = this.getTranslatedWithMetadata(unwrapped);
      keysAndParams.push({
        key: translated.key,
        params: translated.params,
        defaultValue: translated.defaultValue
      });
      matched = true;
      result += pre + translated.translated;
    }
    result += text.substring(start);
    if (matched) {
      return { text: result, keys: keysAndParams };
    }
    return void 0;
  };
  Coder2.prototype.wrap = function(key, params, defaultValue) {
    var _this = this;
    if (params === void 0) {
      params = {};
    }
    if (defaultValue === void 0) {
      defaultValue = void 0;
    }
    var paramString = Object.entries(params).map(function(_a2) {
      var _b = __read(_a2, 2), name = _b[0], value = _b[1];
      return "".concat(_this.escapeParam(name), ":").concat(_this.escapeParam(value));
    }).join(",");
    paramString = paramString.length ? ":".concat(paramString) : "";
    var defaultString = defaultValue !== void 0 ? ",".concat(this.escapeParam(defaultValue)) : "";
    return "".concat(this.properties.config.inputPrefix).concat(this.escapeParam(key)).concat(defaultString).concat(paramString).concat(this.properties.config.inputSuffix);
  };
  Coder2.prototype.getTranslatedWithMetadata = function(text) {
    var _a2 = Coder2.parseUnwrapped(text), key = _a2.key, params = _a2.params, defaultValue = _a2.defaultValue;
    var translated = this.textService.instant(key, params, void 0, false, defaultValue);
    return { translated, key, params, defaultValue };
  };
  return Coder2;
}();
var CoreHandler$1 = function() {
  function CoreHandler2(textHandler, eventService, properties, attributeHandler, coder, wrappedHandler) {
    this.textHandler = textHandler;
    this.eventService = eventService;
    this.properties = properties;
    this.attributeHandler = attributeHandler;
    this.coder = coder;
    this.wrappedHandler = wrappedHandler;
    if (typeof window !== "undefined") {
      eventService.LANGUAGE_CHANGED.subscribe(this.refresh.bind(this));
      eventService.TRANSLATION_CHANGED.subscribe(this.refresh.bind(this));
    }
  }
  CoreHandler2.prototype.handleSubtree = function(target) {
    return __awaiter(this, void 0, void 0, function() {
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            return [4, this.attributeHandler.handle(target)];
          case 1:
            _a2.sent();
            return [4, this.textHandler.handle(target)];
          case 2:
            _a2.sent();
            return [4, this.wrappedHandler.handle(target)];
          case 3:
            _a2.sent();
            return [2];
        }
      });
    });
  };
  CoreHandler2.prototype.refresh = function() {
    return __awaiter(this, void 0, void 0, function() {
      var nodes, nodes_1, nodes_1_1, node, _a2, _b, textNode, result, e_1_1, e_2_1;
      var e_2, _c, e_1, _d;
      return __generator(this, function(_e) {
        switch (_e.label) {
          case 0:
            nodes = NodeHelper.evaluate("//*[@_tolgee]", this.properties.config.targetElement);
            _e.label = 1;
          case 1:
            _e.trys.push([1, 12, 13, 14]);
            nodes_1 = __values(nodes), nodes_1_1 = nodes_1.next();
            _e.label = 2;
          case 2:
            if (!!nodes_1_1.done)
              return [3, 11];
            node = nodes_1_1.value;
            _e.label = 3;
          case 3:
            _e.trys.push([3, 8, 9, 10]);
            _a2 = (e_1 = void 0, __values(node._tolgee.nodes)), _b = _a2.next();
            _e.label = 4;
          case 4:
            if (!!_b.done)
              return [3, 7];
            textNode = _b.value;
            return [4, this.coder.unwrap(textNode._tolgee.oldTextContent)];
          case 5:
            result = _e.sent();
            if (result) {
              NodeHelper.setNodeText(textNode, result.text);
            }
            _e.label = 6;
          case 6:
            _b = _a2.next();
            return [3, 4];
          case 7:
            return [3, 10];
          case 8:
            e_1_1 = _e.sent();
            e_1 = { error: e_1_1 };
            return [3, 10];
          case 9:
            try {
              if (_b && !_b.done && (_d = _a2.return))
                _d.call(_a2);
            } finally {
              if (e_1)
                throw e_1.error;
            }
            return [7];
          case 10:
            nodes_1_1 = nodes_1.next();
            return [3, 2];
          case 11:
            return [3, 14];
          case 12:
            e_2_1 = _e.sent();
            e_2 = { error: e_2_1 };
            return [3, 14];
          case 13:
            try {
              if (nodes_1_1 && !nodes_1_1.done && (_c = nodes_1.return))
                _c.call(nodes_1);
            } finally {
              if (e_2)
                throw e_2.error;
            }
            return [7];
          case 14:
            return [2];
        }
      });
    });
  };
  return CoreHandler2;
}();
var ContentHandler$1 = function() {
  function ContentHandler2(properties, nodeHandler) {
    this.properties = properties;
    this.nodeHandler = nodeHandler;
  }
  ContentHandler2.prototype.handle = function(node) {
    return __awaiter(this, void 0, void 0, function() {
      var inputPrefix, inputSuffix, xPath, nodes, filtered;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            inputPrefix = this.properties.config.inputPrefix;
            inputSuffix = this.properties.config.inputSuffix;
            xPath = "./descendant-or-self::text()[contains(., '".concat(inputPrefix, "') and contains(., '").concat(inputSuffix, "')]");
            nodes = NodeHelper.evaluate(xPath, node);
            filtered = this.nodeHandler.filterRestricted(nodes);
            return [4, this.nodeHandler.handleNodes(filtered)];
          case 1:
            _a2.sent();
            return [2];
        }
      });
    });
  };
  return ContentHandler2;
}();
var WrappedHandler = function() {
  function WrappedHandler2(elementRegistrar, nodeHandler) {
    this.elementRegistrar = elementRegistrar;
    this.nodeHandler = nodeHandler;
  }
  WrappedHandler2.prototype.handle = function(node) {
    return __awaiter(this, void 0, void 0, function() {
      var xPath, nodes, filtered;
      var _this = this;
      return __generator(this, function(_a2) {
        xPath = "./descendant-or-self::*[@".concat(TOLGEE_WRAPPED_ONLY_DATA_ATTRIBUTE, "]");
        nodes = NodeHelper.evaluate(xPath, node);
        filtered = this.nodeHandler.filterRestricted(nodes);
        filtered.forEach(function(element) {
          var elementWithMeta = NodeHandler.initParentElement(element);
          elementWithMeta._tolgee.wrappedWithElementOnlyKey = element.getAttribute(TOLGEE_WRAPPED_ONLY_DATA_ATTRIBUTE);
          elementWithMeta._tolgee.wrappedWithElementOnlyDefaultHtml = element.innerHTML;
          _this.elementRegistrar.register(elementWithMeta);
        });
        return [2];
      });
    });
  };
  return WrappedHandler2;
}();
var TextWrapper = function() {
  function TextWrapper2(eventService, properties, textService, elementRegistrar) {
    this.coder = new Coder$1(properties, textService);
    this.nodeHandler = new NodeHandler(properties, elementRegistrar, this);
    this.textHandler = new ContentHandler$1(properties, this.nodeHandler);
    this.attributeHandler = new AttributeHandler$1(properties, this.nodeHandler);
    this.wrappedHandler = new WrappedHandler(elementRegistrar, this.nodeHandler);
    this.coreHandler = new CoreHandler$1(this.textHandler, eventService, properties, this.attributeHandler, this.coder, this.wrappedHandler);
  }
  TextWrapper2.prototype.handleText = function(node) {
    return this.textHandler.handle(node);
  };
  TextWrapper2.prototype.handleSubtree = function(node) {
    return this.coreHandler.handleSubtree(node);
  };
  TextWrapper2.prototype.handleAttribute = function(node) {
    return this.attributeHandler.handle(node);
  };
  TextWrapper2.prototype.wrap = function(key, params, defaultValue, translation) {
    if (params === void 0) {
      params = {};
    }
    if (defaultValue === void 0) {
      defaultValue = void 0;
    }
    return this.coder.wrap(key, params, defaultValue);
  };
  TextWrapper2.prototype.unwrap = function(text) {
    return this.coder.unwrap(text);
  };
  return TextWrapper2;
}();
function PTextEncoder() {
}
PTextEncoder.prototype.encode = function(string) {
  var octets = [];
  var length = string.length;
  var i = 0;
  while (i < length) {
    var codePoint = string.codePointAt(i);
    var c = 0;
    var bits = 0;
    if (codePoint <= 127) {
      c = 0;
      bits = 0;
    } else if (codePoint <= 2047) {
      c = 6;
      bits = 192;
    } else if (codePoint <= 65535) {
      c = 12;
      bits = 224;
    } else if (codePoint <= 2097151) {
      c = 18;
      bits = 240;
    }
    octets.push(bits | codePoint >> c);
    c -= 6;
    while (c >= 0) {
      octets.push(128 | codePoint >> c & 63);
      c -= 6;
    }
    i += codePoint >= 65536 ? 2 : 1;
  }
  return octets;
};
function PTextDecoder() {
}
PTextDecoder.prototype.decode = function(octets) {
  var string = "";
  var i = 0;
  while (i < octets.length) {
    var octet = octets[i];
    var bytesNeeded = 0;
    var codePoint = 0;
    if (octet <= 127) {
      bytesNeeded = 0;
      codePoint = octet & 255;
    } else if (octet <= 223) {
      bytesNeeded = 1;
      codePoint = octet & 31;
    } else if (octet <= 239) {
      bytesNeeded = 2;
      codePoint = octet & 15;
    } else if (octet <= 244) {
      bytesNeeded = 3;
      codePoint = octet & 7;
    }
    if (octets.length - i - bytesNeeded > 0) {
      var k = 0;
      while (k < bytesNeeded) {
        octet = octets[i + k + 1];
        codePoint = codePoint << 6 | octet & 63;
        k += 1;
      }
    } else {
      codePoint = 65533;
      bytesNeeded = octets.length - i;
    }
    string += String.fromCodePoint(codePoint);
    i += bytesNeeded + 1;
  }
  return string;
};
var Encoder = typeof TextEncoder === "undefined" ? PTextEncoder : TextEncoder;
var Decoder = typeof TextDecoder === "undefined" ? PTextDecoder : TextDecoder;
var INVISIBLE_CHARACTERS = ["\u200C", "\u200D"];
var INVISIBLE_REGEX = RegExp("([".concat(INVISIBLE_CHARACTERS.join(""), "]{9})+"), "gu");
var toBytes = function(text) {
  return Array.from(new Encoder().encode(text));
};
var fromBytes = function(bytes) {
  return new Decoder().decode(new Uint8Array(bytes));
};
var padToWholeBytes = function(binary) {
  var needsToAdd = 8 - binary.length;
  return "0".repeat(needsToAdd) + binary;
};
var encodeMessage = function(text) {
  var bytes = toBytes(text).map(Number);
  var binary = bytes.map(function(byte) {
    return padToWholeBytes(byte.toString(2)) + "0";
  }).join("");
  var result = Array.from(binary).map(function(b) {
    return INVISIBLE_CHARACTERS[Number(b)];
  }).join("");
  return result;
};
var decodeMessage = function(message) {
  var binary = Array.from(message).map(function(character) {
    return INVISIBLE_CHARACTERS.indexOf(character);
  }).map(String).join("");
  var textBytes = binary.match(/(.{9})/g);
  var codes = Uint8Array.from(textBytes.map(function(byte) {
    return parseInt(byte.slice(0, 8), 2);
  }));
  return fromBytes(codes);
};
var decodeFromText = function(text) {
  var _a2;
  var invisibleMessages = (_a2 = text.match(INVISIBLE_REGEX)) === null || _a2 === void 0 ? void 0 : _a2.filter(function(m) {
    return m.length > 8;
  });
  return (invisibleMessages === null || invisibleMessages === void 0 ? void 0 : invisibleMessages.map(decodeMessage)) || [];
};
var removeSecrets = function(text) {
  return text.replace(INVISIBLE_REGEX, "");
};
var stringToCodePoints = function(text) {
  var e_1, _a2;
  var result = [];
  try {
    for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
      var codePoint = text_1_1.value;
      result.push(codePoint.codePointAt(0));
    }
  } catch (e_1_1) {
    e_1 = { error: e_1_1 };
  } finally {
    try {
      if (text_1_1 && !text_1_1.done && (_a2 = text_1.return))
        _a2.call(text_1);
    } finally {
      if (e_1)
        throw e_1.error;
    }
  }
  return result;
};
var AttributeHandler = function() {
  function AttributeHandler2(properties, nodeHandler) {
    this.properties = properties;
    this.nodeHandler = nodeHandler;
  }
  AttributeHandler2.prototype.handle = function(node) {
    return __awaiter(this, void 0, void 0, function() {
      var _a2, _b, _c, tag, attributes, attributes_1, attributes_1_1, attribute, expression, nodes, e_1_1, e_2_1;
      var e_2, _d, e_1, _e;
      return __generator(this, function(_f) {
        switch (_f.label) {
          case 0:
            _f.trys.push([0, 11, 12, 13]);
            _a2 = __values(Object.entries(this.properties.config.tagAttributes)), _b = _a2.next();
            _f.label = 1;
          case 1:
            if (!!_b.done)
              return [3, 10];
            _c = __read(_b.value, 2), tag = _c[0], attributes = _c[1];
            _f.label = 2;
          case 2:
            _f.trys.push([2, 7, 8, 9]);
            attributes_1 = (e_1 = void 0, __values(attributes)), attributes_1_1 = attributes_1.next();
            _f.label = 3;
          case 3:
            if (!!attributes_1_1.done)
              return [3, 6];
            attribute = attributes_1_1.value;
            expression = "descendant-or-self::".concat(tag, "/@").concat(attribute, "[contains(., '").concat(INVISIBLE_CHARACTERS[0], "')]");
            nodes = NodeHelper.evaluate(expression, node);
            return [4, this.nodeHandler.handleNodes(nodes)];
          case 4:
            _f.sent();
            _f.label = 5;
          case 5:
            attributes_1_1 = attributes_1.next();
            return [3, 3];
          case 6:
            return [3, 9];
          case 7:
            e_1_1 = _f.sent();
            e_1 = { error: e_1_1 };
            return [3, 9];
          case 8:
            try {
              if (attributes_1_1 && !attributes_1_1.done && (_e = attributes_1.return))
                _e.call(attributes_1);
            } finally {
              if (e_1)
                throw e_1.error;
            }
            return [7];
          case 9:
            _b = _a2.next();
            return [3, 1];
          case 10:
            return [3, 13];
          case 11:
            e_2_1 = _f.sent();
            e_2 = { error: e_2_1 };
            return [3, 13];
          case 12:
            try {
              if (_b && !_b.done && (_d = _a2.return))
                _d.call(_a2);
            } finally {
              if (e_2)
                throw e_2.error;
            }
            return [7];
          case 13:
            return [2];
        }
      });
    });
  };
  return AttributeHandler2;
}();
var ValueMemory = function() {
  function ValueMemory2() {
    this.values = [];
  }
  ValueMemory2.prototype.valueToNumber = function(key) {
    var index = this.values.indexOf(key);
    if (index === -1) {
      index = this.values.length;
      this.values.push(key);
    }
    return index;
  };
  ValueMemory2.prototype.numberToValue = function(num) {
    return this.values[num];
  };
  return ValueMemory2;
}();
var Coder = function() {
  function Coder2() {
    this.keyMemory = new ValueMemory();
    this.defaultMemory = new ValueMemory();
  }
  Coder2.prototype.unwrap = function(text) {
    var _this = this;
    var keysAndParams = [];
    var messages = decodeFromText(text);
    messages.forEach(function(msg) {
      var _a2 = __read(stringToCodePoints(msg), 2), keyCode = _a2[0], defaultCode = _a2[1];
      var key = _this.keyMemory.numberToValue(keyCode);
      var defaultValue = defaultCode !== void 0 ? _this.defaultMemory.numberToValue(defaultCode) : void 0;
      keysAndParams.push({
        key,
        params: void 0,
        defaultValue
      });
    });
    var result = removeSecrets(text);
    if (keysAndParams.length) {
      return { text: result, keys: keysAndParams };
    }
    return void 0;
  };
  Coder2.prototype.wrap = function(key, _params, defaultValue, translation) {
    if (defaultValue === void 0) {
      defaultValue = void 0;
    }
    if (translation === void 0) {
      translation = void 0;
    }
    var codes = [this.keyMemory.valueToNumber(key)];
    if (defaultValue) {
      codes.push(this.defaultMemory.valueToNumber(defaultValue));
    }
    var value = translation || "";
    var invisibleMark = encodeMessage(String.fromCodePoint.apply(String, __spreadArray([], __read(codes), false)));
    return typeof value === "string" ? value + invisibleMark : Array.isArray(value) ? __spreadArray(__spreadArray([], __read(value), false), [invisibleMark], false) : [value, invisibleMark];
  };
  return Coder2;
}();
var CoreHandler = function() {
  function CoreHandler2(textHandler, attributeHandler, wrappedHandler) {
    this.textHandler = textHandler;
    this.attributeHandler = attributeHandler;
    this.wrappedHandler = wrappedHandler;
  }
  CoreHandler2.prototype.handleSubtree = function(target) {
    return __awaiter(this, void 0, void 0, function() {
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            return [4, this.attributeHandler.handle(target)];
          case 1:
            _a2.sent();
            return [4, this.textHandler.handle(target)];
          case 2:
            _a2.sent();
            return [4, this.wrappedHandler.handle(target)];
          case 3:
            _a2.sent();
            return [2];
        }
      });
    });
  };
  return CoreHandler2;
}();
var ContentHandler = function() {
  function ContentHandler2(nodeHandler) {
    this.nodeHandler = nodeHandler;
  }
  ContentHandler2.prototype.handle = function(node) {
    return __awaiter(this, void 0, void 0, function() {
      var xPath, nodes, filtered;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            xPath = "./descendant-or-self::text()[contains(., '".concat(INVISIBLE_CHARACTERS[0], "')]");
            nodes = NodeHelper.evaluate(xPath, node);
            filtered = this.nodeHandler.filterRestricted(nodes);
            return [4, this.nodeHandler.handleNodes(filtered)];
          case 1:
            _a2.sent();
            return [2];
        }
      });
    });
  };
  return ContentHandler2;
}();
var InvisibleWrapper = function() {
  function InvisibleWrapper2(properties, elementRegistrar) {
    this.coder = new Coder();
    this.nodeHandler = new NodeHandler(properties, elementRegistrar, this);
    this.textHandler = new ContentHandler(this.nodeHandler);
    this.attributeHandler = new AttributeHandler(properties, this.nodeHandler);
    this.wrappedHandler = new WrappedHandler(elementRegistrar, this.nodeHandler);
    this.coreHandler = new CoreHandler(this.textHandler, this.attributeHandler, this.wrappedHandler);
  }
  InvisibleWrapper2.prototype.handleText = function(node) {
    return this.textHandler.handle(node);
  };
  InvisibleWrapper2.prototype.handleSubtree = function(node) {
    return this.coreHandler.handleSubtree(node);
  };
  InvisibleWrapper2.prototype.handleAttribute = function(node) {
    return this.attributeHandler.handle(node);
  };
  InvisibleWrapper2.prototype.wrap = function(key, params, defaultValue, translation) {
    if (params === void 0) {
      params = {};
    }
    if (defaultValue === void 0) {
      defaultValue = void 0;
    }
    if (translation === void 0) {
      translation = "";
    }
    return this.coder.wrap(key, params, defaultValue, translation);
  };
  InvisibleWrapper2.prototype.unwrap = function(text) {
    return this.coder.unwrap(text);
  };
  return InvisibleWrapper2;
}();
var DependencyService = function() {
  function DependencyService2() {
    var _this = this;
    this.properties = new Properties();
    this.eventService = new EventService();
    this.apiHttpService = new ApiHttpService(this.properties);
    this.mouseEventHandler = new MouseEventHandler(this);
    this.moduleService = new ModuleService();
    this.coreService = new CoreService(this.properties, this.apiHttpService);
    this.screenshotService = new ScreenshotService(this.coreService, this.apiHttpService);
    this.translationService = new TranslationService(this.properties, this.coreService, this.apiHttpService, this.eventService);
    this.textService = new TextService(this.properties, this.translationService, this.moduleService);
    this.highlightFunctionInitializer = new HighlightFunctionsInitializer(this.properties);
    this.translationHighlighter = new TranslationHighlighter(this);
    this.elementRegistrar = new ElementRegistrar(this.properties, this.translationHighlighter, this.eventService);
    this.messages = new Messages();
    this.pluginManager = new PluginManager(this.messages, this.properties, this.eventService, this.elementRegistrar, this.translationService);
    this.run = function() {
      _this.mouseEventHandler.run();
    };
    this.stop = function() {
      _this.observer.stopObserving();
      _this.elementRegistrar.cleanAll();
      _this.mouseEventHandler.stop();
      NodeHelper.unmarkElementAsTargetElement(_this.properties.config.targetElement);
    };
    this.translationHighlighter.pluginManager = this.pluginManager;
  }
  DependencyService2.prototype.init = function(config) {
    if (this.properties.config) {
      throw new Error("Duplicate initialization of config");
    }
    this.properties.config = new TolgeeConfig(config);
    if (this.properties.config.wrapperMode === "invisible") {
      this.wrapper = new InvisibleWrapper(this.properties, this.elementRegistrar);
    } else {
      this.wrapper = new TextWrapper(this.eventService, this.properties, this.textService, this.elementRegistrar);
    }
    this.observer = new Observer(this.properties, this.wrapper, this.elementRegistrar);
    this.translationService.initStatic();
  };
  return DependencyService2;
}();
var Tolgee = function() {
  function Tolgee2() {
    var _this = this;
    this.stop = function() {
      _this.dependencyService.stop();
    };
    this.dependencyService = new DependencyService();
  }
  Object.defineProperty(Tolgee2.prototype, "properties", {
    get: function() {
      return this.dependencyService.properties;
    },
    enumerable: false,
    configurable: true
  });
  Object.defineProperty(Tolgee2.prototype, "lang", {
    get: function() {
      return this.properties.currentLanguage;
    },
    set: function(newLanguage) {
      var _this = this;
      this.properties.currentLanguage = newLanguage;
      this.dependencyService.translationService.loadTranslations(newLanguage).then(function() {
        _this.emitLangChangeEvent(newLanguage);
      });
    },
    enumerable: false,
    configurable: true
  });
  Object.defineProperty(Tolgee2.prototype, "defaultLanguage", {
    get: function() {
      return this.properties.config.defaultLanguage;
    },
    enumerable: false,
    configurable: true
  });
  Object.defineProperty(Tolgee2.prototype, "onLangChange", {
    get: function() {
      return this.dependencyService.eventService.LANGUAGE_CHANGED;
    },
    enumerable: false,
    configurable: true
  });
  Object.defineProperty(Tolgee2.prototype, "onTranslationChange", {
    get: function() {
      return this.dependencyService.eventService.TRANSLATION_CHANGED;
    },
    enumerable: false,
    configurable: true
  });
  Object.defineProperty(Tolgee2.prototype, "onLangLoaded", {
    get: function() {
      return this.dependencyService.eventService.LANGUAGE_LOADED;
    },
    enumerable: false,
    configurable: true
  });
  Object.defineProperty(Tolgee2.prototype, "initialLoading", {
    get: function() {
      var _a2, _b;
      var currentLang = this.properties.currentLanguage;
      var fallbackLang = this.properties.config.fallbackLanguage;
      var fallbackPreloading = this.properties.config.preloadFallback;
      var isStaticDataProvided = function(data) {
        return data !== void 0 && typeof data !== "function";
      };
      return !isStaticDataProvided((_a2 = this.properties.config.staticData) === null || _a2 === void 0 ? void 0 : _a2[currentLang]) || !!fallbackPreloading && !isStaticDataProvided((_b = this.properties.config.staticData) === null || _b === void 0 ? void 0 : _b[fallbackLang]);
    },
    enumerable: false,
    configurable: true
  });
  Object.defineProperty(Tolgee2.prototype, "coreService", {
    get: function() {
      return this.dependencyService.coreService;
    },
    enumerable: false,
    configurable: true
  });
  Tolgee2.use = function(module) {
    return new Tolgee2().use(module);
  };
  Tolgee2.init = function(config) {
    return new Tolgee2().init(config);
  };
  Tolgee2.prototype.changeLanguage = function(newLanguage) {
    return __awaiter(this, void 0, void 0, function() {
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            return [4, this.dependencyService.translationService.loadTranslations(newLanguage)];
          case 1:
            _a2.sent();
            this.properties.currentLanguage = newLanguage;
            this.emitLangChangeEvent(newLanguage);
            return [2];
        }
      });
    });
  };
  Tolgee2.prototype.use = function(module) {
    this.dependencyService.moduleService.addModule(module);
    return this;
  };
  Tolgee2.prototype.init = function(config) {
    this.dependencyService.init(config);
    var _a2 = this.dependencyService.properties.config, apiKey = _a2.apiKey, apiUrl = _a2.apiUrl;
    this.dependencyService.properties.mode = apiKey && apiUrl ? "development" : "production";
    return this;
  };
  Tolgee2.prototype.run = function() {
    return __awaiter(this, void 0, void 0, function() {
      var e_1;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            this.dependencyService.run();
            if (!(this.properties.mode === "development"))
              return [3, 4];
            _a2.label = 1;
          case 1:
            _a2.trys.push([1, 3, , 4]);
            return [4, this.coreService.loadApiKeyDetails()];
          case 2:
            _a2.sent();
            return [3, 4];
          case 3:
            e_1 = _a2.sent();
            console.error("Couldn't connect to Tolgee");
            console.error(e_1);
            this.properties.mode = "production";
            return [3, 4];
          case 4:
            return [4, this.dependencyService.translationService.loadTranslations()];
          case 5:
            _a2.sent();
            return [4, this.dependencyService.pluginManager.run()];
          case 6:
            _a2.sent();
            if (!this.properties.config.preloadFallback)
              return [3, 8];
            return [4, this.dependencyService.translationService.loadTranslations(this.properties.config.fallbackLanguage)];
          case 7:
            _a2.sent();
            _a2.label = 8;
          case 8:
            return [4, this.refresh()];
          case 9:
            _a2.sent();
            if (this.properties.config.watch) {
              this.dependencyService.observer.observe();
            }
            return [2];
        }
      });
    });
  };
  Tolgee2.prototype.refresh = function() {
    return __awaiter(this, void 0, void 0, function() {
      return __generator(this, function(_a2) {
        return [2, this.dependencyService.wrapper.handleSubtree(this.properties.config.targetElement)];
      });
    });
  };
  Tolgee2.prototype.translate = function(keyOrProps, params, noWrap, defaultValue) {
    if (params === void 0) {
      params = {};
    }
    if (noWrap === void 0) {
      noWrap = false;
    }
    if (defaultValue === void 0) {
      defaultValue = void 0;
    }
    return __awaiter(this, void 0, void 0, function() {
      var key, orEmpty, props, translation;
      return __generator(this, function(_a2) {
        switch (_a2.label) {
          case 0:
            key = typeof keyOrProps === "string" ? keyOrProps : keyOrProps.key;
            orEmpty = void 0;
            if (typeof keyOrProps === "object") {
              props = keyOrProps;
              params = props.params !== void 0 ? props.params : params;
              noWrap = props.noWrap !== void 0 ? props.noWrap : noWrap;
              defaultValue = props.defaultValue !== void 0 ? props.defaultValue : defaultValue;
              orEmpty = props.orEmpty;
            }
            return [4, this.dependencyService.textService.translate(key, params, void 0, orEmpty, defaultValue)];
          case 1:
            translation = _a2.sent();
            if (!(this.properties.mode === "development" && !noWrap))
              return [3, 3];
            return [4, this.coreService.loadApiKeyDetails()];
          case 2:
            _a2.sent();
            return [2, this.dependencyService.wrapper.wrap(key, params, defaultValue, translation)];
          case 3:
            return [2, translation];
        }
      });
    });
  };
  Tolgee2.prototype.wrap = function(key, params, defaultValue, translation) {
    if (this.properties.mode === "development") {
      return this.dependencyService.wrapper.wrap(key, params, defaultValue, translation);
    } else {
      return translation || defaultValue;
    }
  };
  Tolgee2.prototype.instant = function(keyOrProps, params, noWrap, orEmpty, defaultValue) {
    if (params === void 0) {
      params = {};
    }
    if (noWrap === void 0) {
      noWrap = false;
    }
    var key = typeof keyOrProps === "string" ? keyOrProps : keyOrProps.key;
    if (typeof keyOrProps === "object") {
      var props = keyOrProps;
      params = props.params !== void 0 ? props.params : params;
      noWrap = props.noWrap !== void 0 ? props.noWrap : noWrap;
      defaultValue = props.defaultValue !== void 0 ? props.defaultValue : defaultValue;
      orEmpty = props.orEmpty !== void 0 ? props.orEmpty : orEmpty;
    }
    var translation = this.dependencyService.textService.instant(key, params, void 0, orEmpty, defaultValue);
    if (this.properties.mode === "development" && !noWrap) {
      return this.dependencyService.wrapper.wrap(key, params, defaultValue, translation);
    }
    return translation;
  };
  Tolgee2.prototype.getCachedTranslations = function() {
    return this.dependencyService.translationService.getCachedTranslations();
  };
  Tolgee2.prototype.loadTranslations = function(lang) {
    return this.dependencyService.translationService.loadTranslations(lang);
  };
  Tolgee2.prototype.emitLangChangeEvent = function(value) {
    var langChangedEmitter = this.onLangChange;
    langChangedEmitter.emit(value);
  };
  return Tolgee2;
}();
var ErrorKind;
(function(ErrorKind2) {
  ErrorKind2[ErrorKind2["EXPECT_ARGUMENT_CLOSING_BRACE"] = 1] = "EXPECT_ARGUMENT_CLOSING_BRACE";
  ErrorKind2[ErrorKind2["EMPTY_ARGUMENT"] = 2] = "EMPTY_ARGUMENT";
  ErrorKind2[ErrorKind2["MALFORMED_ARGUMENT"] = 3] = "MALFORMED_ARGUMENT";
  ErrorKind2[ErrorKind2["EXPECT_ARGUMENT_TYPE"] = 4] = "EXPECT_ARGUMENT_TYPE";
  ErrorKind2[ErrorKind2["INVALID_ARGUMENT_TYPE"] = 5] = "INVALID_ARGUMENT_TYPE";
  ErrorKind2[ErrorKind2["EXPECT_ARGUMENT_STYLE"] = 6] = "EXPECT_ARGUMENT_STYLE";
  ErrorKind2[ErrorKind2["INVALID_NUMBER_SKELETON"] = 7] = "INVALID_NUMBER_SKELETON";
  ErrorKind2[ErrorKind2["INVALID_DATE_TIME_SKELETON"] = 8] = "INVALID_DATE_TIME_SKELETON";
  ErrorKind2[ErrorKind2["EXPECT_NUMBER_SKELETON"] = 9] = "EXPECT_NUMBER_SKELETON";
  ErrorKind2[ErrorKind2["EXPECT_DATE_TIME_SKELETON"] = 10] = "EXPECT_DATE_TIME_SKELETON";
  ErrorKind2[ErrorKind2["UNCLOSED_QUOTE_IN_ARGUMENT_STYLE"] = 11] = "UNCLOSED_QUOTE_IN_ARGUMENT_STYLE";
  ErrorKind2[ErrorKind2["EXPECT_SELECT_ARGUMENT_OPTIONS"] = 12] = "EXPECT_SELECT_ARGUMENT_OPTIONS";
  ErrorKind2[ErrorKind2["EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE"] = 13] = "EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE";
  ErrorKind2[ErrorKind2["INVALID_PLURAL_ARGUMENT_OFFSET_VALUE"] = 14] = "INVALID_PLURAL_ARGUMENT_OFFSET_VALUE";
  ErrorKind2[ErrorKind2["EXPECT_SELECT_ARGUMENT_SELECTOR"] = 15] = "EXPECT_SELECT_ARGUMENT_SELECTOR";
  ErrorKind2[ErrorKind2["EXPECT_PLURAL_ARGUMENT_SELECTOR"] = 16] = "EXPECT_PLURAL_ARGUMENT_SELECTOR";
  ErrorKind2[ErrorKind2["EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT"] = 17] = "EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT";
  ErrorKind2[ErrorKind2["EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT"] = 18] = "EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT";
  ErrorKind2[ErrorKind2["INVALID_PLURAL_ARGUMENT_SELECTOR"] = 19] = "INVALID_PLURAL_ARGUMENT_SELECTOR";
  ErrorKind2[ErrorKind2["DUPLICATE_PLURAL_ARGUMENT_SELECTOR"] = 20] = "DUPLICATE_PLURAL_ARGUMENT_SELECTOR";
  ErrorKind2[ErrorKind2["DUPLICATE_SELECT_ARGUMENT_SELECTOR"] = 21] = "DUPLICATE_SELECT_ARGUMENT_SELECTOR";
  ErrorKind2[ErrorKind2["MISSING_OTHER_CLAUSE"] = 22] = "MISSING_OTHER_CLAUSE";
  ErrorKind2[ErrorKind2["INVALID_TAG"] = 23] = "INVALID_TAG";
  ErrorKind2[ErrorKind2["INVALID_TAG_NAME"] = 25] = "INVALID_TAG_NAME";
  ErrorKind2[ErrorKind2["UNMATCHED_CLOSING_TAG"] = 26] = "UNMATCHED_CLOSING_TAG";
  ErrorKind2[ErrorKind2["UNCLOSED_TAG"] = 27] = "UNCLOSED_TAG";
})(ErrorKind || (ErrorKind = {}));
var TYPE;
(function(TYPE2) {
  TYPE2[TYPE2["literal"] = 0] = "literal";
  TYPE2[TYPE2["argument"] = 1] = "argument";
  TYPE2[TYPE2["number"] = 2] = "number";
  TYPE2[TYPE2["date"] = 3] = "date";
  TYPE2[TYPE2["time"] = 4] = "time";
  TYPE2[TYPE2["select"] = 5] = "select";
  TYPE2[TYPE2["plural"] = 6] = "plural";
  TYPE2[TYPE2["pound"] = 7] = "pound";
  TYPE2[TYPE2["tag"] = 8] = "tag";
})(TYPE || (TYPE = {}));
var SKELETON_TYPE;
(function(SKELETON_TYPE2) {
  SKELETON_TYPE2[SKELETON_TYPE2["number"] = 0] = "number";
  SKELETON_TYPE2[SKELETON_TYPE2["dateTime"] = 1] = "dateTime";
})(SKELETON_TYPE || (SKELETON_TYPE = {}));
function isLiteralElement(el) {
  return el.type === TYPE.literal;
}
function isArgumentElement(el) {
  return el.type === TYPE.argument;
}
function isNumberElement(el) {
  return el.type === TYPE.number;
}
function isDateElement(el) {
  return el.type === TYPE.date;
}
function isTimeElement(el) {
  return el.type === TYPE.time;
}
function isSelectElement(el) {
  return el.type === TYPE.select;
}
function isPluralElement(el) {
  return el.type === TYPE.plural;
}
function isPoundElement(el) {
  return el.type === TYPE.pound;
}
function isTagElement(el) {
  return el.type === TYPE.tag;
}
function isNumberSkeleton(el) {
  return !!(el && typeof el === "object" && el.type === SKELETON_TYPE.number);
}
function isDateTimeSkeleton(el) {
  return !!(el && typeof el === "object" && el.type === SKELETON_TYPE.dateTime);
}
var SPACE_SEPARATOR_REGEX = /[ \xA0\u1680\u2000-\u200A\u202F\u205F\u3000]/;
var DATE_TIME_REGEX = /(?:[Eec]{1,6}|G{1,5}|[Qq]{1,5}|(?:[yYur]+|U{1,5})|[ML]{1,5}|d{1,2}|D{1,3}|F{1}|[abB]{1,5}|[hkHK]{1,2}|w{1,2}|W{1}|m{1,2}|s{1,2}|[zZOvVxX]{1,4})(?=([^']*'[^']*')*[^']*$)/g;
function parseDateTimeSkeleton(skeleton) {
  var result = {};
  skeleton.replace(DATE_TIME_REGEX, function(match) {
    var len = match.length;
    switch (match[0]) {
      case "G":
        result.era = len === 4 ? "long" : len === 5 ? "narrow" : "short";
        break;
      case "y":
        result.year = len === 2 ? "2-digit" : "numeric";
        break;
      case "Y":
      case "u":
      case "U":
      case "r":
        throw new RangeError("`Y/u/U/r` (year) patterns are not supported, use `y` instead");
      case "q":
      case "Q":
        throw new RangeError("`q/Q` (quarter) patterns are not supported");
      case "M":
      case "L":
        result.month = ["numeric", "2-digit", "short", "long", "narrow"][len - 1];
        break;
      case "w":
      case "W":
        throw new RangeError("`w/W` (week) patterns are not supported");
      case "d":
        result.day = ["numeric", "2-digit"][len - 1];
        break;
      case "D":
      case "F":
      case "g":
        throw new RangeError("`D/F/g` (day) patterns are not supported, use `d` instead");
      case "E":
        result.weekday = len === 4 ? "short" : len === 5 ? "narrow" : "short";
        break;
      case "e":
        if (len < 4) {
          throw new RangeError("`e..eee` (weekday) patterns are not supported");
        }
        result.weekday = ["short", "long", "narrow", "short"][len - 4];
        break;
      case "c":
        if (len < 4) {
          throw new RangeError("`c..ccc` (weekday) patterns are not supported");
        }
        result.weekday = ["short", "long", "narrow", "short"][len - 4];
        break;
      case "a":
        result.hour12 = true;
        break;
      case "b":
      case "B":
        throw new RangeError("`b/B` (period) patterns are not supported, use `a` instead");
      case "h":
        result.hourCycle = "h12";
        result.hour = ["numeric", "2-digit"][len - 1];
        break;
      case "H":
        result.hourCycle = "h23";
        result.hour = ["numeric", "2-digit"][len - 1];
        break;
      case "K":
        result.hourCycle = "h11";
        result.hour = ["numeric", "2-digit"][len - 1];
        break;
      case "k":
        result.hourCycle = "h24";
        result.hour = ["numeric", "2-digit"][len - 1];
        break;
      case "j":
      case "J":
      case "C":
        throw new RangeError("`j/J/C` (hour) patterns are not supported, use `h/H/K/k` instead");
      case "m":
        result.minute = ["numeric", "2-digit"][len - 1];
        break;
      case "s":
        result.second = ["numeric", "2-digit"][len - 1];
        break;
      case "S":
      case "A":
        throw new RangeError("`S/A` (second) patterns are not supported, use `s` instead");
      case "z":
        result.timeZoneName = len < 4 ? "short" : "long";
        break;
      case "Z":
      case "O":
      case "v":
      case "V":
      case "X":
      case "x":
        throw new RangeError("`Z/O/v/V/X/x` (timeZone) patterns are not supported, use `z` instead");
    }
    return "";
  });
  return result;
}
var WHITE_SPACE_REGEX = /[\t-\r \x85\u200E\u200F\u2028\u2029]/i;
function parseNumberSkeletonFromString(skeleton) {
  if (skeleton.length === 0) {
    throw new Error("Number skeleton cannot be empty");
  }
  var stringTokens = skeleton.split(WHITE_SPACE_REGEX).filter(function(x) {
    return x.length > 0;
  });
  var tokens = [];
  for (var _i = 0, stringTokens_1 = stringTokens; _i < stringTokens_1.length; _i++) {
    var stringToken = stringTokens_1[_i];
    var stemAndOptions = stringToken.split("/");
    if (stemAndOptions.length === 0) {
      throw new Error("Invalid number skeleton");
    }
    var stem = stemAndOptions[0], options = stemAndOptions.slice(1);
    for (var _a2 = 0, options_1 = options; _a2 < options_1.length; _a2++) {
      var option = options_1[_a2];
      if (option.length === 0) {
        throw new Error("Invalid number skeleton");
      }
    }
    tokens.push({ stem, options });
  }
  return tokens;
}
function icuUnitToEcma(unit) {
  return unit.replace(/^(.*?)-/, "");
}
var FRACTION_PRECISION_REGEX = /^\.(?:(0+)(\*)?|(#+)|(0+)(#+))$/g;
var SIGNIFICANT_PRECISION_REGEX = /^(@+)?(\+|#+)?[rs]?$/g;
var INTEGER_WIDTH_REGEX = /(\*)(0+)|(#+)(0+)|(0+)/g;
var CONCISE_INTEGER_WIDTH_REGEX = /^(0+)$/;
function parseSignificantPrecision(str) {
  var result = {};
  if (str[str.length - 1] === "r") {
    result.roundingPriority = "morePrecision";
  } else if (str[str.length - 1] === "s") {
    result.roundingPriority = "lessPrecision";
  }
  str.replace(SIGNIFICANT_PRECISION_REGEX, function(_, g1, g2) {
    if (typeof g2 !== "string") {
      result.minimumSignificantDigits = g1.length;
      result.maximumSignificantDigits = g1.length;
    } else if (g2 === "+") {
      result.minimumSignificantDigits = g1.length;
    } else if (g1[0] === "#") {
      result.maximumSignificantDigits = g1.length;
    } else {
      result.minimumSignificantDigits = g1.length;
      result.maximumSignificantDigits = g1.length + (typeof g2 === "string" ? g2.length : 0);
    }
    return "";
  });
  return result;
}
function parseSign(str) {
  switch (str) {
    case "sign-auto":
      return {
        signDisplay: "auto"
      };
    case "sign-accounting":
    case "()":
      return {
        currencySign: "accounting"
      };
    case "sign-always":
    case "+!":
      return {
        signDisplay: "always"
      };
    case "sign-accounting-always":
    case "()!":
      return {
        signDisplay: "always",
        currencySign: "accounting"
      };
    case "sign-except-zero":
    case "+?":
      return {
        signDisplay: "exceptZero"
      };
    case "sign-accounting-except-zero":
    case "()?":
      return {
        signDisplay: "exceptZero",
        currencySign: "accounting"
      };
    case "sign-never":
    case "+_":
      return {
        signDisplay: "never"
      };
  }
}
function parseConciseScientificAndEngineeringStem(stem) {
  var result;
  if (stem[0] === "E" && stem[1] === "E") {
    result = {
      notation: "engineering"
    };
    stem = stem.slice(2);
  } else if (stem[0] === "E") {
    result = {
      notation: "scientific"
    };
    stem = stem.slice(1);
  }
  if (result) {
    var signDisplay = stem.slice(0, 2);
    if (signDisplay === "+!") {
      result.signDisplay = "always";
      stem = stem.slice(2);
    } else if (signDisplay === "+?") {
      result.signDisplay = "exceptZero";
      stem = stem.slice(2);
    }
    if (!CONCISE_INTEGER_WIDTH_REGEX.test(stem)) {
      throw new Error("Malformed concise eng/scientific notation");
    }
    result.minimumIntegerDigits = stem.length;
  }
  return result;
}
function parseNotationOptions(opt) {
  var result = {};
  var signOpts = parseSign(opt);
  if (signOpts) {
    return signOpts;
  }
  return result;
}
function parseNumberSkeleton(tokens) {
  var result = {};
  for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
    var token = tokens_1[_i];
    switch (token.stem) {
      case "percent":
      case "%":
        result.style = "percent";
        continue;
      case "%x100":
        result.style = "percent";
        result.scale = 100;
        continue;
      case "currency":
        result.style = "currency";
        result.currency = token.options[0];
        continue;
      case "group-off":
      case ",_":
        result.useGrouping = false;
        continue;
      case "precision-integer":
      case ".":
        result.maximumFractionDigits = 0;
        continue;
      case "measure-unit":
      case "unit":
        result.style = "unit";
        result.unit = icuUnitToEcma(token.options[0]);
        continue;
      case "compact-short":
      case "K":
        result.notation = "compact";
        result.compactDisplay = "short";
        continue;
      case "compact-long":
      case "KK":
        result.notation = "compact";
        result.compactDisplay = "long";
        continue;
      case "scientific":
        result = __assign$1(__assign$1(__assign$1({}, result), { notation: "scientific" }), token.options.reduce(function(all, opt2) {
          return __assign$1(__assign$1({}, all), parseNotationOptions(opt2));
        }, {}));
        continue;
      case "engineering":
        result = __assign$1(__assign$1(__assign$1({}, result), { notation: "engineering" }), token.options.reduce(function(all, opt2) {
          return __assign$1(__assign$1({}, all), parseNotationOptions(opt2));
        }, {}));
        continue;
      case "notation-simple":
        result.notation = "standard";
        continue;
      case "unit-width-narrow":
        result.currencyDisplay = "narrowSymbol";
        result.unitDisplay = "narrow";
        continue;
      case "unit-width-short":
        result.currencyDisplay = "code";
        result.unitDisplay = "short";
        continue;
      case "unit-width-full-name":
        result.currencyDisplay = "name";
        result.unitDisplay = "long";
        continue;
      case "unit-width-iso-code":
        result.currencyDisplay = "symbol";
        continue;
      case "scale":
        result.scale = parseFloat(token.options[0]);
        continue;
      case "integer-width":
        if (token.options.length > 1) {
          throw new RangeError("integer-width stems only accept a single optional option");
        }
        token.options[0].replace(INTEGER_WIDTH_REGEX, function(_, g1, g2, g3, g4, g5) {
          if (g1) {
            result.minimumIntegerDigits = g2.length;
          } else if (g3 && g4) {
            throw new Error("We currently do not support maximum integer digits");
          } else if (g5) {
            throw new Error("We currently do not support exact integer digits");
          }
          return "";
        });
        continue;
    }
    if (CONCISE_INTEGER_WIDTH_REGEX.test(token.stem)) {
      result.minimumIntegerDigits = token.stem.length;
      continue;
    }
    if (FRACTION_PRECISION_REGEX.test(token.stem)) {
      if (token.options.length > 1) {
        throw new RangeError("Fraction-precision stems only accept a single optional option");
      }
      token.stem.replace(FRACTION_PRECISION_REGEX, function(_, g1, g2, g3, g4, g5) {
        if (g2 === "*") {
          result.minimumFractionDigits = g1.length;
        } else if (g3 && g3[0] === "#") {
          result.maximumFractionDigits = g3.length;
        } else if (g4 && g5) {
          result.minimumFractionDigits = g4.length;
          result.maximumFractionDigits = g4.length + g5.length;
        } else {
          result.minimumFractionDigits = g1.length;
          result.maximumFractionDigits = g1.length;
        }
        return "";
      });
      var opt = token.options[0];
      if (opt === "w") {
        result = __assign$1(__assign$1({}, result), { trailingZeroDisplay: "stripIfInteger" });
      } else if (opt) {
        result = __assign$1(__assign$1({}, result), parseSignificantPrecision(opt));
      }
      continue;
    }
    if (SIGNIFICANT_PRECISION_REGEX.test(token.stem)) {
      result = __assign$1(__assign$1({}, result), parseSignificantPrecision(token.stem));
      continue;
    }
    var signOpts = parseSign(token.stem);
    if (signOpts) {
      result = __assign$1(__assign$1({}, result), signOpts);
    }
    var conciseScientificAndEngineeringOpts = parseConciseScientificAndEngineeringStem(token.stem);
    if (conciseScientificAndEngineeringOpts) {
      result = __assign$1(__assign$1({}, result), conciseScientificAndEngineeringOpts);
    }
  }
  return result;
}
var _a$1;
var SPACE_SEPARATOR_START_REGEX = new RegExp("^".concat(SPACE_SEPARATOR_REGEX.source, "*"));
var SPACE_SEPARATOR_END_REGEX = new RegExp("".concat(SPACE_SEPARATOR_REGEX.source, "*$"));
function createLocation(start, end) {
  return { start, end };
}
var hasNativeStartsWith = !!String.prototype.startsWith;
var hasNativeFromCodePoint = !!String.fromCodePoint;
var hasNativeFromEntries = !!Object.fromEntries;
var hasNativeCodePointAt = !!String.prototype.codePointAt;
var hasTrimStart = !!String.prototype.trimStart;
var hasTrimEnd = !!String.prototype.trimEnd;
var hasNativeIsSafeInteger = !!Number.isSafeInteger;
var isSafeInteger = hasNativeIsSafeInteger ? Number.isSafeInteger : function(n) {
  return typeof n === "number" && isFinite(n) && Math.floor(n) === n && Math.abs(n) <= 9007199254740991;
};
var REGEX_SUPPORTS_U_AND_Y = true;
try {
  var re = RE("([^\\p{White_Space}\\p{Pattern_Syntax}]*)", "yu");
  REGEX_SUPPORTS_U_AND_Y = ((_a$1 = re.exec("a")) === null || _a$1 === void 0 ? void 0 : _a$1[0]) === "a";
} catch (_) {
  REGEX_SUPPORTS_U_AND_Y = false;
}
var startsWith = hasNativeStartsWith ? function startsWith2(s, search, position) {
  return s.startsWith(search, position);
} : function startsWith3(s, search, position) {
  return s.slice(position, position + search.length) === search;
};
var fromCodePoint = hasNativeFromCodePoint ? String.fromCodePoint : function fromCodePoint2() {
  var codePoints = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    codePoints[_i] = arguments[_i];
  }
  var elements = "";
  var length = codePoints.length;
  var i = 0;
  var code;
  while (length > i) {
    code = codePoints[i++];
    if (code > 1114111)
      throw RangeError(code + " is not a valid code point");
    elements += code < 65536 ? String.fromCharCode(code) : String.fromCharCode(((code -= 65536) >> 10) + 55296, code % 1024 + 56320);
  }
  return elements;
};
var fromEntries = hasNativeFromEntries ? Object.fromEntries : function fromEntries2(entries) {
  var obj = {};
  for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
    var _a2 = entries_1[_i], k = _a2[0], v = _a2[1];
    obj[k] = v;
  }
  return obj;
};
var codePointAt = hasNativeCodePointAt ? function codePointAt2(s, index) {
  return s.codePointAt(index);
} : function codePointAt3(s, index) {
  var size2 = s.length;
  if (index < 0 || index >= size2) {
    return void 0;
  }
  var first = s.charCodeAt(index);
  var second;
  return first < 55296 || first > 56319 || index + 1 === size2 || (second = s.charCodeAt(index + 1)) < 56320 || second > 57343 ? first : (first - 55296 << 10) + (second - 56320) + 65536;
};
var trimStart = hasTrimStart ? function trimStart2(s) {
  return s.trimStart();
} : function trimStart3(s) {
  return s.replace(SPACE_SEPARATOR_START_REGEX, "");
};
var trimEnd = hasTrimEnd ? function trimEnd2(s) {
  return s.trimEnd();
} : function trimEnd3(s) {
  return s.replace(SPACE_SEPARATOR_END_REGEX, "");
};
function RE(s, flag) {
  return new RegExp(s, flag);
}
var matchIdentifierAtIndex;
if (REGEX_SUPPORTS_U_AND_Y) {
  var IDENTIFIER_PREFIX_RE_1 = RE("([^\\p{White_Space}\\p{Pattern_Syntax}]*)", "yu");
  matchIdentifierAtIndex = function matchIdentifierAtIndex2(s, index) {
    var _a2;
    IDENTIFIER_PREFIX_RE_1.lastIndex = index;
    var match = IDENTIFIER_PREFIX_RE_1.exec(s);
    return (_a2 = match[1]) !== null && _a2 !== void 0 ? _a2 : "";
  };
} else {
  matchIdentifierAtIndex = function matchIdentifierAtIndex2(s, index) {
    var match = [];
    while (true) {
      var c = codePointAt(s, index);
      if (c === void 0 || _isWhiteSpace(c) || _isPatternSyntax(c)) {
        break;
      }
      match.push(c);
      index += c >= 65536 ? 2 : 1;
    }
    return fromCodePoint.apply(void 0, match);
  };
}
var Parser = function() {
  function Parser2(message, options) {
    if (options === void 0) {
      options = {};
    }
    this.message = message;
    this.position = { offset: 0, line: 1, column: 1 };
    this.ignoreTag = !!options.ignoreTag;
    this.requiresOtherClause = !!options.requiresOtherClause;
    this.shouldParseSkeletons = !!options.shouldParseSkeletons;
  }
  Parser2.prototype.parse = function() {
    if (this.offset() !== 0) {
      throw Error("parser can only be used once");
    }
    return this.parseMessage(0, "", false);
  };
  Parser2.prototype.parseMessage = function(nestingLevel, parentArgType, expectingCloseTag) {
    var elements = [];
    while (!this.isEOF()) {
      var char = this.char();
      if (char === 123) {
        var result = this.parseArgument(nestingLevel, expectingCloseTag);
        if (result.err) {
          return result;
        }
        elements.push(result.val);
      } else if (char === 125 && nestingLevel > 0) {
        break;
      } else if (char === 35 && (parentArgType === "plural" || parentArgType === "selectordinal")) {
        var position = this.clonePosition();
        this.bump();
        elements.push({
          type: TYPE.pound,
          location: createLocation(position, this.clonePosition())
        });
      } else if (char === 60 && !this.ignoreTag && this.peek() === 47) {
        if (expectingCloseTag) {
          break;
        } else {
          return this.error(ErrorKind.UNMATCHED_CLOSING_TAG, createLocation(this.clonePosition(), this.clonePosition()));
        }
      } else if (char === 60 && !this.ignoreTag && _isAlpha(this.peek() || 0)) {
        var result = this.parseTag(nestingLevel, parentArgType);
        if (result.err) {
          return result;
        }
        elements.push(result.val);
      } else {
        var result = this.parseLiteral(nestingLevel, parentArgType);
        if (result.err) {
          return result;
        }
        elements.push(result.val);
      }
    }
    return { val: elements, err: null };
  };
  Parser2.prototype.parseTag = function(nestingLevel, parentArgType) {
    var startPosition = this.clonePosition();
    this.bump();
    var tagName = this.parseTagName();
    this.bumpSpace();
    if (this.bumpIf("/>")) {
      return {
        val: {
          type: TYPE.literal,
          value: "<".concat(tagName, "/>"),
          location: createLocation(startPosition, this.clonePosition())
        },
        err: null
      };
    } else if (this.bumpIf(">")) {
      var childrenResult = this.parseMessage(nestingLevel + 1, parentArgType, true);
      if (childrenResult.err) {
        return childrenResult;
      }
      var children = childrenResult.val;
      var endTagStartPosition = this.clonePosition();
      if (this.bumpIf("</")) {
        if (this.isEOF() || !_isAlpha(this.char())) {
          return this.error(ErrorKind.INVALID_TAG, createLocation(endTagStartPosition, this.clonePosition()));
        }
        var closingTagNameStartPosition = this.clonePosition();
        var closingTagName = this.parseTagName();
        if (tagName !== closingTagName) {
          return this.error(ErrorKind.UNMATCHED_CLOSING_TAG, createLocation(closingTagNameStartPosition, this.clonePosition()));
        }
        this.bumpSpace();
        if (!this.bumpIf(">")) {
          return this.error(ErrorKind.INVALID_TAG, createLocation(endTagStartPosition, this.clonePosition()));
        }
        return {
          val: {
            type: TYPE.tag,
            value: tagName,
            children,
            location: createLocation(startPosition, this.clonePosition())
          },
          err: null
        };
      } else {
        return this.error(ErrorKind.UNCLOSED_TAG, createLocation(startPosition, this.clonePosition()));
      }
    } else {
      return this.error(ErrorKind.INVALID_TAG, createLocation(startPosition, this.clonePosition()));
    }
  };
  Parser2.prototype.parseTagName = function() {
    var startOffset = this.offset();
    this.bump();
    while (!this.isEOF() && _isPotentialElementNameChar(this.char())) {
      this.bump();
    }
    return this.message.slice(startOffset, this.offset());
  };
  Parser2.prototype.parseLiteral = function(nestingLevel, parentArgType) {
    var start = this.clonePosition();
    var value = "";
    while (true) {
      var parseQuoteResult = this.tryParseQuote(parentArgType);
      if (parseQuoteResult) {
        value += parseQuoteResult;
        continue;
      }
      var parseUnquotedResult = this.tryParseUnquoted(nestingLevel, parentArgType);
      if (parseUnquotedResult) {
        value += parseUnquotedResult;
        continue;
      }
      var parseLeftAngleResult = this.tryParseLeftAngleBracket();
      if (parseLeftAngleResult) {
        value += parseLeftAngleResult;
        continue;
      }
      break;
    }
    var location2 = createLocation(start, this.clonePosition());
    return {
      val: { type: TYPE.literal, value, location: location2 },
      err: null
    };
  };
  Parser2.prototype.tryParseLeftAngleBracket = function() {
    if (!this.isEOF() && this.char() === 60 && (this.ignoreTag || !_isAlphaOrSlash(this.peek() || 0))) {
      this.bump();
      return "<";
    }
    return null;
  };
  Parser2.prototype.tryParseQuote = function(parentArgType) {
    if (this.isEOF() || this.char() !== 39) {
      return null;
    }
    switch (this.peek()) {
      case 39:
        this.bump();
        this.bump();
        return "'";
      case 123:
      case 60:
      case 62:
      case 125:
        break;
      case 35:
        if (parentArgType === "plural" || parentArgType === "selectordinal") {
          break;
        }
        return null;
      default:
        return null;
    }
    this.bump();
    var codePoints = [this.char()];
    this.bump();
    while (!this.isEOF()) {
      var ch = this.char();
      if (ch === 39) {
        if (this.peek() === 39) {
          codePoints.push(39);
          this.bump();
        } else {
          this.bump();
          break;
        }
      } else {
        codePoints.push(ch);
      }
      this.bump();
    }
    return fromCodePoint.apply(void 0, codePoints);
  };
  Parser2.prototype.tryParseUnquoted = function(nestingLevel, parentArgType) {
    if (this.isEOF()) {
      return null;
    }
    var ch = this.char();
    if (ch === 60 || ch === 123 || ch === 35 && (parentArgType === "plural" || parentArgType === "selectordinal") || ch === 125 && nestingLevel > 0) {
      return null;
    } else {
      this.bump();
      return fromCodePoint(ch);
    }
  };
  Parser2.prototype.parseArgument = function(nestingLevel, expectingCloseTag) {
    var openingBracePosition = this.clonePosition();
    this.bump();
    this.bumpSpace();
    if (this.isEOF()) {
      return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));
    }
    if (this.char() === 125) {
      this.bump();
      return this.error(ErrorKind.EMPTY_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));
    }
    var value = this.parseIdentifierIfPossible().value;
    if (!value) {
      return this.error(ErrorKind.MALFORMED_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));
    }
    this.bumpSpace();
    if (this.isEOF()) {
      return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));
    }
    switch (this.char()) {
      case 125: {
        this.bump();
        return {
          val: {
            type: TYPE.argument,
            value,
            location: createLocation(openingBracePosition, this.clonePosition())
          },
          err: null
        };
      }
      case 44: {
        this.bump();
        this.bumpSpace();
        if (this.isEOF()) {
          return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));
        }
        return this.parseArgumentOptions(nestingLevel, expectingCloseTag, value, openingBracePosition);
      }
      default:
        return this.error(ErrorKind.MALFORMED_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));
    }
  };
  Parser2.prototype.parseIdentifierIfPossible = function() {
    var startingPosition = this.clonePosition();
    var startOffset = this.offset();
    var value = matchIdentifierAtIndex(this.message, startOffset);
    var endOffset = startOffset + value.length;
    this.bumpTo(endOffset);
    var endPosition = this.clonePosition();
    var location2 = createLocation(startingPosition, endPosition);
    return { value, location: location2 };
  };
  Parser2.prototype.parseArgumentOptions = function(nestingLevel, expectingCloseTag, value, openingBracePosition) {
    var _a2;
    var typeStartPosition = this.clonePosition();
    var argType = this.parseIdentifierIfPossible().value;
    var typeEndPosition = this.clonePosition();
    switch (argType) {
      case "":
        return this.error(ErrorKind.EXPECT_ARGUMENT_TYPE, createLocation(typeStartPosition, typeEndPosition));
      case "number":
      case "date":
      case "time": {
        this.bumpSpace();
        var styleAndLocation = null;
        if (this.bumpIf(",")) {
          this.bumpSpace();
          var styleStartPosition = this.clonePosition();
          var result = this.parseSimpleArgStyleIfPossible();
          if (result.err) {
            return result;
          }
          var style = trimEnd(result.val);
          if (style.length === 0) {
            return this.error(ErrorKind.EXPECT_ARGUMENT_STYLE, createLocation(this.clonePosition(), this.clonePosition()));
          }
          var styleLocation = createLocation(styleStartPosition, this.clonePosition());
          styleAndLocation = { style, styleLocation };
        }
        var argCloseResult = this.tryParseArgumentClose(openingBracePosition);
        if (argCloseResult.err) {
          return argCloseResult;
        }
        var location_1 = createLocation(openingBracePosition, this.clonePosition());
        if (styleAndLocation && startsWith(styleAndLocation === null || styleAndLocation === void 0 ? void 0 : styleAndLocation.style, "::", 0)) {
          var skeleton = trimStart(styleAndLocation.style.slice(2));
          if (argType === "number") {
            var result = this.parseNumberSkeletonFromString(skeleton, styleAndLocation.styleLocation);
            if (result.err) {
              return result;
            }
            return {
              val: { type: TYPE.number, value, location: location_1, style: result.val },
              err: null
            };
          } else {
            if (skeleton.length === 0) {
              return this.error(ErrorKind.EXPECT_DATE_TIME_SKELETON, location_1);
            }
            var style = {
              type: SKELETON_TYPE.dateTime,
              pattern: skeleton,
              location: styleAndLocation.styleLocation,
              parsedOptions: this.shouldParseSkeletons ? parseDateTimeSkeleton(skeleton) : {}
            };
            var type = argType === "date" ? TYPE.date : TYPE.time;
            return {
              val: { type, value, location: location_1, style },
              err: null
            };
          }
        }
        return {
          val: {
            type: argType === "number" ? TYPE.number : argType === "date" ? TYPE.date : TYPE.time,
            value,
            location: location_1,
            style: (_a2 = styleAndLocation === null || styleAndLocation === void 0 ? void 0 : styleAndLocation.style) !== null && _a2 !== void 0 ? _a2 : null
          },
          err: null
        };
      }
      case "plural":
      case "selectordinal":
      case "select": {
        var typeEndPosition_1 = this.clonePosition();
        this.bumpSpace();
        if (!this.bumpIf(",")) {
          return this.error(ErrorKind.EXPECT_SELECT_ARGUMENT_OPTIONS, createLocation(typeEndPosition_1, __assign$1({}, typeEndPosition_1)));
        }
        this.bumpSpace();
        var identifierAndLocation = this.parseIdentifierIfPossible();
        var pluralOffset = 0;
        if (argType !== "select" && identifierAndLocation.value === "offset") {
          if (!this.bumpIf(":")) {
            return this.error(ErrorKind.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE, createLocation(this.clonePosition(), this.clonePosition()));
          }
          this.bumpSpace();
          var result = this.tryParseDecimalInteger(ErrorKind.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE, ErrorKind.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE);
          if (result.err) {
            return result;
          }
          this.bumpSpace();
          identifierAndLocation = this.parseIdentifierIfPossible();
          pluralOffset = result.val;
        }
        var optionsResult = this.tryParsePluralOrSelectOptions(nestingLevel, argType, expectingCloseTag, identifierAndLocation);
        if (optionsResult.err) {
          return optionsResult;
        }
        var argCloseResult = this.tryParseArgumentClose(openingBracePosition);
        if (argCloseResult.err) {
          return argCloseResult;
        }
        var location_2 = createLocation(openingBracePosition, this.clonePosition());
        if (argType === "select") {
          return {
            val: {
              type: TYPE.select,
              value,
              options: fromEntries(optionsResult.val),
              location: location_2
            },
            err: null
          };
        } else {
          return {
            val: {
              type: TYPE.plural,
              value,
              options: fromEntries(optionsResult.val),
              offset: pluralOffset,
              pluralType: argType === "plural" ? "cardinal" : "ordinal",
              location: location_2
            },
            err: null
          };
        }
      }
      default:
        return this.error(ErrorKind.INVALID_ARGUMENT_TYPE, createLocation(typeStartPosition, typeEndPosition));
    }
  };
  Parser2.prototype.tryParseArgumentClose = function(openingBracePosition) {
    if (this.isEOF() || this.char() !== 125) {
      return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));
    }
    this.bump();
    return { val: true, err: null };
  };
  Parser2.prototype.parseSimpleArgStyleIfPossible = function() {
    var nestedBraces = 0;
    var startPosition = this.clonePosition();
    while (!this.isEOF()) {
      var ch = this.char();
      switch (ch) {
        case 39: {
          this.bump();
          var apostrophePosition = this.clonePosition();
          if (!this.bumpUntil("'")) {
            return this.error(ErrorKind.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE, createLocation(apostrophePosition, this.clonePosition()));
          }
          this.bump();
          break;
        }
        case 123: {
          nestedBraces += 1;
          this.bump();
          break;
        }
        case 125: {
          if (nestedBraces > 0) {
            nestedBraces -= 1;
          } else {
            return {
              val: this.message.slice(startPosition.offset, this.offset()),
              err: null
            };
          }
          break;
        }
        default:
          this.bump();
          break;
      }
    }
    return {
      val: this.message.slice(startPosition.offset, this.offset()),
      err: null
    };
  };
  Parser2.prototype.parseNumberSkeletonFromString = function(skeleton, location2) {
    var tokens = [];
    try {
      tokens = parseNumberSkeletonFromString(skeleton);
    } catch (e) {
      return this.error(ErrorKind.INVALID_NUMBER_SKELETON, location2);
    }
    return {
      val: {
        type: SKELETON_TYPE.number,
        tokens,
        location: location2,
        parsedOptions: this.shouldParseSkeletons ? parseNumberSkeleton(tokens) : {}
      },
      err: null
    };
  };
  Parser2.prototype.tryParsePluralOrSelectOptions = function(nestingLevel, parentArgType, expectCloseTag, parsedFirstIdentifier) {
    var _a2;
    var hasOtherClause = false;
    var options = [];
    var parsedSelectors = /* @__PURE__ */ new Set();
    var selector = parsedFirstIdentifier.value, selectorLocation = parsedFirstIdentifier.location;
    while (true) {
      if (selector.length === 0) {
        var startPosition = this.clonePosition();
        if (parentArgType !== "select" && this.bumpIf("=")) {
          var result = this.tryParseDecimalInteger(ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR, ErrorKind.INVALID_PLURAL_ARGUMENT_SELECTOR);
          if (result.err) {
            return result;
          }
          selectorLocation = createLocation(startPosition, this.clonePosition());
          selector = this.message.slice(startPosition.offset, this.offset());
        } else {
          break;
        }
      }
      if (parsedSelectors.has(selector)) {
        return this.error(parentArgType === "select" ? ErrorKind.DUPLICATE_SELECT_ARGUMENT_SELECTOR : ErrorKind.DUPLICATE_PLURAL_ARGUMENT_SELECTOR, selectorLocation);
      }
      if (selector === "other") {
        hasOtherClause = true;
      }
      this.bumpSpace();
      var openingBracePosition = this.clonePosition();
      if (!this.bumpIf("{")) {
        return this.error(parentArgType === "select" ? ErrorKind.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT : ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT, createLocation(this.clonePosition(), this.clonePosition()));
      }
      var fragmentResult = this.parseMessage(nestingLevel + 1, parentArgType, expectCloseTag);
      if (fragmentResult.err) {
        return fragmentResult;
      }
      var argCloseResult = this.tryParseArgumentClose(openingBracePosition);
      if (argCloseResult.err) {
        return argCloseResult;
      }
      options.push([
        selector,
        {
          value: fragmentResult.val,
          location: createLocation(openingBracePosition, this.clonePosition())
        }
      ]);
      parsedSelectors.add(selector);
      this.bumpSpace();
      _a2 = this.parseIdentifierIfPossible(), selector = _a2.value, selectorLocation = _a2.location;
    }
    if (options.length === 0) {
      return this.error(parentArgType === "select" ? ErrorKind.EXPECT_SELECT_ARGUMENT_SELECTOR : ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR, createLocation(this.clonePosition(), this.clonePosition()));
    }
    if (this.requiresOtherClause && !hasOtherClause) {
      return this.error(ErrorKind.MISSING_OTHER_CLAUSE, createLocation(this.clonePosition(), this.clonePosition()));
    }
    return { val: options, err: null };
  };
  Parser2.prototype.tryParseDecimalInteger = function(expectNumberError, invalidNumberError) {
    var sign = 1;
    var startingPosition = this.clonePosition();
    if (this.bumpIf("+"))
      ;
    else if (this.bumpIf("-")) {
      sign = -1;
    }
    var hasDigits = false;
    var decimal = 0;
    while (!this.isEOF()) {
      var ch = this.char();
      if (ch >= 48 && ch <= 57) {
        hasDigits = true;
        decimal = decimal * 10 + (ch - 48);
        this.bump();
      } else {
        break;
      }
    }
    var location2 = createLocation(startingPosition, this.clonePosition());
    if (!hasDigits) {
      return this.error(expectNumberError, location2);
    }
    decimal *= sign;
    if (!isSafeInteger(decimal)) {
      return this.error(invalidNumberError, location2);
    }
    return { val: decimal, err: null };
  };
  Parser2.prototype.offset = function() {
    return this.position.offset;
  };
  Parser2.prototype.isEOF = function() {
    return this.offset() === this.message.length;
  };
  Parser2.prototype.clonePosition = function() {
    return {
      offset: this.position.offset,
      line: this.position.line,
      column: this.position.column
    };
  };
  Parser2.prototype.char = function() {
    var offset = this.position.offset;
    if (offset >= this.message.length) {
      throw Error("out of bound");
    }
    var code = codePointAt(this.message, offset);
    if (code === void 0) {
      throw Error("Offset ".concat(offset, " is at invalid UTF-16 code unit boundary"));
    }
    return code;
  };
  Parser2.prototype.error = function(kind, location2) {
    return {
      val: null,
      err: {
        kind,
        message: this.message,
        location: location2
      }
    };
  };
  Parser2.prototype.bump = function() {
    if (this.isEOF()) {
      return;
    }
    var code = this.char();
    if (code === 10) {
      this.position.line += 1;
      this.position.column = 1;
      this.position.offset += 1;
    } else {
      this.position.column += 1;
      this.position.offset += code < 65536 ? 1 : 2;
    }
  };
  Parser2.prototype.bumpIf = function(prefix) {
    if (startsWith(this.message, prefix, this.offset())) {
      for (var i = 0; i < prefix.length; i++) {
        this.bump();
      }
      return true;
    }
    return false;
  };
  Parser2.prototype.bumpUntil = function(pattern) {
    var currentOffset = this.offset();
    var index = this.message.indexOf(pattern, currentOffset);
    if (index >= 0) {
      this.bumpTo(index);
      return true;
    } else {
      this.bumpTo(this.message.length);
      return false;
    }
  };
  Parser2.prototype.bumpTo = function(targetOffset) {
    if (this.offset() > targetOffset) {
      throw Error("targetOffset ".concat(targetOffset, " must be greater than or equal to the current offset ").concat(this.offset()));
    }
    targetOffset = Math.min(targetOffset, this.message.length);
    while (true) {
      var offset = this.offset();
      if (offset === targetOffset) {
        break;
      }
      if (offset > targetOffset) {
        throw Error("targetOffset ".concat(targetOffset, " is at invalid UTF-16 code unit boundary"));
      }
      this.bump();
      if (this.isEOF()) {
        break;
      }
    }
  };
  Parser2.prototype.bumpSpace = function() {
    while (!this.isEOF() && _isWhiteSpace(this.char())) {
      this.bump();
    }
  };
  Parser2.prototype.peek = function() {
    if (this.isEOF()) {
      return null;
    }
    var code = this.char();
    var offset = this.offset();
    var nextCode = this.message.charCodeAt(offset + (code >= 65536 ? 2 : 1));
    return nextCode !== null && nextCode !== void 0 ? nextCode : null;
  };
  return Parser2;
}();
function _isAlpha(codepoint) {
  return codepoint >= 97 && codepoint <= 122 || codepoint >= 65 && codepoint <= 90;
}
function _isAlphaOrSlash(codepoint) {
  return _isAlpha(codepoint) || codepoint === 47;
}
function _isPotentialElementNameChar(c) {
  return c === 45 || c === 46 || c >= 48 && c <= 57 || c === 95 || c >= 97 && c <= 122 || c >= 65 && c <= 90 || c == 183 || c >= 192 && c <= 214 || c >= 216 && c <= 246 || c >= 248 && c <= 893 || c >= 895 && c <= 8191 || c >= 8204 && c <= 8205 || c >= 8255 && c <= 8256 || c >= 8304 && c <= 8591 || c >= 11264 && c <= 12271 || c >= 12289 && c <= 55295 || c >= 63744 && c <= 64975 || c >= 65008 && c <= 65533 || c >= 65536 && c <= 983039;
}
function _isWhiteSpace(c) {
  return c >= 9 && c <= 13 || c === 32 || c === 133 || c >= 8206 && c <= 8207 || c === 8232 || c === 8233;
}
function _isPatternSyntax(c) {
  return c >= 33 && c <= 35 || c === 36 || c >= 37 && c <= 39 || c === 40 || c === 41 || c === 42 || c === 43 || c === 44 || c === 45 || c >= 46 && c <= 47 || c >= 58 && c <= 59 || c >= 60 && c <= 62 || c >= 63 && c <= 64 || c === 91 || c === 92 || c === 93 || c === 94 || c === 96 || c === 123 || c === 124 || c === 125 || c === 126 || c === 161 || c >= 162 && c <= 165 || c === 166 || c === 167 || c === 169 || c === 171 || c === 172 || c === 174 || c === 176 || c === 177 || c === 182 || c === 187 || c === 191 || c === 215 || c === 247 || c >= 8208 && c <= 8213 || c >= 8214 && c <= 8215 || c === 8216 || c === 8217 || c === 8218 || c >= 8219 && c <= 8220 || c === 8221 || c === 8222 || c === 8223 || c >= 8224 && c <= 8231 || c >= 8240 && c <= 8248 || c === 8249 || c === 8250 || c >= 8251 && c <= 8254 || c >= 8257 && c <= 8259 || c === 8260 || c === 8261 || c === 8262 || c >= 8263 && c <= 8273 || c === 8274 || c === 8275 || c >= 8277 && c <= 8286 || c >= 8592 && c <= 8596 || c >= 8597 && c <= 8601 || c >= 8602 && c <= 8603 || c >= 8604 && c <= 8607 || c === 8608 || c >= 8609 && c <= 8610 || c === 8611 || c >= 8612 && c <= 8613 || c === 8614 || c >= 8615 && c <= 8621 || c === 8622 || c >= 8623 && c <= 8653 || c >= 8654 && c <= 8655 || c >= 8656 && c <= 8657 || c === 8658 || c === 8659 || c === 8660 || c >= 8661 && c <= 8691 || c >= 8692 && c <= 8959 || c >= 8960 && c <= 8967 || c === 8968 || c === 8969 || c === 8970 || c === 8971 || c >= 8972 && c <= 8991 || c >= 8992 && c <= 8993 || c >= 8994 && c <= 9e3 || c === 9001 || c === 9002 || c >= 9003 && c <= 9083 || c === 9084 || c >= 9085 && c <= 9114 || c >= 9115 && c <= 9139 || c >= 9140 && c <= 9179 || c >= 9180 && c <= 9185 || c >= 9186 && c <= 9254 || c >= 9255 && c <= 9279 || c >= 9280 && c <= 9290 || c >= 9291 && c <= 9311 || c >= 9472 && c <= 9654 || c === 9655 || c >= 9656 && c <= 9664 || c === 9665 || c >= 9666 && c <= 9719 || c >= 9720 && c <= 9727 || c >= 9728 && c <= 9838 || c === 9839 || c >= 9840 && c <= 10087 || c === 10088 || c === 10089 || c === 10090 || c === 10091 || c === 10092 || c === 10093 || c === 10094 || c === 10095 || c === 10096 || c === 10097 || c === 10098 || c === 10099 || c === 10100 || c === 10101 || c >= 10132 && c <= 10175 || c >= 10176 && c <= 10180 || c === 10181 || c === 10182 || c >= 10183 && c <= 10213 || c === 10214 || c === 10215 || c === 10216 || c === 10217 || c === 10218 || c === 10219 || c === 10220 || c === 10221 || c === 10222 || c === 10223 || c >= 10224 && c <= 10239 || c >= 10240 && c <= 10495 || c >= 10496 && c <= 10626 || c === 10627 || c === 10628 || c === 10629 || c === 10630 || c === 10631 || c === 10632 || c === 10633 || c === 10634 || c === 10635 || c === 10636 || c === 10637 || c === 10638 || c === 10639 || c === 10640 || c === 10641 || c === 10642 || c === 10643 || c === 10644 || c === 10645 || c === 10646 || c === 10647 || c === 10648 || c >= 10649 && c <= 10711 || c === 10712 || c === 10713 || c === 10714 || c === 10715 || c >= 10716 && c <= 10747 || c === 10748 || c === 10749 || c >= 10750 && c <= 11007 || c >= 11008 && c <= 11055 || c >= 11056 && c <= 11076 || c >= 11077 && c <= 11078 || c >= 11079 && c <= 11084 || c >= 11085 && c <= 11123 || c >= 11124 && c <= 11125 || c >= 11126 && c <= 11157 || c === 11158 || c >= 11159 && c <= 11263 || c >= 11776 && c <= 11777 || c === 11778 || c === 11779 || c === 11780 || c === 11781 || c >= 11782 && c <= 11784 || c === 11785 || c === 11786 || c === 11787 || c === 11788 || c === 11789 || c >= 11790 && c <= 11798 || c === 11799 || c >= 11800 && c <= 11801 || c === 11802 || c === 11803 || c === 11804 || c === 11805 || c >= 11806 && c <= 11807 || c === 11808 || c === 11809 || c === 11810 || c === 11811 || c === 11812 || c === 11813 || c === 11814 || c === 11815 || c === 11816 || c === 11817 || c >= 11818 && c <= 11822 || c === 11823 || c >= 11824 && c <= 11833 || c >= 11834 && c <= 11835 || c >= 11836 && c <= 11839 || c === 11840 || c === 11841 || c === 11842 || c >= 11843 && c <= 11855 || c >= 11856 && c <= 11857 || c === 11858 || c >= 11859 && c <= 11903 || c >= 12289 && c <= 12291 || c === 12296 || c === 12297 || c === 12298 || c === 12299 || c === 12300 || c === 12301 || c === 12302 || c === 12303 || c === 12304 || c === 12305 || c >= 12306 && c <= 12307 || c === 12308 || c === 12309 || c === 12310 || c === 12311 || c === 12312 || c === 12313 || c === 12314 || c === 12315 || c === 12316 || c === 12317 || c >= 12318 && c <= 12319 || c === 12320 || c === 12336 || c === 64830 || c === 64831 || c >= 65093 && c <= 65094;
}
function pruneLocation(els) {
  els.forEach(function(el) {
    delete el.location;
    if (isSelectElement(el) || isPluralElement(el)) {
      for (var k in el.options) {
        delete el.options[k].location;
        pruneLocation(el.options[k].value);
      }
    } else if (isNumberElement(el) && isNumberSkeleton(el.style)) {
      delete el.style.location;
    } else if ((isDateElement(el) || isTimeElement(el)) && isDateTimeSkeleton(el.style)) {
      delete el.style.location;
    } else if (isTagElement(el)) {
      pruneLocation(el.children);
    }
  });
}
function parse(message, opts) {
  if (opts === void 0) {
    opts = {};
  }
  opts = __assign$1({ shouldParseSkeletons: true, requiresOtherClause: true }, opts);
  var result = new Parser(message, opts).parse();
  if (result.err) {
    var error = SyntaxError(ErrorKind[result.err.kind]);
    error.location = result.err.location;
    error.originalMessage = result.err.message;
    throw error;
  }
  if (!(opts === null || opts === void 0 ? void 0 : opts.captureLocation)) {
    pruneLocation(result.val);
  }
  return result.val;
}
function memoize(fn, options) {
  var cache = options && options.cache ? options.cache : cacheDefault;
  var serializer = options && options.serializer ? options.serializer : serializerDefault;
  var strategy = options && options.strategy ? options.strategy : strategyDefault;
  return strategy(fn, {
    cache,
    serializer
  });
}
function isPrimitive(value) {
  return value == null || typeof value === "number" || typeof value === "boolean";
}
function monadic(fn, cache, serializer, arg) {
  var cacheKey = isPrimitive(arg) ? arg : serializer(arg);
  var computedValue = cache.get(cacheKey);
  if (typeof computedValue === "undefined") {
    computedValue = fn.call(this, arg);
    cache.set(cacheKey, computedValue);
  }
  return computedValue;
}
function variadic(fn, cache, serializer) {
  var args = Array.prototype.slice.call(arguments, 3);
  var cacheKey = serializer(args);
  var computedValue = cache.get(cacheKey);
  if (typeof computedValue === "undefined") {
    computedValue = fn.apply(this, args);
    cache.set(cacheKey, computedValue);
  }
  return computedValue;
}
function assemble(fn, context, strategy, cache, serialize) {
  return strategy.bind(context, fn, cache, serialize);
}
function strategyDefault(fn, options) {
  var strategy = fn.length === 1 ? monadic : variadic;
  return assemble(fn, this, strategy, options.cache.create(), options.serializer);
}
function strategyVariadic(fn, options) {
  return assemble(fn, this, variadic, options.cache.create(), options.serializer);
}
function strategyMonadic(fn, options) {
  return assemble(fn, this, monadic, options.cache.create(), options.serializer);
}
var serializerDefault = function() {
  return JSON.stringify(arguments);
};
function ObjectWithoutPrototypeCache() {
  this.cache = /* @__PURE__ */ Object.create(null);
}
ObjectWithoutPrototypeCache.prototype.get = function(key) {
  return this.cache[key];
};
ObjectWithoutPrototypeCache.prototype.set = function(key, value) {
  this.cache[key] = value;
};
var cacheDefault = {
  create: function create() {
    return new ObjectWithoutPrototypeCache();
  }
};
var strategies = {
  variadic: strategyVariadic,
  monadic: strategyMonadic
};
var ErrorCode;
(function(ErrorCode2) {
  ErrorCode2["MISSING_VALUE"] = "MISSING_VALUE";
  ErrorCode2["INVALID_VALUE"] = "INVALID_VALUE";
  ErrorCode2["MISSING_INTL_API"] = "MISSING_INTL_API";
})(ErrorCode || (ErrorCode = {}));
var FormatError = function(_super) {
  __extends(FormatError2, _super);
  function FormatError2(msg, code, originalMessage) {
    var _this = _super.call(this, msg) || this;
    _this.code = code;
    _this.originalMessage = originalMessage;
    return _this;
  }
  FormatError2.prototype.toString = function() {
    return "[formatjs Error: ".concat(this.code, "] ").concat(this.message);
  };
  return FormatError2;
}(Error);
var InvalidValueError = function(_super) {
  __extends(InvalidValueError2, _super);
  function InvalidValueError2(variableId, value, options, originalMessage) {
    return _super.call(this, 'Invalid values for "'.concat(variableId, '": "').concat(value, '". Options are "').concat(Object.keys(options).join('", "'), '"'), ErrorCode.INVALID_VALUE, originalMessage) || this;
  }
  return InvalidValueError2;
}(FormatError);
var InvalidValueTypeError = function(_super) {
  __extends(InvalidValueTypeError2, _super);
  function InvalidValueTypeError2(value, type, originalMessage) {
    return _super.call(this, 'Value for "'.concat(value, '" must be of type ').concat(type), ErrorCode.INVALID_VALUE, originalMessage) || this;
  }
  return InvalidValueTypeError2;
}(FormatError);
var MissingValueError = function(_super) {
  __extends(MissingValueError2, _super);
  function MissingValueError2(variableId, originalMessage) {
    return _super.call(this, 'The intl string context variable "'.concat(variableId, '" was not provided to the string "').concat(originalMessage, '"'), ErrorCode.MISSING_VALUE, originalMessage) || this;
  }
  return MissingValueError2;
}(FormatError);
var PART_TYPE;
(function(PART_TYPE2) {
  PART_TYPE2[PART_TYPE2["literal"] = 0] = "literal";
  PART_TYPE2[PART_TYPE2["object"] = 1] = "object";
})(PART_TYPE || (PART_TYPE = {}));
function mergeLiteral(parts) {
  if (parts.length < 2) {
    return parts;
  }
  return parts.reduce(function(all, part) {
    var lastPart = all[all.length - 1];
    if (!lastPart || lastPart.type !== PART_TYPE.literal || part.type !== PART_TYPE.literal) {
      all.push(part);
    } else {
      lastPart.value += part.value;
    }
    return all;
  }, []);
}
function isFormatXMLElementFn(el) {
  return typeof el === "function";
}
function formatToParts(els, locales, formatters, formats, values, currentPluralValue, originalMessage) {
  if (els.length === 1 && isLiteralElement(els[0])) {
    return [
      {
        type: PART_TYPE.literal,
        value: els[0].value
      }
    ];
  }
  var result = [];
  for (var _i = 0, els_1 = els; _i < els_1.length; _i++) {
    var el = els_1[_i];
    if (isLiteralElement(el)) {
      result.push({
        type: PART_TYPE.literal,
        value: el.value
      });
      continue;
    }
    if (isPoundElement(el)) {
      if (typeof currentPluralValue === "number") {
        result.push({
          type: PART_TYPE.literal,
          value: formatters.getNumberFormat(locales).format(currentPluralValue)
        });
      }
      continue;
    }
    var varName = el.value;
    if (!(values && varName in values)) {
      throw new MissingValueError(varName, originalMessage);
    }
    var value = values[varName];
    if (isArgumentElement(el)) {
      if (!value || typeof value === "string" || typeof value === "number") {
        value = typeof value === "string" || typeof value === "number" ? String(value) : "";
      }
      result.push({
        type: typeof value === "string" ? PART_TYPE.literal : PART_TYPE.object,
        value
      });
      continue;
    }
    if (isDateElement(el)) {
      var style = typeof el.style === "string" ? formats.date[el.style] : isDateTimeSkeleton(el.style) ? el.style.parsedOptions : void 0;
      result.push({
        type: PART_TYPE.literal,
        value: formatters.getDateTimeFormat(locales, style).format(value)
      });
      continue;
    }
    if (isTimeElement(el)) {
      var style = typeof el.style === "string" ? formats.time[el.style] : isDateTimeSkeleton(el.style) ? el.style.parsedOptions : void 0;
      result.push({
        type: PART_TYPE.literal,
        value: formatters.getDateTimeFormat(locales, style).format(value)
      });
      continue;
    }
    if (isNumberElement(el)) {
      var style = typeof el.style === "string" ? formats.number[el.style] : isNumberSkeleton(el.style) ? el.style.parsedOptions : void 0;
      if (style && style.scale) {
        value = value * (style.scale || 1);
      }
      result.push({
        type: PART_TYPE.literal,
        value: formatters.getNumberFormat(locales, style).format(value)
      });
      continue;
    }
    if (isTagElement(el)) {
      var children = el.children, value_1 = el.value;
      var formatFn = values[value_1];
      if (!isFormatXMLElementFn(formatFn)) {
        throw new InvalidValueTypeError(value_1, "function", originalMessage);
      }
      var parts = formatToParts(children, locales, formatters, formats, values, currentPluralValue);
      var chunks = formatFn(parts.map(function(p2) {
        return p2.value;
      }));
      if (!Array.isArray(chunks)) {
        chunks = [chunks];
      }
      result.push.apply(result, chunks.map(function(c) {
        return {
          type: typeof c === "string" ? PART_TYPE.literal : PART_TYPE.object,
          value: c
        };
      }));
    }
    if (isSelectElement(el)) {
      var opt = el.options[value] || el.options.other;
      if (!opt) {
        throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);
      }
      result.push.apply(result, formatToParts(opt.value, locales, formatters, formats, values));
      continue;
    }
    if (isPluralElement(el)) {
      var opt = el.options["=".concat(value)];
      if (!opt) {
        if (!Intl.PluralRules) {
          throw new FormatError('Intl.PluralRules is not available in this environment.\nTry polyfilling it using "@formatjs/intl-pluralrules"\n', ErrorCode.MISSING_INTL_API, originalMessage);
        }
        var rule = formatters.getPluralRules(locales, { type: el.pluralType }).select(value - (el.offset || 0));
        opt = el.options[rule] || el.options.other;
      }
      if (!opt) {
        throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);
      }
      result.push.apply(result, formatToParts(opt.value, locales, formatters, formats, values, value - (el.offset || 0)));
      continue;
    }
  }
  return mergeLiteral(result);
}
function mergeConfig(c1, c2) {
  if (!c2) {
    return c1;
  }
  return __assign$1(__assign$1(__assign$1({}, c1 || {}), c2 || {}), Object.keys(c1).reduce(function(all, k) {
    all[k] = __assign$1(__assign$1({}, c1[k]), c2[k] || {});
    return all;
  }, {}));
}
function mergeConfigs(defaultConfig, configs) {
  if (!configs) {
    return defaultConfig;
  }
  return Object.keys(defaultConfig).reduce(function(all, k) {
    all[k] = mergeConfig(defaultConfig[k], configs[k]);
    return all;
  }, __assign$1({}, defaultConfig));
}
function createFastMemoizeCache(store) {
  return {
    create: function() {
      return {
        get: function(key) {
          return store[key];
        },
        set: function(key, value) {
          store[key] = value;
        }
      };
    }
  };
}
function createDefaultFormatters(cache) {
  if (cache === void 0) {
    cache = {
      number: {},
      dateTime: {},
      pluralRules: {}
    };
  }
  return {
    getNumberFormat: memoize(function() {
      var _a2;
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      return new ((_a2 = Intl.NumberFormat).bind.apply(_a2, __spreadArray([void 0], args, false)))();
    }, {
      cache: createFastMemoizeCache(cache.number),
      strategy: strategies.variadic
    }),
    getDateTimeFormat: memoize(function() {
      var _a2;
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      return new ((_a2 = Intl.DateTimeFormat).bind.apply(_a2, __spreadArray([void 0], args, false)))();
    }, {
      cache: createFastMemoizeCache(cache.dateTime),
      strategy: strategies.variadic
    }),
    getPluralRules: memoize(function() {
      var _a2;
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      return new ((_a2 = Intl.PluralRules).bind.apply(_a2, __spreadArray([void 0], args, false)))();
    }, {
      cache: createFastMemoizeCache(cache.pluralRules),
      strategy: strategies.variadic
    })
  };
}
var IntlMessageFormat$1 = function() {
  function IntlMessageFormat2(message, locales, overrideFormats, opts) {
    var _this = this;
    if (locales === void 0) {
      locales = IntlMessageFormat2.defaultLocale;
    }
    this.formatterCache = {
      number: {},
      dateTime: {},
      pluralRules: {}
    };
    this.format = function(values) {
      var parts = _this.formatToParts(values);
      if (parts.length === 1) {
        return parts[0].value;
      }
      var result = parts.reduce(function(all, part) {
        if (!all.length || part.type !== PART_TYPE.literal || typeof all[all.length - 1] !== "string") {
          all.push(part.value);
        } else {
          all[all.length - 1] += part.value;
        }
        return all;
      }, []);
      if (result.length <= 1) {
        return result[0] || "";
      }
      return result;
    };
    this.formatToParts = function(values) {
      return formatToParts(_this.ast, _this.locales, _this.formatters, _this.formats, values, void 0, _this.message);
    };
    this.resolvedOptions = function() {
      return {
        locale: Intl.NumberFormat.supportedLocalesOf(_this.locales)[0]
      };
    };
    this.getAst = function() {
      return _this.ast;
    };
    if (typeof message === "string") {
      this.message = message;
      if (!IntlMessageFormat2.__parse) {
        throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");
      }
      this.ast = IntlMessageFormat2.__parse(message, {
        ignoreTag: opts === null || opts === void 0 ? void 0 : opts.ignoreTag
      });
    } else {
      this.ast = message;
    }
    if (!Array.isArray(this.ast)) {
      throw new TypeError("A message must be provided as a String or AST.");
    }
    this.formats = mergeConfigs(IntlMessageFormat2.formats, overrideFormats);
    this.locales = locales;
    this.formatters = opts && opts.formatters || createDefaultFormatters(this.formatterCache);
  }
  Object.defineProperty(IntlMessageFormat2, "defaultLocale", {
    get: function() {
      if (!IntlMessageFormat2.memoizedDefaultLocale) {
        IntlMessageFormat2.memoizedDefaultLocale = new Intl.NumberFormat().resolvedOptions().locale;
      }
      return IntlMessageFormat2.memoizedDefaultLocale;
    },
    enumerable: false,
    configurable: true
  });
  IntlMessageFormat2.memoizedDefaultLocale = null;
  IntlMessageFormat2.__parse = parse;
  IntlMessageFormat2.formats = {
    number: {
      integer: {
        maximumFractionDigits: 0
      },
      currency: {
        style: "currency"
      },
      percent: {
        style: "percent"
      }
    },
    date: {
      short: {
        month: "numeric",
        day: "numeric",
        year: "2-digit"
      },
      medium: {
        month: "short",
        day: "numeric",
        year: "numeric"
      },
      long: {
        month: "long",
        day: "numeric",
        year: "numeric"
      },
      full: {
        weekday: "long",
        month: "long",
        day: "numeric",
        year: "numeric"
      }
    },
    time: {
      short: {
        hour: "numeric",
        minute: "numeric"
      },
      medium: {
        hour: "numeric",
        minute: "numeric",
        second: "numeric"
      },
      long: {
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
        timeZoneName: "short"
      },
      full: {
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
        timeZoneName: "short"
      }
    }
  };
  return IntlMessageFormat2;
}();
var IntlMessageFormat = IntlMessageFormat$1;
var _a;
var IcuFormatter = (_a = function() {
  function class_1() {
    this.cache = /* @__PURE__ */ new Map();
  }
  class_1.prototype.format = function(_a2) {
    var translation = _a2.translation, language = _a2.language, params = _a2.params;
    var ignoreTag = !Object.values(params).find(function(p2) {
      return typeof p2 === "function";
    });
    return new IntlMessageFormat(translation, language, void 0, {
      ignoreTag
    }).format(params);
  };
  return class_1;
}(), _a.type = "formatter", _a);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var __assign = function() {
  __assign = Object.assign || function __assign2(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p2 in s)
        if (Object.prototype.hasOwnProperty.call(s, p2))
          t[p2] = s[p2];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
var TolgeeProvider = defineComponent({
  name: "TolgeeProvider",
  props: {
    config: { type: Object, required: true },
    loadingFallback: {
      type: [Object, String]
    }
  },
  created: function() {
    var _this = this;
    var tolgee = Tolgee.use(IcuFormatter).init(__assign({
      wrapperMode: "invisible",
      ui: void 0
    }, this.$props.config));
    this.tolgeeContext.tolgee = tolgee;
    this.loading = tolgee.initialLoading;
    tolgee.run().then(function() {
      _this.loading = false;
    });
  },
  data: function() {
    return {
      tolgeeContext: {
        tolgee: null
      },
      loading: null
    };
  },
  provide: function() {
    return {
      tolgeeContext: this.tolgeeContext
    };
  },
  beforeUnmount: function() {
    var _a2, _b;
    (_a2 = this.tolgeeContext.tolgee) === null || _a2 === void 0 ? void 0 : _a2.stop();
    (_b = this.$options.langSubscription) === null || _b === void 0 ? void 0 : _b.unsubscribe();
  },
  render: function() {
    var _a2, _b, _c, _d;
    return !this.loading ? (_b = (_a2 = this.$slots).default) === null || _b === void 0 ? void 0 : _b.call(_a2) : ((_d = (_c = this.$slots).fallback) === null || _d === void 0 ? void 0 : _d.call(_c)) || this.loadingFallback || null;
  }
});
var useTranslate = function() {
  var tolgeeContext = inject("tolgeeContext");
  var keysRef = [];
  var resetMemory = function(key) {
    keysRef = key ? keysRef.filter(function(k) {
      return k !== key;
    }) : [];
  };
  var createTFunction = function() {
    return function(keyOrProps) {
      var params = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        params[_i - 1] = arguments[_i];
      }
      var parameters = void 0;
      var noWrap = void 0;
      var defaultValue = void 0;
      var key = typeof keyOrProps === "object" ? keyOrProps.key : keyOrProps;
      if (typeof keyOrProps === "object") {
        parameters = keyOrProps.parameters;
        noWrap = keyOrProps.noWrap;
        defaultValue = keyOrProps.defaultValue;
      } else {
        params.forEach(function(param) {
          switch (typeof param) {
            case "object":
              parameters = param;
              break;
            case "boolean":
              noWrap = param;
              break;
            case "string":
              defaultValue = param;
          }
        });
      }
      var result = tolgeeContext === null || tolgeeContext === void 0 ? void 0 : tolgeeContext.tolgee.instant({
        key,
        params: parameters,
        noWrap,
        defaultValue
      });
      var firstRender = !keysRef.includes(key);
      if (firstRender) {
        keysRef.push(key);
        tolgeeContext === null || tolgeeContext === void 0 ? void 0 : tolgeeContext.tolgee.translate({
          key,
          params: parameters,
          noWrap,
          defaultValue
        }).then(function(value) {
          if (value !== result) {
            t.value = createTFunction();
          }
        });
      }
      return result;
    };
  };
  var t = ref(createTFunction());
  var translationSub;
  var allTranslationsSub;
  onMounted(function() {
    var tolgee = tolgeeContext.tolgee;
    translationSub = tolgee.onTranslationChange.subscribe(function(_a2) {
      var key = _a2.key;
      if (keysRef.includes(key)) {
        resetMemory(key);
        t.value = createTFunction();
      }
    });
    allTranslationsSub = tolgee.onLangChange.subscribe(function() {
      if (keysRef.length) {
        resetMemory();
        t.value = createTFunction();
      }
    });
  });
  onUnmounted(function() {
    translationSub === null || translationSub === void 0 ? void 0 : translationSub.unsubscribe();
    allTranslationsSub === null || allTranslationsSub === void 0 ? void 0 : allTranslationsSub.unsubscribe();
  });
  return t;
};
var T = defineComponent({
  name: "T",
  props: {
    keyName: { type: String, required: true },
    parameters: Object,
    defaultValue: String,
    noWrap: {
      type: Boolean,
      default: false
    }
  },
  setup: function() {
    var t = useTranslate();
    return { t };
  },
  render: function() {
    var params = {
      key: this.$props.keyName,
      parameters: this.$props.parameters,
      defaultValue: this.$props.defaultValue,
      noWrap: this.noWrap
    };
    var content = this.t(params);
    return content;
  }
});
defineComponent({
  inject: ["tolgeeContext"],
  beforeCreate: function() {
    this.$options._tolgee = {
      subscribedKeys: [],
      subscribedKeysReady: [],
      translationSub: null,
      langSub: null
    };
  },
  created: function() {
    var _this = this;
    var tolgeeContext = this.tolgeeContext;
    if (tolgeeContext) {
      this.$options._tolgee.langSub = tolgeeContext === null || tolgeeContext === void 0 ? void 0 : tolgeeContext.tolgee.onLangChange.subscribe(function(lang) {
        var _a2;
        _this.tolgeeLanguage = lang;
        if ((_a2 = _this.$options._tolgee.subscribedKeys) === null || _a2 === void 0 ? void 0 : _a2.length) {
          _this._tolgeeResetMemory();
          _this.$forceUpdate();
        }
      });
      this.$options._tolgee.translationSub = tolgeeContext.tolgee.onTranslationChange.subscribe(function(data) {
        if (_this.$options._tolgee.subscribedKeys.includes(data.key)) {
          _this.$forceUpdate();
        }
      });
    } else {
      throw new Error('TolgeeMixin: tolgeeContext not provided for "'.concat(this.$options.name, '". Did you use TolgeeProvider correctly?'));
    }
  },
  data: function() {
    var tolgeeContext = this.tolgeeContext;
    return {
      tolgeeLanguage: tolgeeContext.tolgee.lang
    };
  },
  watch: {
    tolgeeLanguage: function(value) {
      this.tolgeeContext.tolgee.changeLanguage(value);
    }
  },
  methods: {
    $t: function(keyOrProps) {
      var params = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        params[_i - 1] = arguments[_i];
      }
      var parameters = void 0;
      var noWrap = void 0;
      var defaultValue = void 0;
      var key = typeof keyOrProps === "object" ? keyOrProps.key : keyOrProps;
      if (typeof keyOrProps === "object") {
        parameters = keyOrProps.parameters;
        noWrap = keyOrProps.noWrap;
        defaultValue = keyOrProps.defaultValue;
      } else {
        params.forEach(function(param) {
          switch (typeof param) {
            case "object":
              parameters = param;
              break;
            case "boolean":
              noWrap = param;
              break;
            case "string":
              defaultValue = param;
          }
        });
      }
      var result = this._tolgeeGetTranslation(key, parameters, noWrap, defaultValue);
      return result;
    },
    _tolgeeResetMemory: function(key) {
      this.subscribedKeys = key ? this.subscribedKeys.filter(function(k) {
        return k !== key;
      }) : [];
      this.subscribedKeysReady = key ? this.subscribedKeysReady.filter(function(k) {
        return k !== key;
      }) : [];
    },
    _tolgeeUnsubscribe: function() {
      var _a2, _b, _c, _d;
      (_b = (_a2 = this.$options._tolgee) === null || _a2 === void 0 ? void 0 : _a2.langSub) === null || _b === void 0 ? void 0 : _b.unsubscribe();
      (_d = (_c = this.$options._tolgee) === null || _c === void 0 ? void 0 : _c.translationSub) === null || _d === void 0 ? void 0 : _d.unsubscribe();
    },
    _tolgeeGetTranslation: function(key, parameters, noWrap, defaultValue) {
      var _this = this;
      var tolgeeContext = this.tolgeeContext;
      var firstRender = !this.$options._tolgee.subscribedKeys.includes(key);
      var ready = this.$options._tolgee.subscribedKeysReady.includes(key);
      var translation = tolgeeContext.tolgee.instant({
        key,
        params: parameters,
        noWrap,
        defaultValue: !ready ? void 0 : defaultValue,
        orEmpty: !ready
      });
      if (firstRender) {
        this.$options._tolgee.subscribedKeys.push(key);
        tolgeeContext.tolgee.translate({ key, params: parameters, noWrap, defaultValue }).then(function(value) {
          _this.$options._tolgee.subscribedKeysReady.push(key);
          if (value !== translation) {
            _this.$forceUpdate();
          }
        });
      }
      return translation;
    }
  },
  beforeUnmount: function() {
    this._tolgeeUnsubscribe();
  }
});
function isRangeFilter(result) {
  var _a2;
  return ((_a2 = result.filter) == null ? void 0 : _a2.type) === "range";
}
function isValue(value) {
  return !(isNaN(value) || value === null || value === void 0);
}
function between(x, min, max) {
  if (!isValue(min) && !isValue(max) && !x)
    return true;
  const num = typeof x !== "string" ? x : parseInt(x);
  return num >= Math.max(min || 0, 0) && num <= Math.min(max || Infinity, Infinity);
}
function filterMachines(machine, filter) {
  return Object.entries(filter).every(([name, result]) => {
    var _a2, _b, _c, _d, _e, _f, _g;
    if (result.filter) {
      if (isRangeFilter(result)) {
        const [min, max] = result.value;
        switch (name) {
          case "manufacture_date": {
            return between(machine.year, min, max);
          }
          case "workhours": {
            return between((_a2 = machine.workhours) == null ? void 0 : _a2.value, min, max);
          }
          case "power": {
            return between((_b = machine.power) == null ? void 0 : _b.kW, min, max);
          }
          case "price": {
            return between((_c = machine.price.values) == null ? void 0 : _c.netto, min, max);
          }
        }
      } else if (result.value) {
        switch (name) {
          case "freetext": {
            const search = result.value.toString().toLowerCase();
            if (machine.id.toString().toLowerCase().includes(search))
              return true;
            if ((_d = machine.dealer_internal_id) == null ? void 0 : _d.toString().toLowerCase().includes(search))
              return true;
            if ((_e = machine.model) == null ? void 0 : _e.toString().toLowerCase().includes(search))
              return true;
            if ((_g = (_f = machine.manufacturer) == null ? void 0 : _f.value) == null ? void 0 : _g.toString().toLowerCase().includes(search))
              return true;
            return false;
          }
          case "manufacturer": {
            return machine.manufacturer.id == result.value;
          }
          case "model": {
            return machine.model == result.value;
          }
          case "category": {
            return machine.category.id == result.value;
          }
          case "location": {
            return machine.dealer.id == result.value;
          }
          case "condition": {
            return machine.condition.id == result.value;
          }
        }
      }
    }
    return true;
  });
}
function isHistoryStateValid(state) {
  if (!window.history.state)
    return false;
  const { page, filter } = window.history.state;
  if (isNaN(page))
    return false;
  const stateFilterKeys = Object.keys(state.filter);
  const filterKeys = Object.keys(filter != null ? filter : {});
  if (stateFilterKeys.length !== filterKeys.length || !stateFilterKeys.every((a) => filterKeys.includes(a)))
    return false;
  return true;
}
var SelectGroup_vue_vue_type_style_index_0_lang = "";
const _hoisted_1$4 = { class: "select-group__label" };
const _hoisted_2$4 = ["for"];
const _hoisted_3$2 = ["disabled"];
const _hoisted_4$2 = /* @__PURE__ */ createBaseVNode("svg", {
  xmlns: "http://www.w3.org/2000/svg",
  class: "h-5 w-5",
  viewBox: "0 0 20 20",
  fill: "currentColor"
}, [
  /* @__PURE__ */ createBaseVNode("path", {
    "fill-rule": "evenodd",
    d: "M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",
    "clip-rule": "evenodd"
  })
], -1);
const _hoisted_5$2 = [
  _hoisted_4$2
];
const _hoisted_6$2 = ["placeholder", "value"];
const _hoisted_7$2 = {
  key: 1,
  class: "select-group__range"
};
const _hoisted_8$2 = ["placeholder", "min", "max", "value"];
const _hoisted_9$2 = /* @__PURE__ */ createTextVNode(" \u2013 ");
const _hoisted_10$2 = ["placeholder", "min", "max", "value"];
const _hoisted_11$2 = ["disabled", "id", "value"];
const _hoisted_12$1 = { value: "" };
const _hoisted_13$1 = ["value"];
const _sfc_main$5 = /* @__PURE__ */ defineComponent({
  __name: "SelectGroup",
  props: {
    modelValue: null,
    filter: null
  },
  emits: ["update:modelValue"],
  setup(__props, { emit }) {
    const props = __props;
    const t = useTranslate();
    const reset2 = () => {
      update(props.filter.type === "range" ? [null, null] : null);
    };
    const dirty = computed(() => {
      const { value } = props.modelValue[props.filter.name];
      return props.filter.type === "range" && value.some((v) => isValue(v)) || props.filter.type !== "range" && value;
    });
    const updateMin = (ev) => {
      const max = props.modelValue[props.filter.name].value[1];
      update([parseInt(ev.target.value), max]);
    };
    const updateMax = (ev) => {
      const min = props.modelValue[props.filter.name].value[0];
      update([min, parseInt(ev.target.value)]);
    };
    const update = (value) => {
      if (props.filter.reset) {
        props.filter.reset();
      }
      emit("update:modelValue", {
        ...props.modelValue,
        ...{
          [props.filter.name]: {
            value,
            filter: props.filter
          }
        }
      });
    };
    return (_ctx, _cache) => {
      var _a2, _b, _c, _d;
      return openBlock(), createElementBlock("div", {
        class: normalizeClass(["select-group", `select-group--${__props.filter.type}`])
      }, [
        createBaseVNode("div", _hoisted_1$4, [
          createBaseVNode("label", {
            for: __props.filter.name
          }, [
            createVNode(unref(T), {
              keyName: __props.filter.name
            }, null, 8, ["keyName"])
          ], 8, _hoisted_2$4),
          createBaseVNode("button", {
            onClick: reset2,
            class: "select-group__clear",
            disabled: !unref(dirty)
          }, _hoisted_5$2, 8, _hoisted_3$2)
        ]),
        __props.filter.type === "input" ? (openBlock(), createElementBlock("input", {
          key: 0,
          type: "text",
          placeholder: unref(t)("search_placeholder"),
          value: __props.modelValue[__props.filter.name].value,
          onChange: _cache[0] || (_cache[0] = (ev) => update(ev.target.value))
        }, null, 40, _hoisted_6$2)) : __props.filter.type === "range" ? (openBlock(), createElementBlock("div", _hoisted_7$2, [
          createBaseVNode("input", {
            type: "number",
            placeholder: unref(t)("min_placeholder"),
            min: __props.filter.min,
            max: (_a2 = __props.modelValue[__props.filter.name].value[1]) != null ? _a2 : __props.filter.max,
            value: (_b = __props.modelValue[__props.filter.name].value[0]) != null ? _b : null,
            onChange: updateMin
          }, null, 40, _hoisted_8$2),
          _hoisted_9$2,
          createBaseVNode("input", {
            type: "number",
            placeholder: unref(t)("max_placeholder"),
            min: (_c = __props.modelValue[__props.filter.name].value[0]) != null ? _c : __props.filter.min,
            max: __props.filter.max,
            value: (_d = __props.modelValue[__props.filter.name].value[1]) != null ? _d : null,
            onChange: updateMax
          }, null, 40, _hoisted_10$2)
        ])) : (openBlock(), createElementBlock("select", {
          key: 2,
          disabled: __props.filter.disabled,
          id: __props.filter.name,
          value: __props.modelValue[__props.filter.name].value,
          onChange: _cache[1] || (_cache[1] = (ev) => update(ev.target.value))
        }, [
          createBaseVNode("option", _hoisted_12$1, [
            createVNode(unref(T), {
              keyName: "filter_placeholder",
              parameters: { filter: __props.filter.name }
            }, null, 8, ["parameters"])
          ]),
          (openBlock(true), createElementBlock(Fragment, null, renderList(__props.filter.options, ([value, label]) => {
            return openBlock(), createElementBlock("option", { value }, toDisplayString(label), 9, _hoisted_13$1);
          }), 256))
        ], 40, _hoisted_11$2))
      ], 2);
    };
  }
});
var Filter_vue_vue_type_style_index_0_scoped_true_lang = "";
var _export_sfc = (sfc, props) => {
  const target = sfc.__vccOpts || sfc;
  for (const [key, val] of props) {
    target[key] = val;
  }
  return target;
};
const _hoisted_1$3 = { class: "filter" };
const _hoisted_2$3 = { class: "filter__result_text" };
const _sfc_main$4 = /* @__PURE__ */ defineComponent({
  __name: "Filter",
  props: {
    machines: null,
    filteredMachines: null,
    modelValue: null
  },
  setup(__props) {
    const props = __props;
    const t = unref(useTranslate());
    const filters = computed(() => [
      {
        name: "freetext",
        type: "input"
      },
      {
        name: "category",
        type: "single",
        options: new Map(props.machines.filter((machine) => {
          const { category, model, ...filter } = props.modelValue;
          return filterMachines(machine, filter);
        }).slice().sort((a, b) => a.category.name.localeCompare(b.category.name)).map(({ category }) => [category.id, category.name])),
        reset() {
          props.modelValue["model"].value = null;
        }
      },
      {
        name: "manufacture_date",
        type: "range",
        min: 1900,
        max: new Date().getFullYear()
      },
      {
        name: "workhours",
        type: "range",
        min: 0,
        max: 1e5
      },
      {
        name: "manufacturer",
        type: "single",
        options: new Map(props.machines.filter((machine) => {
          const { manufacturer, model, ...filter } = props.modelValue;
          if (machine.manufacturer.id == props.modelValue["manufacturer"].value)
            return true;
          return filterMachines(machine, filter);
        }).slice().sort((a, b) => a.manufacturer.value.localeCompare(b.manufacturer.value)).map(({ manufacturer }) => [manufacturer.id, manufacturer.value])),
        reset() {
          props.modelValue["model"].value = null;
        }
      },
      {
        name: "model",
        type: "single",
        disabled: !props.modelValue["manufacturer"].value,
        options: new Map(props.machines.filter((machine) => {
          const { model, ...filter } = props.modelValue;
          if (machine.model == props.modelValue["model"].value)
            return true;
          return filterMachines(machine, filter);
        }).slice().sort((a, b) => a.model.localeCompare(b.model)).map(({ model }) => [model, model]))
      },
      {
        name: "power",
        type: "range",
        min: 0,
        max: 3e3
      },
      {
        name: "location",
        type: "single",
        options: new Map(props.machines.filter((machine) => {
          const { location: location2, ...filter } = props.modelValue;
          return filterMachines(machine, filter);
        }).slice().sort((a, b) => a.dealer.zip.localeCompare(b.dealer.zip)).map(({ dealer }) => [dealer.id, `${dealer.zip} ${dealer.city}`]))
      },
      {
        name: "price",
        type: "range",
        min: 1,
        max: 9999999
      },
      {
        name: "condition",
        type: "single",
        options: new Map(props.machines.filter((machine) => {
          const { condition, ...filter } = props.modelValue;
          return filterMachines(machine, filter);
        }).slice().sort((a, b) => a.condition.id.localeCompare(b.condition.id)).map(({ condition }) => [condition.id, t(`_${condition.id}`)]))
      }
    ]);
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$3, [
        (openBlock(true), createElementBlock(Fragment, null, renderList(unref(filters), (filter) => {
          return openBlock(), createBlock(_sfc_main$5, {
            filter,
            modelValue: __props.modelValue,
            "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => _ctx.$emit("update:modelValue", $event))
          }, null, 8, ["filter", "modelValue"]);
        }), 256)),
        createBaseVNode("div", _hoisted_2$3, [
          createVNode(unref(T), {
            keyName: "filter_results",
            parameters: { filtered: __props.filteredMachines.length.toString(), total: __props.machines.length.toString(), all: (__props.filteredMachines.length === __props.machines.length).toString() }
          }, null, 8, ["parameters"])
        ])
      ]);
    };
  }
});
var Filter = /* @__PURE__ */ _export_sfc(_sfc_main$4, [["__scopeId", "data-v-8726e17a"]]);
const settingsKey = Symbol();
var Machine_vue_vue_type_style_index_0_lang = "";
const _hoisted_1$2 = {
  itemscope: "",
  itemtype: "https://schema.org/Product",
  class: "machine"
};
const _hoisted_2$2 = ["onClick", "href"];
const _hoisted_3$1 = ["src"];
const _hoisted_4$1 = { class: "machine_description" };
const _hoisted_5$1 = { itemprop: "name" };
const _hoisted_6$1 = {
  class: "machine_description_list",
  itemprop: "description"
};
const _hoisted_7$1 = { class: "machine_description_list_item" };
const _hoisted_8$1 = {
  itemprop: "offers",
  itemscope: "",
  itemtype: "https://schema.org/Offer",
  class: "machine_prices"
};
const _hoisted_9$1 = { class: "machine_price" };
const _hoisted_10$1 = { key: 0 };
const _hoisted_11$1 = {
  key: 0,
  class: "machine_price"
};
const _hoisted_12 = {
  key: 1,
  class: "machine_price machine_price--without-label"
};
const _hoisted_13 = ["onClick", "href"];
const _sfc_main$3 = /* @__PURE__ */ defineComponent({
  __name: "Machine",
  props: {
    machine: null
  },
  setup(__props) {
    const props = __props;
    const t = unref(useTranslate());
    const settings = inject(settingsKey, {
      decimals: 2
    });
    const saveURL = () => {
      window.location.assign(`${props.machine.link}#!`);
    };
    const formatPrice = (value) => {
      if (!value)
        return "";
      if (settings.decimals < 0) {
        const factor = Math.pow(10, Math.min(Math.abs(settings.decimals), Math.ceil(Math.log10(Math.abs(value)) - 1)));
        value = Math.round(value / factor) * factor;
      }
      const decimals = Math.max(0, settings.decimals);
      return value.toLocaleString("de-DE", {
        style: "currency",
        currency: "EUR",
        minimumFractionDigits: decimals,
        maximumFractionDigits: decimals
      });
    };
    const descriptionList = computed(() => {
      var _a2, _b, _c, _d;
      const machine = props.machine;
      return [
        { name: t("manufacture_date"), show: machine.year },
        { name: t("power"), show: machine.power ? `${machine.power.kW} kW (${machine.power.PS} PS)` : void 0 },
        { name: t("workhours"), show: (_a2 = machine.workhours) == null ? void 0 : _a2.show },
        { name: t("max_speed"), show: (_b = machine.max_speed) == null ? void 0 : _b.show },
        { name: t("work_width"), show: (_c = machine.work_width) == null ? void 0 : _c.show },
        ...[...(_d = machine == null ? void 0 : machine.additional) != null ? _d : []].filter((v) => !!v)
      ].filter(({ show }) => !!show).slice(0, 5);
    });
    return (_ctx, _cache) => {
      var _a2, _b, _c, _d;
      return openBlock(), createElementBlock("div", _hoisted_1$2, [
        createBaseVNode("a", {
          class: "machine_image",
          onClick: withModifiers(saveURL, ["prevent"]),
          href: __props.machine.link
        }, [
          __props.machine.images[0] ? (openBlock(), createElementBlock("img", {
            key: 0,
            src: __props.machine.images[0].href,
            itemprop: "image"
          }, null, 8, _hoisted_3$1)) : createCommentVNode("", true)
        ], 8, _hoisted_2$2),
        createBaseVNode("div", _hoisted_4$1, [
          createBaseVNode("h3", _hoisted_5$1, toDisplayString(`${__props.machine.manufacturer.value} ${__props.machine.model}`), 1),
          createBaseVNode("dl", _hoisted_6$1, [
            (openBlock(true), createElementBlock(Fragment, null, renderList(unref(descriptionList), ({ name, show }) => {
              return openBlock(), createElementBlock("div", _hoisted_7$1, [
                createBaseVNode("dt", null, toDisplayString(name), 1),
                createBaseVNode("dd", null, toDisplayString(show), 1)
              ]);
            }), 256))
          ])
        ]),
        createBaseVNode("div", _hoisted_8$1, [
          __props.machine.price.values && __props.machine.price.values.netto ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
            createBaseVNode("div", _hoisted_9$1, [
              createBaseVNode("small", null, [
                createVNode(unref(T), { keyName: "netto_label" })
              ]),
              ((_a2 = __props.machine.price.values) == null ? void 0 : _a2.old) ? (openBlock(), createElementBlock("del", _hoisted_10$1, toDisplayString(formatPrice((_b = __props.machine.price.values) == null ? void 0 : _b.old)), 1)) : createCommentVNode("", true),
              createBaseVNode("span", null, toDisplayString(formatPrice((_c = __props.machine.price.values) == null ? void 0 : _c.netto)), 1)
            ]),
            __props.machine.vat.separable && __props.machine.vat.value > 0 ? (openBlock(), createElementBlock("div", _hoisted_11$1, [
              createBaseVNode("small", null, [
                createVNode(unref(T), { keyName: "brutto_label" })
              ]),
              createBaseVNode("span", null, toDisplayString(formatPrice((_d = __props.machine.price.values) == null ? void 0 : _d.brutto)), 1)
            ])) : createCommentVNode("", true)
          ], 64)) : (openBlock(), createElementBlock("div", _hoisted_12, [
            createVNode(unref(T), { keyName: "price_on_request" })
          ]))
        ]),
        createBaseVNode("a", {
          class: "machine_button",
          onClick: withModifiers(saveURL, ["prevent"]),
          href: __props.machine.link
        }, [
          createVNode(unref(T), { keyName: "read_more" })
        ], 8, _hoisted_13)
      ]);
    };
  }
});
var Pagination_vue_vue_type_style_index_0_scoped_true_lang = "";
const _withScopeId = (n) => (pushScopeId("data-v-00237303"), n = n(), popScopeId(), n);
const _hoisted_1$1 = { "aria-label": "Machine Navigation" };
const _hoisted_2$1 = {
  key: 0,
  class: "pagination"
};
const _hoisted_3 = ["aria-disabled"];
const _hoisted_4 = /* @__PURE__ */ _withScopeId(() => /* @__PURE__ */ createBaseVNode("svg", {
  fill: "currentColor",
  viewBox: "0 0 20 20",
  xmlns: "http://www.w3.org/2000/svg"
}, [
  /* @__PURE__ */ createBaseVNode("path", {
    "fill-rule": "evenodd",
    d: "M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z",
    "clip-rule": "evenodd"
  })
], -1));
const _hoisted_5 = [
  _hoisted_4
];
const _hoisted_6 = ["aria-disabled"];
const _hoisted_7 = ["onClick"];
const _hoisted_8 = { key: 1 };
const _hoisted_9 = ["aria-disabled"];
const _hoisted_10 = /* @__PURE__ */ _withScopeId(() => /* @__PURE__ */ createBaseVNode("svg", {
  fill: "currentColor",
  viewBox: "0 0 20 20",
  xmlns: "http://www.w3.org/2000/svg"
}, [
  /* @__PURE__ */ createBaseVNode("path", {
    "fill-rule": "evenodd",
    d: "M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z",
    "clip-rule": "evenodd"
  })
], -1));
const _hoisted_11 = [
  _hoisted_10
];
const _sfc_main$2 = /* @__PURE__ */ defineComponent({
  __name: "Pagination",
  props: {
    currentPage: null,
    pages: null,
    pageSize: null,
    setPage: null
  },
  setup(__props) {
    const props = __props;
    const paddingPages = 3;
    const pagination = computed(() => {
      const paginationSize = Math.min(paddingPages * 2 + 1, props.pages);
      return [...Array(paginationSize).keys()].map((v) => {
        const page = Math.max(v + (Math.max(1, props.currentPage - paddingPages) - Math.max(0, props.currentPage + paddingPages - props.pages)), v + 1);
        if (props.currentPage > paddingPages && v === 0)
          return void 0;
        if (props.currentPage < props.pages - paddingPages && v === paginationSize - 1)
          return void 0;
        return page;
      });
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("nav", _hoisted_1$1, [
        unref(pagination) ? (openBlock(), createElementBlock("ul", _hoisted_2$1, [
          createBaseVNode("li", {
            class: "pagination-item",
            onClick: _cache[0] || (_cache[0] = ($event) => __props.setPage(__props.currentPage - 1)),
            "aria-disabled": __props.currentPage === 1
          }, _hoisted_5, 8, _hoisted_3),
          (openBlock(true), createElementBlock(Fragment, null, renderList(unref(pagination), (page) => {
            return openBlock(), createElementBlock("li", {
              class: normalizeClass(["pagination-item", { active: page === __props.currentPage }]),
              "aria-disabled": typeof page !== "number"
            }, [
              typeof page === "number" ? (openBlock(), createElementBlock("a", {
                key: 0,
                onClick: ($event) => __props.setPage(page)
              }, toDisplayString(page), 9, _hoisted_7)) : (openBlock(), createElementBlock("span", _hoisted_8, "\u2026"))
            ], 10, _hoisted_6);
          }), 256)),
          createBaseVNode("li", {
            class: "pagination-item",
            onClick: _cache[1] || (_cache[1] = ($event) => __props.setPage(__props.currentPage + 1)),
            "aria-disabled": __props.currentPage === __props.pages
          }, _hoisted_11, 8, _hoisted_9)
        ])) : createCommentVNode("", true)
      ]);
    };
  }
});
var Pagination = /* @__PURE__ */ _export_sfc(_sfc_main$2, [["__scopeId", "data-v-00237303"]]);
var Market_vue_vue_type_style_index_0_scoped_true_lang = "";
const _hoisted_1 = { class: "market" };
const _hoisted_2 = { class: "item_list" };
const _sfc_main$1 = /* @__PURE__ */ defineComponent({
  __name: "Market",
  props: {
    machines: null,
    pageSize: null,
    settings: null
  },
  setup(__props) {
    const props = __props;
    const state = reactive({
      page: 1,
      filter: {
        freetext: { value: null },
        manufacture_date: { value: [null, null] },
        workhours: { value: [null, null] },
        manufacturer: { value: null },
        model: { value: null },
        category: { value: null },
        location: { value: null },
        condition: { value: null },
        power: { value: [null, null] },
        price: { value: [null, null] }
      }
    });
    if (isHistoryStateValid(state)) {
      Object.assign(state, { ...window.history.state });
    }
    const pages = computed(() => {
      return Math.ceil(filteredMachines.value.length / props.pageSize);
    });
    const setPage = (page) => {
      state.page = Math.max(1, Math.min(pages.value, page));
    };
    const filteredMachines = computed(() => {
      return props.machines.filter((machine) => filterMachines(machine, state.filter));
    });
    const paginatedMachines = computed(() => {
      window.history.replaceState({
        ...JSON.parse(JSON.stringify(state))
      }, "null", "");
      return filteredMachines.value.slice((state.page - 1) * props.pageSize, state.page * props.pageSize);
    });
    provide("settings", props.settings);
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1, [
        createBaseVNode("div", null, [
          createVNode(Filter, {
            machines: __props.machines,
            filteredMachines: unref(filteredMachines),
            modelValue: state.filter,
            "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => state.filter = $event),
            onInput: _cache[1] || (_cache[1] = ($event) => setPage(0))
          }, null, 8, ["machines", "filteredMachines", "modelValue"]),
          createVNode(Pagination, {
            "set-page": setPage,
            "page-size": __props.pageSize,
            "current-page": state.page,
            pages: unref(pages)
          }, null, 8, ["page-size", "current-page", "pages"])
        ]),
        createBaseVNode("div", _hoisted_2, [
          (openBlock(true), createElementBlock(Fragment, null, renderList(unref(paginatedMachines), (machine) => {
            return openBlock(), createBlock(_sfc_main$3, {
              machine,
              key: machine.id
            }, null, 8, ["machine"]);
          }), 128))
        ]),
        createBaseVNode("div", null, [
          createVNode(Pagination, {
            "set-page": setPage,
            "page-size": __props.pageSize,
            "current-page": state.page,
            pages: unref(pages)
          }, null, 8, ["page-size", "current-page", "pages"])
        ])
      ]);
    };
  }
});
var MarketIndex = /* @__PURE__ */ _export_sfc(_sfc_main$1, [["__scopeId", "data-v-1beafe9e"]]);
var base = "";
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "App",
  props: {
    machines: null,
    pageSize: null,
    settings: null,
    lang: null
  },
  setup(__props) {
    var _a2;
    const props = __props;
    const config = {
      apiUrl: {}.VITE_TOLGEE_API_URL,
      apiKey: {}.VITE_TOLGEE_API_KEY,
      forceLanguage: (_a2 = props.lang) != null ? _a2 : "de",
      fallbackLanguage: "en",
      staticData: {
        en: () => import("./en.js"),
        de: () => import("./de.js"),
        es: () => import("./es.js"),
        fr: () => import("./fr.js"),
        tr: () => import("./tr.js"),
        it: () => import("./it.js"),
        ru: () => import("./ru.js")
      }
    };
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(TolgeeProvider), { config }, {
        default: withCtx(() => [
          createVNode(MarketIndex, {
            machines: props.machines,
            "page-size": props.pageSize,
            settings: props.settings
          }, null, 8, ["machines", "page-size", "settings"])
        ]),
        _: 1
      });
    };
  }
});
function lib(target, props) {
  createApp(_sfc_main, { ...props }).mount(target);
}
export { lib as default };
